dsh-team-bots 0.2.289 → 0.2.347

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 (119) hide show
  1. package/README.md +60 -122
  2. package/docs/README.zh.md +61 -123
  3. package/docs/assets/channel-redesign.png +0 -0
  4. package/docs/assets/global-config-dark.png +0 -0
  5. package/docs/assets/global-config-light.png +0 -0
  6. package/docs/assets/global-config-light.zh.png +0 -0
  7. package/docs/assets/global-config-redesign.png +0 -0
  8. package/docs/assets/secrets-redesign.png +0 -0
  9. package/docs/assets/tasks.png +0 -0
  10. package/docs/assets/tasks.zh.png +0 -0
  11. package/docs/assets/usage-redesign-global.png +0 -0
  12. package/docs/assets/usage.png +0 -0
  13. package/docs/assets/usage.zh.png +0 -0
  14. package/package.json +17 -5
  15. package/scripts/doctor.mjs +4 -4
  16. package/src/api.js +6 -3
  17. package/src/botmsg.js +1 -1
  18. package/src/config.js +18 -8
  19. package/src/db-migrations.js +76 -9
  20. package/src/db.js +28 -2
  21. package/src/http.js +22 -3
  22. package/src/paths.js +32 -1
  23. package/src/pricing.js +2 -2
  24. package/src/runtime.js +1 -1
  25. package/src/secrets.js +4 -4
  26. package/src/service.js +14 -5
  27. package/src/services/approvals.js +109 -24
  28. package/src/services/backoff.js +34 -0
  29. package/src/services/bot-quota.js +242 -0
  30. package/src/services/bots.js +35 -6
  31. package/src/services/chat.js +15 -9
  32. package/src/services/core.js +33 -5
  33. package/src/services/hygiene.js +8 -4
  34. package/src/services/locale.js +17 -0
  35. package/src/services/memory.js +112 -1
  36. package/src/services/message-images.js +3 -3
  37. package/src/services/notify.js +169 -0
  38. package/src/services/projects.js +119 -10
  39. package/src/services/proposals.js +2 -3
  40. package/src/services/questions.js +75 -32
  41. package/src/services/review-watchdog.js +261 -30
  42. package/src/services/run-finish.js +186 -17
  43. package/src/services/runs.js +42 -13
  44. package/src/services/runtime/lifecycle.js +3 -1
  45. package/src/services/runtime/model-restore.js +5 -5
  46. package/src/services/runtime/prompt.js +106 -45
  47. package/src/services/runtime/session.js +38 -14
  48. package/src/services/runtime/trajectory.js +1 -1
  49. package/src/services/scheduler.js +146 -19
  50. package/src/services/secrets.js +1 -1
  51. package/src/services/system.js +23 -6
  52. package/src/services/task-dispatch.js +315 -0
  53. package/src/services/task-notify.js +55 -11
  54. package/src/services/task-runs.js +179 -0
  55. package/src/services/task-stage.js +4 -0
  56. package/src/services/tasks.js +51 -399
  57. package/src/services/terminal.js +2 -2
  58. package/src/services/vision-proxy.js +3 -3
  59. package/src/services/wechat.js +228 -7
  60. package/src/services/workspace-groups.js +4 -3
  61. package/src/skill-parse.js +1 -1
  62. package/src/skills.js +1 -1
  63. package/src/tools.js +275 -6
  64. package/src/updater.js +52 -0
  65. package/src/usage-reconcile.js +1 -1
  66. package/src/usage.js +52 -11
  67. package/src/wechat/channel.js +14 -20
  68. package/src/wechat/commands.js +129 -81
  69. package/src/wechat/format.js +247 -0
  70. package/src/wechat/store.js +30 -2
  71. package/ui/app.js +57 -53
  72. package/ui/i18n/en/chat.js +140 -0
  73. package/ui/i18n/en/common.js +187 -0
  74. package/ui/i18n/en/nav.js +89 -0
  75. package/ui/i18n/en/settings.js +352 -0
  76. package/ui/i18n/en/tasks.js +229 -0
  77. package/ui/i18n/en/usage.js +141 -0
  78. package/ui/i18n/en/wechat.js +23 -0
  79. package/ui/i18n/en.js +17 -237
  80. package/ui/i18n/zh/chat.js +140 -0
  81. package/ui/i18n/zh/common.js +187 -0
  82. package/ui/i18n/zh/nav.js +89 -0
  83. package/ui/i18n/zh/settings.js +352 -0
  84. package/ui/i18n/zh/tasks.js +229 -0
  85. package/ui/i18n/zh/usage.js +141 -0
  86. package/ui/i18n/zh/wechat.js +23 -0
  87. package/ui/i18n/zh.js +17 -236
  88. package/ui/modules/api.js +4 -3
  89. package/ui/modules/bot-quota.js +27 -0
  90. package/ui/modules/cards.js +96 -58
  91. package/ui/modules/chat.js +28 -30
  92. package/ui/modules/composer.js +41 -37
  93. package/ui/modules/dom-morph.js +292 -0
  94. package/ui/modules/events-board.js +22 -22
  95. package/ui/modules/events-click.js +100 -68
  96. package/ui/modules/events-misc.js +34 -34
  97. package/ui/modules/events-submit.js +28 -28
  98. package/ui/modules/global-pages.js +125 -116
  99. package/ui/modules/i18n.js +0 -5
  100. package/ui/modules/icons.js +0 -1
  101. package/ui/modules/markdown.js +1 -1
  102. package/ui/modules/modal-forms.js +196 -203
  103. package/ui/modules/modal-layer.js +6 -9
  104. package/ui/modules/page-shell.js +62 -0
  105. package/ui/modules/settings.js +211 -198
  106. package/ui/modules/solo-archive.js +0 -4
  107. package/ui/modules/state.js +57 -50
  108. package/ui/modules/tasks.js +167 -171
  109. package/ui/modules/typing-linger.js +1 -4
  110. package/ui/modules/usage.js +65 -78
  111. package/ui/modules/util.js +92 -25
  112. package/ui/styles/avatars.css +14 -0
  113. package/ui/styles/cards.css +49 -0
  114. package/ui/styles/chat-cards.css +17 -21
  115. package/ui/styles/global-config.css +56 -2
  116. package/ui/styles/modal.css +13 -0
  117. package/ui/styles/usage.css +3 -61
  118. package/CONTRIBUTING.md +0 -20
  119. package/docs/assets/usage-dark.png +0 -0
@@ -1,8 +1,6 @@
1
- // composer.js —— 输入区域:@ 自动补全、草稿、图片附件、消息图片渲染与查看器、
2
- // 输入框高度自适应、发送消息与任务表单提交。
3
1
  import { state } from './state.js'
4
2
  import { icon } from './icons.js'
5
- import { activeProject, attr, avatar, botById, esc, initials, toast } from './util.js'
3
+ import { activeProject, attr, avatar, botById, esc, toast } from './util.js'
6
4
  import { api, loadState } from './api.js'
7
5
  import { applyOptimisticTyping } from './typing-linger.js'
8
6
  import { t } from './i18n.js'
@@ -11,9 +9,9 @@ import { flushAppRender } from './modal-layer.js'
11
9
 
12
10
  // ac-core:start —— 输入框 / 与 @ 自动补全的纯逻辑(tests/ac.test.js 抽取此块断言)
13
11
  const AC_COMMANDS = [
14
- { kind: 'command', label: '/task', title: '派任务', desc: '创建任务并排队执行:/task @成员 标题', insert: '/task @', then: 'mention' },
15
- { kind: 'command', label: '/remember', title: '写项目记忆', desc: '写入项目级记忆:/remember 内容', insert: '/remember ' },
16
- { kind: 'command', label: '/clear', title: '清空聊天', desc: '清空本群全部聊天记录(任务与记忆保留)', insert: '/clear' },
12
+ { kind: 'command', label: '/task', title: t("派任务"), desc: t("创建任务并排队执行:/task @成员 标题"), insert: '/task @', then: 'mention' },
13
+ { kind: 'command', label: '/remember', title: t("写项目记忆"), desc: t("写入项目级记忆:/remember 内容"), insert: '/remember ' },
14
+ { kind: 'command', label: '/clear', title: t("清空聊天"), desc: t("清空本群全部聊天记录(任务与记忆保留)"), insert: '/clear' },
17
15
  ]
18
16
  const acWordChar = (ch) => ch !== undefined && !/[\s@/]/.test(ch)
19
17
 
@@ -47,14 +45,14 @@ function buildAcItems(mode, query, sources) {
47
45
  for (const skill of sources.skills ?? []) {
48
46
  if (hit(skill.slug) || hit(skill.name)) items.push({
49
47
  kind: 'skill', label: `/${skill.slug}`, title: skill.name || skill.slug,
50
- desc: skill.description || '共享技能', insert: `/${skill.slug} `,
48
+ desc: skill.description || t("共享技能"), insert: `/${skill.slug} `,
51
49
  })
52
50
  }
53
51
  } else {
54
52
  for (const member of sources.members ?? []) {
55
53
  if (hit(member.name) || hit(member.role)) items.push({
56
54
  kind: 'member', label: `@${member.name}`, title: member.name, color: member.color,
57
- desc: member.owner ? `总监 · ${member.role || '成员'}` : (member.role || '成员'),
55
+ desc: member.owner ? `${t("总监")} · ${member.role || t("成员")}` : (member.role || t("成员")),
58
56
  insert: `@${member.name} `,
59
57
  })
60
58
  }
@@ -82,7 +80,7 @@ function acSources() {
82
80
  }
83
81
 
84
82
  function updateAutocomplete() {
85
- const input = document.getElementById('composer-input')
83
+ const input = document.getElementById('composer-input')
86
84
  const popup = document.getElementById('composer-ac')
87
85
  if (!input || !popup) { state.ac = null; return }
88
86
  const token = input === document.activeElement ? detectAcToken(input.value, input.selectionStart) : null
@@ -104,13 +102,13 @@ function renderAcPopup(popup, session) {
104
102
  }
105
103
  popup.innerHTML = session.items.map((item, index) => {
106
104
  const glyph = item.kind === 'member'
107
- ? `<span class="avatar sm ${attr(item.color || 'gray')}">${esc(initials(item.title))}</span>`
105
+ ? avatar({ name: item.title, color: item.color }, 'sm')
108
106
  : `<span class="composer-ac-glyph">${icon(item.kind === 'skill' ? 'spark' : 'terminal')}</span>`
109
107
  return `<button type="button" class="composer-ac-item${index === session.selected ? ' active' : ''}" role="option" aria-selected="${index === session.selected}" data-ac-idx="${index}" id="composer-ac-item-${index}">
110
108
  ${glyph}
111
109
  <span class="composer-ac-text"><strong>${esc(item.label)}</strong><span>${esc(item.desc)}</span></span>
112
110
  </button>`
113
- }).join('') + `<div class="composer-ac-hint">↑↓ 选择 · Enter 或 Tab 插入 · Esc 关闭</div>`
111
+ }).join('') + `<div class="composer-ac-hint">↑↓ ${t("选择 · Enter 或 Tab 插入 · Esc 关闭")}</div>`
114
112
  popup.hidden = false
115
113
  const active = popup.querySelector('.composer-ac-item.active')
116
114
  if (active && input) input.setAttribute('aria-activedescendant', active.id)
@@ -131,7 +129,7 @@ function closeAutocomplete() {
131
129
  }
132
130
 
133
131
  function applyAutocomplete(item) {
134
- const input = document.getElementById('composer-input')
132
+ const input = document.getElementById('composer-input')
135
133
  if (!input || !item || !state.ac) return
136
134
  const { from, to } = state.ac
137
135
  input.value = input.value.slice(0, from) + item.insert + input.value.slice(to)
@@ -182,20 +180,20 @@ function validateImageSelection(files, existingCount = 0) {
182
180
  const accepted = []
183
181
  const rejected = []
184
182
  let count = Number(existingCount) || 0
185
- for (const file of Array.from(files ?? [])) {
183
+ for (const file of Array.from(files ?? []) ) {
186
184
  const name = file?.name ?? ''
187
185
  const mediaType = resolveImageMediaType(file?.type, name)
188
186
  if (!mediaType) {
189
- rejected.push({ name, reason: '仅支持 PNG / JPEG / GIF / WebP 格式' })
187
+ rejected.push({ name, reason: t("仅支持 PNG / JPEG / GIF / WebP 格式") })
190
188
  continue
191
189
  }
192
190
  const bytes = Number(file?.size) || 0
193
191
  if (bytes > MAX_IMAGE_BYTES) {
194
- rejected.push({ name, reason: '单张图片不能超过 5MB' })
192
+ rejected.push({ name, reason: t("单张图片不能超过 5MB") })
195
193
  continue
196
194
  }
197
195
  if (count >= MAX_IMAGES_PER_MESSAGE) {
198
- rejected.push({ name, reason: `一条消息最多 ${MAX_IMAGES_PER_MESSAGE} 张图片` })
196
+ rejected.push({ name, reason: t("一条消息最多 ${MAX_IMAGES_PER_MESSAGE} 张图片", { MAX_IMAGES_PER_MESSAGE: MAX_IMAGES_PER_MESSAGE }) })
199
197
  continue
200
198
  }
201
199
  count += 1
@@ -233,7 +231,7 @@ function readFileAsBase64(file) {
233
231
  const comma = result.indexOf(',')
234
232
  resolve(comma >= 0 ? result.slice(comma + 1) : result)
235
233
  }
236
- reader.onerror = () => reject(new Error('读取失败'))
234
+ reader.onerror = () => reject(new Error(t("读取失败")))
237
235
  reader.readAsDataURL(file)
238
236
  })
239
237
  }
@@ -315,7 +313,7 @@ function thumbnailFallback(name, iconHtml, doc = document) {
315
313
  glyph.innerHTML = iconHtml
316
314
  const label = doc.createElement('span')
317
315
  label.className = 'image-thumb-fallback-name'
318
- label.textContent = String(name || '图片预览不可用')
316
+ label.textContent = String(name || t("图片预览不可用"))
319
317
  wrap.append(glyph, label)
320
318
  return wrap
321
319
  }
@@ -326,7 +324,7 @@ function thumbnailFallback(name, iconHtml, doc = document) {
326
324
  // change 落在已脱离 document 的旧节点上,document 级委托收不到(DSHBOTS-64 根因)。
327
325
  // 挂在 body 上只建一次,任何重渲染都动不了它,change 始终能冒泡到委托层。
328
326
  function ensureComposerImageInput(doc = document) {
329
- let el = doc.getElementById('composer-image-input')
327
+ let el = doc.getElementById('composer-image-input')
330
328
  if (el) return el
331
329
  el = doc.createElement('input')
332
330
  el.id = 'composer-image-input'
@@ -412,11 +410,11 @@ function renderMessageImages(images) {
412
410
  return `<div class="msg-images">${list.map(image => {
413
411
  const thumbUrl = messageImageThumbUrls.get(image.id) ?? ''
414
412
  return `
415
- <button type="button" class="msg-image-tile" data-action="view-message-image" data-image-id="${attr(image.id)}" title="${attr(image.name || '查看原图')}">
413
+ <button type="button" class="msg-image-tile" data-action="view-message-image" data-image-id="${attr(image.id)}" title="${attr(image.name || t("查看原图"))}">
416
414
  ${thumbUrl
417
- ? `<img class="msg-image-thumb" src="${attr(thumbUrl)}" alt="${attr(image.name || '图片')}" />`
415
+ ? `<img class="msg-image-thumb" src="${attr(thumbUrl)}" alt="${attr(image.name || t("图片"))}" />`
418
416
  : `<span class="msg-image-icon">${icon('image')}</span>`}
419
- <span class="msg-image-meta"><span class="msg-image-name">${esc(image.name || '图片')}</span><span class="msg-image-size">${esc(formatImageBytes(image.bytes))}</span></span>
417
+ <span class="msg-image-meta"><span class="msg-image-name">${esc(image.name || t("图片"))}</span><span class="msg-image-size">${esc(formatImageBytes(image.bytes))}</span></span>
420
418
  </button>`
421
419
  }).join('')}</div>`
422
420
  }
@@ -424,7 +422,7 @@ function renderMessageImages(images) {
424
422
  // 渲染后补缩略图:模板已同步嵌缓存命中者,这里只处理未命中的瓦片——异步取图并原位替换图标占位;
425
423
  // 取图失败保留占位(瓦片仍可点击,报错交给查看器路径兜底)。
426
424
  async function hydrateMessageImageThumbs(root = document) {
427
- const tiles = Array.from(root.querySelectorAll('.msg-image-tile[data-image-id]'))
425
+ const tiles = Array.from(root.querySelectorAll('.msg-image-tile[data-image-id]') )
428
426
  await Promise.all(tiles.filter(tile => !tile.querySelector('.msg-image-thumb')).map(async tile => {
429
427
  const imageId = tile.dataset.imageId
430
428
  if (!imageId) return
@@ -433,7 +431,7 @@ async function hydrateMessageImageThumbs(root = document) {
433
431
  if (!tile.isConnected || tile.querySelector('.msg-image-thumb')) return
434
432
  const img = document.createElement('img')
435
433
  img.className = 'msg-image-thumb'
436
- img.alt = tile.querySelector('.msg-image-name')?.textContent || '图片'
434
+ img.alt = tile.querySelector('.msg-image-name')?.textContent || t("图片")
437
435
  img.src = url
438
436
  tile.querySelector('.msg-image-icon')?.replaceWith(img)
439
437
  } catch {}
@@ -449,11 +447,11 @@ function ensureImageViewer() {
449
447
  el.id = 'image-viewer'
450
448
  el.hidden = true
451
449
  el.innerHTML = `<div class="image-viewer-backdrop" data-action="close-image-viewer"></div>
452
- <div class="image-viewer-panel" role="dialog" aria-modal="true" aria-label="图片预览">
450
+ <div class="image-viewer-panel" role="dialog" aria-modal="true" aria-label="${t("图片预览")}">
453
451
  <div class="image-viewer-head">
454
452
  <strong id="image-viewer-name"></strong>
455
453
  <span class="faint" id="image-viewer-size"></span>
456
- <button type="button" class="image-viewer-close" data-action="close-image-viewer" title="关闭" aria-label="关闭图片预览">${icon('close')}</button>
454
+ <button type="button" class="image-viewer-close" data-action="close-image-viewer" title="${t("关闭")}" aria-label="${t("关闭图片预览")}">${icon('close')}</button>
457
455
  </div>
458
456
  <div class="image-viewer-body" id="image-viewer-body"></div>
459
457
  </div>`
@@ -468,28 +466,28 @@ async function openMessageImage(imageId) {
468
466
  const nameEl = document.getElementById('image-viewer-name')
469
467
  const sizeEl = document.getElementById('image-viewer-size')
470
468
  viewer.hidden = false
471
- body.textContent = '图片加载中…'
469
+ body.textContent = t("图片加载中…")
472
470
  if (nameEl) nameEl.textContent = ''
473
471
  if (sizeEl) sizeEl.textContent = ''
474
472
  try {
475
473
  const image = await api('get_message_image', { imageId }, { quiet: true })
476
- if (nameEl) nameEl.textContent = image.name || '图片'
474
+ if (nameEl) nameEl.textContent = image.name || t("图片")
477
475
  if (sizeEl) sizeEl.textContent = formatImageBytes(image.bytes)
478
476
  body.textContent = ''
479
477
  const img = document.createElement('img')
480
478
  img.className = 'image-viewer-img'
481
- img.alt = image.name || '图片'
479
+ img.alt = image.name || t("图片")
482
480
  img.src = base64BlobUrl(image.data, image.mediaType)
483
481
  body.appendChild(img)
484
- } catch (error) {
485
- body.textContent = error?.message || '图片加载失败'
482
+ } catch (error ) {
483
+ body.textContent = error?.message || t("图片加载失败")
486
484
  }
487
485
  }
488
486
 
489
487
  function closeImageViewer() {
490
488
  const viewer = document.getElementById('image-viewer')
491
489
  if (!viewer || viewer.hidden) return
492
- const img = viewer.querySelector('.image-viewer-img')
490
+ const img = viewer.querySelector('.image-viewer-img')
493
491
  if (img?.src) {
494
492
  try { URL.revokeObjectURL(img.src) } catch {}
495
493
  img.removeAttribute('src')
@@ -514,7 +512,7 @@ function openInlineImage(img) {
514
512
  name = url.searchParams.get('path')?.split('/').pop() ?? url.pathname.split('/').pop() ?? ''
515
513
  } catch { name = '' }
516
514
  }
517
- if (!name) name = '图片'
515
+ if (!name) name = t("图片")
518
516
  document.getElementById('image-viewer-name').textContent = name
519
517
  document.getElementById('image-viewer-size').textContent = ''
520
518
  viewer.hidden = false
@@ -559,7 +557,7 @@ function applyComposerHeight(input) {
559
557
  function syncComposerBox(input) {
560
558
  state.chatDrafts[draftKey(state)] = input.value
561
559
  applyComposerHeight(input)
562
- const button = document.querySelector('[data-action="send-message"]')
560
+ const button = document.querySelector('[data-action="send-message"]')
563
561
  if (button) button.disabled = input.value.trim() === '' && pendingImagesFor().length === 0
564
562
  }
565
563
 
@@ -583,7 +581,7 @@ async function sendMessage() {
583
581
  const project = solo ? null : activeProject()
584
582
  if (solo ? !bot : !project) return
585
583
  // 命令类消息保留原 confirm 拦截语义:取消即整体退出,草稿与附件原样不动。
586
- if (body === '/clear' && !window.confirm(solo ? `清空和 ${bot.name} 的全部对话记录?清除后不可恢复(记忆保留)。` : '清空本群全部聊天记录?清除后不可恢复(任务与记忆保留)。')) return
584
+ if (body === '/clear' && !window.confirm(solo ? `${t("清空和")} ${bot.name} ${t("的全部对话记录?清除后不可恢复(记忆保留)。")}` : t("清空本群全部聊天记录?清除后不可恢复(任务与记忆保留)。"))) return
587
585
  // 待发图片随消息一起出站:mediaType + name + base64,字段口径与后端 normalizeImageInputs 一致。
588
586
  const images = pending.map(item => ({ mediaType: item.mediaType, name: item.name, data: item.data }))
589
587
  const key = draftKey(state)
@@ -599,6 +597,12 @@ async function sendMessage() {
599
597
  state.chatAtBottom = true
600
598
  clearPendingImages()
601
599
  render()
600
+ // DOM 值显式清空(DSHBOTS-244):morph 复用持焦 textarea 时,syncFormValue 按「聚焦中控件的
601
+ // 值归用户管」不覆写 .value,state 已清而 DOM 残留;render 的 rAF 里 syncComposerBox 还会把
602
+ // 残值回写复活 state 草稿(失败恢复串随之叠加 "body\nbody")。render 后取节点收敛唯一出口:
603
+ // 复用路径清掉残留,全量重建路径对新节点幂等。⌘Enter/发送按钮/补全回车三入口同经此处。
604
+ const box = document.getElementById('composer-input')
605
+ if (box) box.value = ''
602
606
  let result
603
607
  if (solo) {
604
608
  result = await api('send_solo_message', { botId: bot.id, body, ...(images.length ? { images } : {}) })
@@ -645,8 +649,8 @@ async function sendMessage() {
645
649
  }
646
650
 
647
651
  async function saveTaskFromForm(taskId) {
648
- const form = document.getElementById('task-form')
649
- if (!form) throw new Error('保存失败,请重试。')
652
+ const form = document.getElementById('task-form')
653
+ if (!form) throw new Error(t("保存失败,请重试。"))
650
654
  const formData = new FormData(form)
651
655
  const assignee = formData.get('assigneeBotId')
652
656
  await api('update_task', {
@@ -0,0 +1,292 @@
1
+ // dom-morph —— #app 稳定节点原位补丁(DSHBOTS-227)
2
+ // 轮询每 2.8s 把整页 innerHTML 重建一次,节点全部换新:CSS 动画从头重启(看板进行中的
3
+ // 鱼尾/微光每拍抽一下)、composer 的 textarea 被拆走(输入框闪)、聚焦中的 <select> 被拆走
4
+ // (原生下拉弹层直接关闭,选不中项)。这里改成「按身份键复用现有节点、只写真正变了的东西」:
5
+ // 结构没变即零 DOM 操作,变了的只改属性与文本,节点身份连同动画相位、焦点、滚动位一起活下来。
6
+ //
7
+ // 复用规则(宁可少动,不可动错):
8
+ // 1) 同一位置的同标签节点算「同一身份」——先按 key(id / data-task-id / data-panel 等)配对,
9
+ // 未带 key 的再按位置与标签配对;配不上的新节点插入,配不上的旧节点删除。
10
+ // 2) 表单控件只同步值,不重建子树;聚焦中的控件不覆写用户手上的值;聚焦中的 <select>
11
+ // 连 option 都不动(动 option 会关掉原生弹层)。
12
+ // 3) 运行期由 JS 加的东西不清:data-dirty 属性、拖拽态 class、行内 style 只做叠加合并。
13
+ // 4) 需要「搬动或删除正在持有焦点的节点」才能成立的重排,整页放弃补丁回退全量重建
14
+ // ——顺序与正确性优先于保焦点;morph() 自己兜底,调用方只管一行。
15
+
16
+ // morph-keys:start —— 身份键与子节点合并计划的纯逻辑(tests/dom-morph.test.ts 抽取本块断言)
17
+ // 模板里携带业务身份的 data-* 依次优先;没有键的静态节点走「同标签 + 同位置」。
18
+ const MORPH_KEY_ATTRS = [
19
+ 'data-panel', 'data-task-id', 'data-run-id', 'data-bot-id', 'data-project-id',
20
+ 'data-memory-id', 'data-proposal-id', 'data-question-id', 'data-approval-id',
21
+ 'data-image-key', 'data-bubble-key', 'data-task-filter', 'data-task-sort',
22
+ 'data-drop-status', 'data-tree', 'data-view', 'data-slug', 'data-section',
23
+ 'data-picker-for', 'data-revision-id', 'data-item-id', 'data-command-id',
24
+ ]
25
+
26
+ function morphKey(el) {
27
+ if (!el || el.nodeType !== 1 || !el.getAttribute) return null
28
+ const id = el.getAttribute('id')
29
+ if (id) return `#${id}`
30
+ for (const name of MORPH_KEY_ATTRS) {
31
+ const value = el.getAttribute(name)
32
+ if (value != null && value !== '') return `${name}=${value}`
33
+ }
34
+ return null
35
+ }
36
+
37
+ function morphTag(el) {
38
+ if (!el) return ''
39
+ if (el.nodeType === 3) return '#text'
40
+ if (el.nodeType === 8) return '#comment'
41
+ return String(el.tagName ?? '').toUpperCase()
42
+ }
43
+
44
+ function morphDescriptor(el) {
45
+ return { node: el, key: morphKey(el), tag: morphTag(el) }
46
+ }
47
+
48
+ // 子节点合并计划:liveItems/freshItems 为同序 descriptor 数组({node,key,tag})。
49
+ // entries 按 fresh 顺序给出落位方案(live=null 即需要插入新节点);removals 是没人认领的 live 节点。
50
+ function planChildren(liveItems, freshItems) {
51
+ const free = liveItems.map(item => ({ ...item, taken: false }))
52
+ const byKey = new Map()
53
+ for (const item of free) {
54
+ if (!item.key || byKey.has(item.key)) continue
55
+ byKey.set(item.key, item)
56
+ }
57
+ const entries = freshItems.map(fresh => ({ live: null, fresh }))
58
+ // 第一轮:身份键配对(标签不一致即不是同一身份,交给插入 + 删除)
59
+ for (const entry of entries) {
60
+ if (!entry.fresh.key) continue
61
+ const hit = byKey.get(entry.fresh.key)
62
+ if (hit && !hit.taken && hit.tag === entry.fresh.tag) {
63
+ hit.taken = true
64
+ entry.live = hit
65
+ }
66
+ }
67
+ // 第二轮:无键节点按同位置配对(模板结构没变即整树原位复用)
68
+ for (let index = 0; index < entries.length; index += 1) {
69
+ const entry = entries[index]
70
+ if (entry.live || entry.fresh.key) continue
71
+ const cand = free[index]
72
+ if (cand && !cand.taken && !cand.key && cand.tag === entry.fresh.tag) {
73
+ cand.taken = true
74
+ entry.live = cand
75
+ }
76
+ }
77
+ const removals = free.filter(item => !item.taken)
78
+ return { entries, removals }
79
+ }
80
+ // morph-keys:end
81
+
82
+ // morph-attrs:start —— 属性/类/样式/表单值的同步策略纯逻辑(tests/dom-morph.test.ts 抽取本块断言)
83
+ // 运行期由 JS 写上的属性与 class 不归模板管:data-dirty 是「表单有未保存修改」的轮询闸门信号,
84
+ // dragging/drop-target 是一次拖拽的中间态,删掉就等于打断正在进行的动作。
85
+ const MORPH_PRESERVE_ATTRS = new Set(['data-dirty'])
86
+ const MORPH_PRESERVE_CLASSES = new Set(['dragging', 'drop-target'])
87
+ // 秒级定时器维护的 class(倒计时临期色):模板算出的时刻可能比上一拍定时器旧,
88
+ // 保留旧值等下一拍校正,免得临期色被抹掉再闪回来。
89
+ const MORPH_SOFT_CLASSES = new Set(['urgent'])
90
+ // 表单控件的值是 IDL 属性不是内容属性:value/checked/selected 走专门的值同步通道,
91
+ // 通用属性写入改不动用户手上的当前值,反而会污染默认值。
92
+ const MORPH_VALUE_ATTRS = new Set(['value', 'checked', 'selected'])
93
+
94
+ function mergeClass(freshClass, liveClass) {
95
+ const freshTokens = String(freshClass ?? '').split(/\s+/).filter(Boolean)
96
+ const liveTokens = String(liveClass ?? '').split(/\s+/).filter(Boolean)
97
+ const out = [...freshTokens]
98
+ for (const token of liveTokens) {
99
+ if (freshTokens.includes(token)) continue
100
+ if (MORPH_PRESERVE_CLASSES.has(token) || MORPH_SOFT_CLASSES.has(token)) out.push(token)
101
+ }
102
+ return out.join(' ')
103
+ }
104
+
105
+ // 行内样式只叠加不清空:composer 高度、终态气泡淡出 opacity、进度条宽度都是 JS 写的。
106
+ // 入参是 fresh 声明的 [[prop, value]] 列表(模板侧的期望值),原样交回给写入方。
107
+ function stylePatch(freshDecls) {
108
+ return Array.from(freshDecls ?? [])
109
+ }
110
+
111
+ // 目标值:从模板节点算出「这一拍应有的值」;null 表示这个标签不管值。
112
+ function desiredFormValue(fresh, tag) {
113
+ if (tag === 'TEXTAREA') return { kind: 'value', value: fresh.textContent ?? '' }
114
+ if (tag === 'SELECT') {
115
+ const options = [...(fresh.children ?? [])].filter(node => node.tagName === 'OPTION')
116
+ const chosen = options.find(node => node.hasAttribute('selected')) ?? options[0] ?? null
117
+ if (!chosen) return null
118
+ const value = chosen.hasAttribute('value') ? chosen.getAttribute('value') : (chosen.textContent ?? '')
119
+ return { kind: 'value', value }
120
+ }
121
+ if (tag === 'INPUT') {
122
+ const type = String(fresh.getAttribute?.('type') ?? 'text').toLowerCase()
123
+ // file 输入的值只能由用户给:写 value(含清空)会抹掉刚选好还没提交的文件。
124
+ if (type === 'file') return null
125
+ if (type === 'checkbox' || type === 'radio') return { kind: 'checked', value: fresh.hasAttribute('checked') }
126
+ return { kind: 'value', value: fresh.getAttribute?.('value') ?? '' }
127
+ }
128
+ if (tag === 'OPTION') return { kind: 'selected', value: fresh.hasAttribute('selected') }
129
+ return null
130
+ }
131
+
132
+ // 是否继续向下补子树:控件的子节点大多是「默认值」本身,动它们等于改用户的输入;
133
+ // OPTION 的文本是标签(成员改名要跟着变)所以下得去;聚焦中的 SELECT 一律不下(弹层会关)。
134
+ function shouldDescend(tag, focused) {
135
+ if (['INPUT', 'TEXTAREA', 'PROGRESS', 'METER'].includes(tag)) return false
136
+ if (tag === 'SELECT') return !focused
137
+ return true
138
+ }
139
+ // morph-attrs:end
140
+
141
+ // 表单控件标签集:值走同步通道,子树按 shouldDescend 裁决。
142
+ const MORPH_FORM_TAGS = new Set(['INPUT', 'TEXTAREA', 'SELECT', 'OPTION', 'PROGRESS', 'METER'])
143
+
144
+ function hasFocusIn(node, doc) {
145
+ const active = doc.activeElement
146
+ if (!active || active === doc.body) return false
147
+ return node === active || Boolean(node.contains?.(active))
148
+ }
149
+
150
+ function freshStyleDecls(node) {
151
+ const style = node.style
152
+ if (!style) return []
153
+ const out = []
154
+ for (let i = 0; i < style.length; i += 1) {
155
+ const prop = style.item(i)
156
+ if (!prop) continue
157
+ out.push([prop, style.getPropertyValue(prop)])
158
+ }
159
+ return out
160
+ }
161
+
162
+ function syncAttributes(live, fresh) {
163
+ for (const attr of Array.from(fresh.attributes) ) {
164
+ if (attr.name === 'class' || attr.name === 'style' || MORPH_VALUE_ATTRS.has(attr.name)) continue
165
+ if (live.getAttribute(attr.name) !== attr.value) live.setAttribute(attr.name, attr.value)
166
+ }
167
+ for (const attr of Array.from(live.attributes) ) {
168
+ if (MORPH_PRESERVE_ATTRS.has(attr.name) || attr.name === 'class' || attr.name === 'style' || MORPH_VALUE_ATTRS.has(attr.name)) continue
169
+ if (!fresh.hasAttribute(attr.name)) live.removeAttribute(attr.name)
170
+ }
171
+ const merged = mergeClass(fresh.getAttribute('class'), live.getAttribute('class'))
172
+ if ((live.getAttribute('class') ?? '') !== merged) live.setAttribute('class', merged)
173
+ for (const [prop, value] of stylePatch(freshStyleDecls(fresh))) {
174
+ if (live.style.getPropertyValue(prop) !== value) live.style.setProperty(prop, value)
175
+ }
176
+ }
177
+
178
+ function syncFormValue(live, fresh, tag, doc) {
179
+ const desired = desiredFormValue(fresh, tag)
180
+ if (!desired) return
181
+ // 聚焦中的控件:值归用户管,不覆写(否则正在输入的内容与光标会被模板回滚)。
182
+ if (hasFocusIn(live, doc)) return
183
+ if (desired.kind === 'checked') {
184
+ if (live.checked !== desired.value) live.checked = desired.value
185
+ return
186
+ }
187
+ if (desired.kind === 'selected') {
188
+ if (live.selected !== desired.value) live.selected = desired.value
189
+ return
190
+ }
191
+ if (live.value !== desired.value) live.value = desired.value
192
+ }
193
+
194
+ // 返回是否继续向下补子树。
195
+ function patchElement(live, fresh, doc) {
196
+ syncAttributes(live, fresh)
197
+ const tag = morphTag(live)
198
+ if (MORPH_FORM_TAGS.has(tag)) syncFormValue(live, fresh, tag, doc)
199
+ return shouldDescend(tag, hasFocusIn(live, doc))
200
+ }
201
+
202
+ function patchNode(live, fresh, doc) {
203
+ if (live.nodeType === 3 || live.nodeType === 8) {
204
+ if (live.nodeValue !== fresh.nodeValue) live.nodeValue = fresh.nodeValue
205
+ return true
206
+ }
207
+ // 整棵子树的标签、属性与文本都相同即跳过:这是轮询最常见的路径,零 DOM 操作。
208
+ if (live.isEqualNode(fresh)) return true
209
+ if (!patchElement(live, fresh, doc)) return true
210
+ return patchChildren(live, fresh, doc)
211
+ }
212
+
213
+ function patchChildren(live, fresh, doc) {
214
+ const liveItems = Array.from(live.childNodes).map(morphDescriptor)
215
+ const freshItems = Array.from(fresh.childNodes).map(morphDescriptor)
216
+ const { entries, removals } = planChildren(liveItems, freshItems)
217
+ for (const item of removals) {
218
+ if (hasFocusIn(item.node, doc)) return false
219
+ live.removeChild(item.node)
220
+ }
221
+ let index = 0
222
+ for (const entry of entries) {
223
+ const desired = entry.live ? entry.live.node : entry.fresh.node.cloneNode(true)
224
+ const current = live.childNodes[index]
225
+ if (current !== desired) {
226
+ if (entry.live && hasFocusIn(entry.live.node, doc)) return false
227
+ live.insertBefore(desired, current ?? null)
228
+ }
229
+ index += 1
230
+ }
231
+ for (const entry of entries) {
232
+ if (!entry.live) continue
233
+ if (!patchNode(entry.live.node, entry.fresh.node, doc)) return false
234
+ }
235
+ return true
236
+ }
237
+
238
+ // patch(root, html):试着原位补成 html。false = 补不成(换页级结构变化、需要搬动/删除持焦节点),
239
+ // 调用方(morph)据此回退整页 innerHTML。
240
+ function firstElement(node) {
241
+ for (const child of Array.from(node.childNodes ?? []) ) {
242
+ if (child.nodeType === 1) return child
243
+ }
244
+ return null
245
+ }
246
+
247
+ function patch(root, html) {
248
+ const doc = root.ownerDocument ?? document
249
+ const stage = doc.createElement('template')
250
+ stage.innerHTML = html
251
+ // 壳层判定:模板首元素是 .shell,换标签或换类名即「换页级」变化(boot 屏 → 工作台等),
252
+ // 这种变化交给全量重建;空白文本节点不算元素,所以逐个找首个元素而不是看 childNodes.length。
253
+ const liveShell = firstElement(root)
254
+ const freshShell = firstElement(stage.content)
255
+ if (!liveShell || !freshShell) return false
256
+ if (liveShell.tagName !== freshShell.tagName) return false
257
+ if ((liveShell.getAttribute('class') ?? '') !== (freshShell.getAttribute('class') ?? '')) return false
258
+ return patchChildren(root, stage.content, doc)
259
+ }
260
+
261
+ // morph(root, html):保证 root 的内容与 html 一致——能原位补就补(节点身份、动画相位、
262
+ // 焦点与滚动位随之保留),补不动才整页重建。调用方一行接线,不必自己兜底。
263
+ function morph(root, html) {
264
+ if (patch(root, html)) return
265
+ root.innerHTML = html
266
+ }
267
+
268
+ export {
269
+ MORPH_KEY_ATTRS,
270
+ morphKey,
271
+ morphTag,
272
+ morphDescriptor,
273
+ planChildren,
274
+ MORPH_PRESERVE_ATTRS,
275
+ MORPH_PRESERVE_CLASSES,
276
+ MORPH_SOFT_CLASSES,
277
+ MORPH_VALUE_ATTRS,
278
+ MORPH_FORM_TAGS,
279
+ mergeClass,
280
+ stylePatch,
281
+ desiredFormValue,
282
+ shouldDescend,
283
+ hasFocusIn,
284
+ freshStyleDecls,
285
+ syncAttributes,
286
+ syncFormValue,
287
+ patchElement,
288
+ patchNode,
289
+ patchChildren,
290
+ patch,
291
+ morph,
292
+ }