soma-kit 0.1.14 → 0.1.15

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 (287) hide show
  1. package/package.json +3 -3
  2. package/packs/finance/reconcile-desk/compile.ts +1 -1
  3. package/packs/finance/reconcile-desk/shell.ts +1 -1
  4. package/spec/generated/kit-app.schema.json +4 -2
  5. package/spec/generated/kit-page.schema.json +72 -2
  6. package/spec/kit-grammar.json +163 -57
  7. package/spec/kit-grammar.schema.json +0 -24
  8. package/src/app/app-config.ts +1 -1
  9. package/src/app/component-gate.ts +2 -2
  10. package/src/app/compose-apps.ts +5 -2
  11. package/src/app/define-kit-actions.ts +82 -10
  12. package/src/app/define-kit-app.ts +6 -5
  13. package/src/app/define-kit-view.ts +1 -1
  14. package/src/app/index.ts +7 -7
  15. package/src/app/kit-view-context.ts +11 -2
  16. package/src/app/theme-endpoint.ts +1 -1
  17. package/src/app/theme-runtime.ts +7 -2
  18. package/src/base/alert.ts +23 -20
  19. package/src/base/anchored-layer.ts +1 -1
  20. package/src/base/button.ts +30 -15
  21. package/src/base/cascader.ts +8 -4
  22. package/src/base/check-core.ts +9 -6
  23. package/src/base/color-picker.ts +10 -6
  24. package/src/base/command-palette.ts +10 -4
  25. package/src/base/context-menu.ts +5 -2
  26. package/src/base/date-range.ts +9 -6
  27. package/src/base/date.ts +10 -6
  28. package/src/base/delta.ts +4 -2
  29. package/src/base/divider.ts +15 -66
  30. package/src/base/fab.ts +11 -6
  31. package/src/base/gap-value.ts +1 -1
  32. package/src/base/hint-tips.ts +1 -1
  33. package/src/base/index.ts +15 -4
  34. package/src/base/inline-error.ts +84 -0
  35. package/src/base/input.ts +54 -18
  36. package/src/base/kbd.ts +4 -3
  37. package/src/base/link.ts +1 -1
  38. package/src/base/listbox-core.ts +70 -22
  39. package/src/base/mentions.ts +6 -3
  40. package/src/base/menu-button.ts +63 -27
  41. package/src/base/menu-core.ts +9 -2
  42. package/src/base/motion/hover-3d.ts +4 -1
  43. package/src/base/motion/hover-gallery.ts +4 -1
  44. package/src/base/otp.ts +7 -3
  45. package/src/base/overlay-runtime.ts +3 -2
  46. package/src/base/overlay-shell.ts +141 -0
  47. package/src/base/popover.ts +2 -2
  48. package/src/base/popup.ts +47 -41
  49. package/src/base/qty-stepper.ts +14 -9
  50. package/src/base/reason-tip.ts +2 -2
  51. package/src/{frames → base}/resize-handle.ts +1 -1
  52. package/src/base/segmented.ts +35 -36
  53. package/src/base/select.ts +1 -0
  54. package/src/base/shared.ts +43 -7
  55. package/src/base/status-tone.ts +1 -1
  56. package/src/base/tag-input.ts +13 -8
  57. package/src/base/tag.ts +53 -59
  58. package/src/base/text.ts +37 -13
  59. package/src/base/textarea.ts +1 -1
  60. package/src/base/time-picker.ts +9 -5
  61. package/src/base/tree-select.ts +12 -9
  62. package/src/base/upload.ts +21 -13
  63. package/src/biz/approval-desk/compile.ts +28 -1
  64. package/src/biz/approval-desk/shell.ts +2 -2
  65. package/src/biz/auth-panel/compile.ts +1 -1
  66. package/src/biz/auth-panel/shell.ts +2 -2
  67. package/src/biz/category-crud/compile.ts +17 -4
  68. package/src/biz/category-crud/shell.ts +7 -5
  69. package/src/biz/checkout-page/compile.ts +1 -1
  70. package/src/biz/checkout-page/shell.ts +7 -6
  71. package/src/biz/compose.ts +3 -3
  72. package/src/biz/define.ts +1 -1
  73. package/src/biz/import-wizard/compile.ts +1 -1
  74. package/src/biz/import-wizard/shell.ts +6 -4
  75. package/src/biz/index.ts +4 -3
  76. package/src/biz/landing-page/compile.ts +1 -1
  77. package/src/biz/landing-page/shell.ts +5 -4
  78. package/src/biz/link/shared.ts +8 -1
  79. package/src/biz/master-sub/compile.ts +162 -19
  80. package/src/biz/master-sub/detail-head.ts +7 -6
  81. package/src/biz/master-sub/index.ts +3 -3
  82. package/src/biz/master-sub/shell.ts +90 -53
  83. package/src/biz/multi-board/compile.ts +3 -3
  84. package/src/biz/multi-board/index.ts +24 -9
  85. package/src/biz/multi-board/prose-fold.ts +2 -2
  86. package/src/biz/multi-board/shell.ts +17 -13
  87. package/src/biz/names.ts +1 -0
  88. package/src/biz/notification-center/compile.ts +9 -2
  89. package/src/biz/notification-center/shell.ts +9 -2
  90. package/src/biz/page-templates/domain-templates.ts +6 -2
  91. package/src/biz/page-templates/result-page/compile.ts +1 -1
  92. package/src/biz/page-templates/result-page/shell.ts +4 -3
  93. package/src/biz/page-templates/shared.ts +1 -1
  94. package/src/biz/page-templates/sign-in-page/compile.ts +1 -1
  95. package/src/biz/page-templates/sign-in-page/shell.ts +4 -4
  96. package/src/biz/record-detail/compile.ts +5 -2
  97. package/src/biz/record-detail/shell.ts +4 -4
  98. package/src/biz/settings-center/compile.ts +1 -1
  99. package/src/biz/settings-center/shell.ts +8 -5
  100. package/src/biz/shared/action-host.ts +12 -5
  101. package/src/biz/shared/compile-helpers.ts +4 -4
  102. package/src/biz/shared/coordinator.ts +104 -21
  103. package/src/biz/shared/overlay-compile.ts +48 -18
  104. package/src/biz/shared/overlay-shell.ts +63 -112
  105. package/src/biz/single-form/compile.ts +2 -2
  106. package/src/biz/single-form/shell.ts +8 -4
  107. package/src/biz/standard-crud/compile.ts +11 -4
  108. package/src/biz/standard-crud/shell.ts +26 -9
  109. package/src/biz/standard-crud/summary.ts +3 -1
  110. package/src/biz/step-form/compile.ts +1 -1
  111. package/src/biz/step-form/hub.ts +4 -0
  112. package/src/biz/step-form/shell.ts +6 -4
  113. package/src/biz/types.ts +11 -4
  114. package/src/cli/app-layer-check.ts +375 -0
  115. package/src/cli/kit-cli.ts +35 -8
  116. package/src/cli/kit-init.ts +149 -0
  117. package/src/compile/access-gate-attach.ts +1 -1
  118. package/src/compile/action-host-attach.ts +1 -1
  119. package/src/compile/compile-page.ts +29 -234
  120. package/src/compile/component-candidates.ts +2 -1
  121. package/src/compile/hints.ts +5 -58
  122. package/src/compile/index.ts +2 -2
  123. package/src/compile/layout-lint/index.ts +4 -1
  124. package/src/compile/layout-lint/rules-composition.ts +43 -13
  125. package/src/compile/page-composition.ts +33 -31
  126. package/src/compile/redirect.ts +1 -1
  127. package/src/compile/stages.ts +169 -0
  128. package/src/compile/styles.ts +70 -32
  129. package/src/compile/types.ts +2 -2
  130. package/src/data/amount-breakdown.ts +4 -2
  131. package/src/data/anchor-nav.ts +4 -1
  132. package/src/data/approval-flow.ts +9 -4
  133. package/src/data/assignment-picker.ts +28 -18
  134. package/src/data/async-result-panel.ts +6 -2
  135. package/src/data/breadcrumbs.ts +13 -9
  136. package/src/data/calendar.ts +4 -3
  137. package/src/data/carousel.ts +11 -5
  138. package/src/data/chart.ts +153 -23
  139. package/src/data/checklist.ts +5 -4
  140. package/src/data/code-view.ts +220 -26
  141. package/src/data/comment-thread.ts +7 -2
  142. package/src/data/confirm-dialog.ts +56 -13
  143. package/src/data/diff.ts +4 -1
  144. package/src/data/dock.ts +5 -1
  145. package/src/data/embed.ts +1 -1
  146. package/src/data/engine-ports.ts +126 -0
  147. package/src/data/field-mapper.ts +12 -6
  148. package/src/data/flow-editor.ts +105 -29
  149. package/src/data/footer.ts +6 -2
  150. package/src/data/gantt.ts +11 -8
  151. package/src/data/hero.ts +6 -2
  152. package/src/data/image-viewer.ts +7 -3
  153. package/src/data/index.ts +12 -5
  154. package/src/data/item-list.ts +6 -5
  155. package/src/data/json-view.ts +844 -0
  156. package/src/data/kanban.ts +11 -8
  157. package/src/data/markdown-view.ts +487 -0
  158. package/src/data/matrix.ts +23 -14
  159. package/src/data/media-grid.ts +5 -2
  160. package/src/data/mega-menu.ts +4 -3
  161. package/src/data/menu-dom.ts +9 -8
  162. package/src/data/menu.ts +15 -9
  163. package/src/data/mockup.ts +9 -5
  164. package/src/data/modal-dialog.ts +39 -88
  165. package/src/data/navbar.ts +11 -7
  166. package/src/data/notice-list.ts +1 -1
  167. package/src/data/notify-renderer.ts +21 -10
  168. package/src/data/object-form.ts +129 -48
  169. package/src/data/pager.ts +12 -8
  170. package/src/data/panel-head.ts +1 -1
  171. package/src/data/permission-matrix.ts +15 -8
  172. package/src/data/permission-tree.ts +24 -11
  173. package/src/data/pricing-table.ts +8 -3
  174. package/src/data/reaction-bar.ts +6 -3
  175. package/src/data/record-card.ts +13 -9
  176. package/src/data/record-picker.ts +8 -4
  177. package/src/data/redirect.ts +1 -1
  178. package/src/data/request-console.ts +20 -7
  179. package/src/data/resident.ts +0 -12
  180. package/src/data/result-panel.ts +2 -2
  181. package/src/data/rich-text.ts +58 -96
  182. package/src/data/row-editor.ts +10 -5
  183. package/src/data/rule-builder.ts +14 -8
  184. package/src/data/shape-util.ts +14 -3
  185. package/src/data/stat-group.ts +63 -22
  186. package/src/data/static-lazy.ts +3 -0
  187. package/src/data/static-registry.ts +8 -2
  188. package/src/data/steps.ts +6 -2
  189. package/src/data/survey.ts +9 -3
  190. package/src/data/system-switcher.ts +15 -6
  191. package/src/data/text-diff.ts +663 -0
  192. package/src/data/timeline.ts +1 -1
  193. package/src/data/tour-guide.ts +6 -3
  194. package/src/data/transfer.ts +19 -10
  195. package/src/data/tree-table.ts +77 -12
  196. package/src/data/tree.ts +5 -2
  197. package/src/data/virtual-rows.ts +17 -7
  198. package/src/data/wrap.ts +2 -2
  199. package/src/frames/index.ts +3 -2
  200. package/src/frames/inherited-shell.ts +178 -0
  201. package/src/frames/list-summary.ts +59 -36
  202. package/src/frames/page-bar.ts +4 -2
  203. package/src/frames/resident-components.ts +20 -0
  204. package/src/frames/shared.ts +18 -14
  205. package/src/frames/split-frame/shell.ts +17 -11
  206. package/src/frames/split-frame/wiring.ts +2 -2
  207. package/src/frames/tabs-frame/shell.ts +12 -6
  208. package/src/frames/types.ts +3 -2
  209. package/src/frames/workspace-frame/extras.ts +19 -5
  210. package/src/frames/workspace-frame/shell.ts +2 -1
  211. package/src/frames/workspace-frame/state.ts +8 -2
  212. package/src/frames/workspace-frame/view.ts +125 -76
  213. package/src/generated/kit-grammar-runtime.ts +61 -39
  214. package/src/i18n/kit-text.ts +114 -2
  215. package/src/i18n/resolve-text-refs.ts +1 -1
  216. package/src/object-renderer/action-group.ts +31 -1
  217. package/src/object-renderer/action-more.ts +28 -12
  218. package/src/object-renderer/arrange.ts +37 -7
  219. package/src/object-renderer/collection-parts.ts +38 -7
  220. package/src/object-renderer/collection-table.ts +68 -23
  221. package/src/object-renderer/collection.ts +63 -30
  222. package/src/object-renderer/compile-data.ts +1 -1
  223. package/src/object-renderer/defaults.ts +8 -0
  224. package/src/object-renderer/emit-events.ts +1 -1
  225. package/src/object-renderer/emit-object.ts +3 -0
  226. package/src/object-renderer/emit-static.ts +140 -37
  227. package/src/object-renderer/field-value.ts +12 -239
  228. package/src/object-renderer/filter-toolbar.ts +103 -0
  229. package/src/{compile → object-renderer}/fragment.ts +2 -2
  230. package/src/object-renderer/index.ts +1 -1
  231. package/src/object-renderer/layout-facts.ts +37 -5
  232. package/src/object-renderer/overlay-decide.ts +82 -0
  233. package/src/object-renderer/render-object.ts +1 -1
  234. package/src/object-renderer/table-actions.ts +70 -23
  235. package/src/object-renderer/table-tools.ts +12 -5
  236. package/src/object-renderer/types.ts +9 -15
  237. package/src/recipes/app-blocks.ts +66 -0
  238. package/src/recipes/code-view.ts +56 -0
  239. package/src/recipes/compact-group.ts +31 -0
  240. package/src/recipes/container.ts +25 -15
  241. package/src/recipes/control.ts +21 -3
  242. package/src/recipes/desc-list.ts +14 -0
  243. package/src/recipes/divider.ts +53 -0
  244. package/src/recipes/emphasis.ts +12 -8
  245. package/src/recipes/frame-bleed.ts +3 -3
  246. package/src/recipes/index.ts +11 -1
  247. package/src/recipes/inherited-shell.ts +37 -0
  248. package/src/recipes/json-view.ts +49 -0
  249. package/src/recipes/markdown.ts +86 -0
  250. package/src/recipes/overlay.ts +112 -26
  251. package/src/recipes/page-width.ts +20 -0
  252. package/src/recipes/placeholder.ts +1 -1
  253. package/src/recipes/stat-state.ts +1 -1
  254. package/src/recipes/state.ts +10 -8
  255. package/src/recipes/status.ts +13 -12
  256. package/src/recipes/strip.ts +72 -0
  257. package/src/recipes/surface.ts +10 -6
  258. package/src/recipes/table-gap.ts +1 -1
  259. package/src/recipes/table-native-edit.ts +4 -4
  260. package/src/recipes/table-row.ts +11 -8
  261. package/src/recipes/tabs.ts +108 -31
  262. package/src/recipes/text-diff.ts +90 -0
  263. package/src/recipes/title-row.ts +4 -2
  264. package/src/recipes/typography.ts +2 -2
  265. package/src/shared/diagnostics.ts +16 -0
  266. package/src/shared/envelope.ts +1 -1
  267. package/src/shared/field-value-format.ts +246 -0
  268. package/src/shared/focus-ring.ts +8 -0
  269. package/src/shared/hints.ts +56 -0
  270. package/src/{base → shared}/icons.ts +12 -0
  271. package/src/shared/kit-error.ts +1 -1
  272. package/src/{object-renderer → shared}/merge-class.ts +3 -2
  273. package/src/shared/path-guard.ts +1 -1
  274. package/src/shared/primitives-types.ts +8 -0
  275. package/src/shared/theme-runtime-shared.ts +19 -0
  276. package/src/theme/kit-theme-text.ts +1 -1
  277. package/src/theme/kit-theme.css +38 -14
  278. package/src/theme/kit-theme.tpl +38 -14
  279. package/src/theme/nine-dim-structure.ts +66 -41
  280. package/src/theme/surface-layers.ts +11 -3
  281. package/src/theme/theme-tokens.ts +5 -1
  282. package/src/app/envelope.ts +0 -1
  283. package/src/app/notify-renderer.ts +0 -1
  284. package/src/app/paged-list-adapter.ts +0 -1
  285. package/src/app/theme-runtime-shared.ts +0 -1
  286. package/src/compile/kit-error.ts +0 -1
  287. /package/src/{base → shared}/class-candidates.ts +0 -0
@@ -0,0 +1,663 @@
1
+ // TextDiff:文本 / 条目差异(layer: data,写死形状,accept: single;内容展示批次 ①)。
2
+ //
3
+ // 传入数据对象即自动渲染(规格:knowledge/Kit主题规则与算法.md §10「文本差异」;参考文本差异组件笔记 C.5):
4
+ // { before: string, after: string } → 散文两级差异(端口 diffProse:段 → 句 → 词,中文按词)
5
+ // { before: object[], after: object[], key?, fields?, title?, noun? } → 条目差异(端口 diffItems:配对、字段差异、移动)
6
+ // { before: 标量, after: 标量 }(数字 / 布尔 / 日期串以外的非字符串) → 字段「旧 → 新」
7
+ // { fragments: [{ v, op }] }(调用方算好的片段) → 直接渲染,不再计算
8
+ // before 空 / after 有 → 全部新增;归一化后相同 → 「两个版本内容相同」+ 正文;两侧类型不一致 → 分别显示旧 / 新
9
+ // format: 'code'(或带 language / filename) → 按行差异(合并视图;并排与折叠见第 ⑥ 批)
10
+ // 自动决定:版式(单栏行内)、粒度(端口按内容定)、改写呈现(端口 kind=rewrite → 旧 / 新上下堆叠)、
11
+ // 仅看改动(有改动且未变占比 > 阈值时默认开)、被删条目默认收起、导航(改动处 ≥ 2 才出「上一处 / 下一处」)。
12
+ // 可覆盖项只有 show_unchanged: auto | on | off。
13
+ // 无障碍:<ins>/<del> 首部视觉隐藏「新增:/ 删除:」;摘要条 role=region;F7 / Shift+F7 跳转(焦点在组件内时),
14
+ // 跳到的落点读出「第 i 处,共 k 处:…」(aria-live);折叠条是按钮(aria-expanded)。
15
+ // 数据只经 textContent / createElement 写入,不用 innerHTML。差异计算只经 core 引擎端口 engines.diff。
16
+
17
+ import type { SomaComponentDefinition } from 'soma-core';
18
+ import { KIT_CONTENT_LIMITS } from 'soma-foundation/kit-limits';
19
+ import { createKitController, joinClass, str } from '../base/shared';
20
+ import { KIT_LOADING_GATE_DEFAULTS } from '../base/loading-gate';
21
+ import { kitText } from '../i18n/kit-text';
22
+ import { kitIcon } from '../shared/icons';
23
+ import {
24
+ KIT_DIFF_BLOCK_NEW_CLASS, KIT_DIFF_BLOCK_OLD_CLASS, KIT_DIFF_DEL_CLASS, KIT_DIFF_FIELDS_CLASS, KIT_DIFF_FIELD_BODY_CLASS,
25
+ KIT_DIFF_FIELD_LABEL_CLASS, KIT_DIFF_FIELD_MARK_CLASS, KIT_DIFF_FIELD_ROW_CLASS, KIT_DIFF_HEAD_CLASS, KIT_DIFF_INS_CLASS,
26
+ KIT_DIFF_LIST_CLASS, KIT_DIFF_NAV_POS_CLASS, KIT_DIFF_NOTE_CLASS, KIT_DIFF_PROSE_CLASS, KIT_DIFF_PROSE_CODE_CLASS,
27
+ KIT_DIFF_REWRITE_SCROLL_CLASS, KIT_DIFF_ROOT_CLASS, KIT_DIFF_STACK_LABEL_CLASS, KIT_DIFF_SUMMARY_CLASS, KIT_DIFF_SUMMARY_NOTE_CLASS,
28
+ KIT_DIFF_SUMMARY_TEXT_CLASS, KIT_DIFF_TITLE_CLASS, KIT_DIFF_TITLE_REMOVED_CLASS, KIT_DIFF_TOGGLE_ACTIVE_CLASS,
29
+ KIT_DIFF_TOOLS_CLASS, KIT_DIFF_VALUE_ARROW_CLASS, KIT_TEXT_DIFF_RECIPE_CLASS_CANDIDATES, kitDiffBadgeRecipe, kitDiffItemRecipe,
30
+ kitDiffParagraphRecipe, kitDiffSymbolRecipe, type KitDiffTone,
31
+ } from '../recipes/text-diff';
32
+ import { KIT_SKELETON_BAR_LINE, KIT_SKELETON_BAR_MID } from '../recipes/placeholder';
33
+ import { actionButton, BUTTON_CLASS_TOKENS, classTokens, emptyNode, mk, recOf } from './shape-util';
34
+ import { textActionButton, TEXT_ACTION_CLASS_TOKENS } from './text-action-button';
35
+ import {
36
+ kitEnginePort, type KitDiffEnginePort, type KitDiffFragment, type KitItemDiff, type KitItemDiffEntry, type KitItemFieldDiff,
37
+ type KitItemFieldSpec, type KitItemState, type KitProseBlock, type KitProseDiff,
38
+ } from './engine-ports';
39
+
40
+ const L = KIT_CONTENT_LIMITS.textDiff;
41
+ const REWRITE_FOLD_ABOVE = KIT_CONTENT_LIMITS.codeView.foldAbove;
42
+ const REWRITE_FOLD_TO = KIT_CONTENT_LIMITS.codeView.foldTo;
43
+
44
+ export const KIT_TEXT_DIFF_DEFAULT_MAP = Object.freeze({ before: 'before', after: 'after' });
45
+
46
+ // ── 形状识别(纯函数,便于单测) ───────────────────────────────────────────────
47
+
48
+ export type KitTextDiffShape =
49
+ | { readonly kind: 'empty' }
50
+ | { readonly kind: 'prose'; readonly before: string; readonly after: string }
51
+ | { readonly kind: 'code'; readonly before: string; readonly after: string }
52
+ | { readonly kind: 'items'; readonly before: readonly unknown[]; readonly after: readonly unknown[]; readonly key?: string; readonly fields?: readonly KitItemFieldSpec[]; readonly title?: string; readonly noun: string }
53
+ | { readonly kind: 'value'; readonly before: unknown; readonly after: unknown }
54
+ | { readonly kind: 'fragments'; readonly fragments: readonly KitDiffFragment[]; readonly invalid: boolean; readonly after: string }
55
+ | { readonly kind: 'mismatch'; readonly before: unknown; readonly after: unknown };
56
+
57
+ const blank = (v: unknown): boolean => v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0);
58
+ const OPS = new Set(['eq', 'ins', 'del']);
59
+
60
+ function fieldsOf(raw: unknown): KitItemFieldSpec[] | undefined {
61
+ if (!Array.isArray(raw)) return undefined;
62
+ const out: KitItemFieldSpec[] = [];
63
+ for (const f of raw) {
64
+ if (typeof f === 'string' && f !== '') out.push({ name: f, label: f, type: 'text' });
65
+ else if (f !== null && typeof f === 'object') {
66
+ const o = f as Record<string, unknown>;
67
+ const name = typeof o.name === 'string' ? o.name : '';
68
+ if (name === '') continue;
69
+ out.push({ name, label: typeof o.label === 'string' && o.label !== '' ? o.label : name, type: o.type === 'value' ? 'value' : 'text' });
70
+ }
71
+ }
72
+ return out.length > 0 ? out : undefined;
73
+ }
74
+
75
+ /** 数据对象 → 差异形态(自动识别与归一) */
76
+ export function textDiffShapeOf(data: Record<string, unknown>, map: Record<string, string> = KIT_TEXT_DIFF_DEFAULT_MAP): KitTextDiffShape {
77
+ if (Array.isArray(data.fragments)) {
78
+ const frags: KitDiffFragment[] = [];
79
+ let invalid = false;
80
+ for (const f of data.fragments) {
81
+ const o = recOf(f);
82
+ if (typeof o.v !== 'string' || !OPS.has(String(o.op))) { invalid = true; continue; }
83
+ frags.push({ v: o.v, op: o.op as KitDiffFragment['op'] });
84
+ }
85
+ const after = typeof data[map.after ?? 'after'] === 'string' ? String(data[map.after ?? 'after']) : frags.filter((f) => f.op !== 'del').map((f) => f.v).join('');
86
+ return { kind: 'fragments', fragments: frags, invalid, after };
87
+ }
88
+ const before = data[map.before ?? 'before'];
89
+ const after = data[map.after ?? 'after'];
90
+ if (blank(before) && blank(after)) return { kind: 'empty' };
91
+ const isList = (v: unknown): boolean => Array.isArray(v) || blank(v);
92
+ if ((Array.isArray(before) || Array.isArray(after)) && isList(before) && isList(after)) {
93
+ return {
94
+ kind: 'items',
95
+ before: Array.isArray(before) ? before : [],
96
+ after: Array.isArray(after) ? after : [],
97
+ ...(typeof data.key === 'string' && data.key !== '' ? { key: data.key } : {}),
98
+ ...(fieldsOf(data.fields) ? { fields: fieldsOf(data.fields)! } : {}),
99
+ ...(typeof data.title === 'string' && data.title !== '' ? { title: data.title } : {}),
100
+ noun: typeof data.noun === 'string' && data.noun !== '' ? data.noun : '',
101
+ };
102
+ }
103
+ const isText = (v: unknown): boolean => typeof v === 'string' || blank(v);
104
+ if (isText(before) && isText(after)) {
105
+ const b = typeof before === 'string' ? before : '';
106
+ const a = typeof after === 'string' ? after : '';
107
+ const code = data.format === 'code' || typeof data.language === 'string' || typeof data.filename === 'string';
108
+ return code ? { kind: 'code', before: b, after: a } : { kind: 'prose', before: b, after: a };
109
+ }
110
+ const scalar = (v: unknown): boolean => blank(v) || ['string', 'number', 'boolean'].includes(typeof v);
111
+ if (scalar(before) && scalar(after)) return { kind: 'value', before, after };
112
+ return { kind: 'mismatch', before, after };
113
+ }
114
+
115
+ /** 仅看改动的缺省(纯函数):有改动且未变占比 > onlyChangesAbove → 开 */
116
+ export function onlyChangesDefault(unchanged: number, total: number, changes: number): boolean {
117
+ if (changes <= 0 || total <= 0) return false;
118
+ return unchanged / total > L.onlyChangesAbove;
119
+ }
120
+
121
+ // ── 状态 ─────────────────────────────────────────────────────────────────────
122
+
123
+ type Computed =
124
+ | { readonly kind: 'prose'; readonly prose: KitProseDiff; readonly unit: 'chars' | 'lines' }
125
+ | { readonly kind: 'items'; readonly items: KitItemDiff; readonly noun: string }
126
+ | { readonly kind: 'failed' };
127
+
128
+ interface UiState {
129
+ sig: string;
130
+ computed: Computed | null;
131
+ /** null = 跟随缺省 */
132
+ onlyChanges: boolean | null;
133
+ unfolded: Set<string>;
134
+ openRemoved: Set<string>;
135
+ openFields: Set<string>;
136
+ pos: number;
137
+ }
138
+
139
+ const STATE_SYMBOL: Readonly<Record<KitItemState, string>> = Object.freeze({ added: '+', removed: '−', modified: '~', moved: '', 'moved-modified': '', same: '' });
140
+ const STATE_TONE: Readonly<Record<KitItemState, KitDiffTone>> = Object.freeze({ added: 'ins', removed: 'del', modified: 'mod', moved: 'move', 'moved-modified': 'mod', same: 'same' });
141
+ const BLOCK_TONE: Readonly<Record<KitProseBlock['op'], KitDiffTone>> = Object.freeze({ eq: 'same', ins: 'ins', del: 'del', mod: 'mod' });
142
+ const BLOCK_SYMBOL: Readonly<Record<KitProseBlock['op'], string>> = Object.freeze({ eq: '', ins: '+', del: '−', mod: '~' });
143
+ const STOP_ATTR = 'data-kit-diff-stop';
144
+ const HIDDEN = 'hidden';
145
+
146
+ export const KIT_TEXT_DIFF_CLASS_CANDIDATES: readonly string[] = classTokens(
147
+ KIT_TEXT_DIFF_RECIPE_CLASS_CANDIDATES, BUTTON_CLASS_TOKENS, TEXT_ACTION_CLASS_TOKENS, KIT_SKELETON_BAR_LINE, KIT_SKELETON_BAR_MID, 'sr-only', HIDDEN, 'flex', 'flex-col', 'gap-2',
148
+ );
149
+
150
+ function signatureOf(shape: KitTextDiffShape): string {
151
+ try { return JSON.stringify(shape); } catch { return String(Math.random()); }
152
+ }
153
+
154
+ const t = (key: Parameters<typeof kitText>[0], root: HTMLElement, params?: Record<string, string | number>): string => kitText(key, params, root);
155
+
156
+ // ── 渲染件 ───────────────────────────────────────────────────────────────────
157
+
158
+ /** 行内片段:<ins>/<del> 首部视觉隐藏前缀;每个改动簇的第一个元素是导航落点(stop=true 时) */
159
+ function appendFragments(box: HTMLElement, frags: readonly KitDiffFragment[], root: HTMLElement, stop: boolean): void {
160
+ let inChange = false;
161
+ for (const f of frags) {
162
+ if (f.op === 'eq') { box.appendChild(document.createTextNode(f.v)); inChange = false; continue; }
163
+ const el = mk(f.op === 'ins' ? 'ins' : 'del', f.op === 'ins' ? KIT_DIFF_INS_CLASS : KIT_DIFF_DEL_CLASS);
164
+ el.appendChild(mk('span', 'sr-only', t(f.op === 'ins' ? 'soma.kit.diff_sr_ins' : 'soma.kit.diff_sr_del', root)));
165
+ el.appendChild(document.createTextNode(f.v));
166
+ if (stop && !inChange) { el.setAttribute(STOP_ATTR, ''); el.tabIndex = -1; }
167
+ inChange = true;
168
+ box.appendChild(el);
169
+ }
170
+ }
171
+
172
+ function paragraph(block: KitProseBlock, root: HTMLElement, stop: boolean): HTMLElement {
173
+ const tone = BLOCK_TONE[block.op];
174
+ const p = mk('p', kitDiffParagraphRecipe(tone));
175
+ const sym = mk('span', kitDiffSymbolRecipe(tone), BLOCK_SYMBOL[block.op]);
176
+ sym.setAttribute('aria-hidden', 'true');
177
+ p.appendChild(sym);
178
+ const body = mk('span', 'min-w-0 whitespace-pre-wrap break-words');
179
+ if (block.op === 'ins' || block.op === 'del') {
180
+ // 整段增删:段本身是落点,正文按 ins / del 标记(第二线索)
181
+ appendFragments(body, block.fragments, root, false);
182
+ if (stop) { p.setAttribute(STOP_ATTR, ''); p.tabIndex = -1; }
183
+ } else appendFragments(body, block.fragments, root, stop && block.op === 'mod');
184
+ p.appendChild(body);
185
+ return p;
186
+ }
187
+
188
+ function foldButton(id: string, label: string, open: boolean): HTMLButtonElement {
189
+ const btn = textActionButton(`diff-fold:${id}`, label, 'primary');
190
+ btn.setAttribute('aria-expanded', open ? 'true' : 'false');
191
+ return btn;
192
+ }
193
+
194
+ /** 散文正文:rewrite → 旧 / 新上下堆叠(超长时默认折叠预览、展开在限高区滚动);否则逐段;仅看改动时连续未变段(超出上下文)折叠 */
195
+ function renderProse(box: HTMLElement, prose: KitProseDiff, root: HTMLElement, st: UiState, only: boolean, keyPrefix: string, stops: boolean, mono = false): void {
196
+ const wrap = mk('div', mono ? KIT_DIFF_PROSE_CODE_CLASS : KIT_DIFF_PROSE_CLASS);
197
+ if (prose.kind === 'rewrite') {
198
+ const olds = prose.blocks.filter((b) => b.op === 'del');
199
+ const news = prose.blocks.filter((b) => b.op === 'ins');
200
+ const fillStack = (host: HTMLElement, list: readonly KitProseBlock[], foldId: string): void => {
201
+ const large = list.length > REWRITE_FOLD_ABOVE;
202
+ const open = st.unfolded.has(foldId);
203
+ const shown = large && !open ? list.slice(0, REWRITE_FOLD_TO) : list;
204
+ const body = large && open ? mk('div', KIT_DIFF_REWRITE_SCROLL_CLASS) : host;
205
+ for (const b of shown) {
206
+ const d = mk('p', 'm-0 whitespace-pre-wrap break-words');
207
+ appendFragments(d, b.fragments, root, false);
208
+ body.appendChild(d);
209
+ }
210
+ if (body !== host) host.appendChild(body);
211
+ if (large) {
212
+ host.appendChild(foldButton(foldId, t(open ? 'soma.kit.diff_fold_rewrite' : 'soma.kit.diff_unfold_rewrite', root, { n: list.length }), open));
213
+ }
214
+ };
215
+ const oldBox = mk('div', KIT_DIFF_BLOCK_OLD_CLASS);
216
+ oldBox.appendChild(mk('span', KIT_DIFF_STACK_LABEL_CLASS, t('soma.kit.diff_before', root)));
217
+ fillStack(oldBox, olds, `${keyPrefix}rw-old`);
218
+ const newBox = mk('div', KIT_DIFF_BLOCK_NEW_CLASS);
219
+ newBox.appendChild(mk('span', KIT_DIFF_STACK_LABEL_CLASS, t('soma.kit.diff_after', root)));
220
+ fillStack(newBox, news, `${keyPrefix}rw-new`);
221
+ if (stops) { oldBox.setAttribute(STOP_ATTR, ''); oldBox.tabIndex = -1; }
222
+ wrap.append(oldBox, newBox);
223
+ box.appendChild(wrap);
224
+ return;
225
+ }
226
+ const blocks = prose.blocks;
227
+ const changed = blocks.map((b) => b.op !== 'eq');
228
+ const near = (i: number): boolean => {
229
+ for (let d = -L.proseContext; d <= L.proseContext; d += 1) if (changed[i + d] === true) return true;
230
+ return false;
231
+ };
232
+ let k = 0;
233
+ while (k < blocks.length) {
234
+ if (!only || changed[k] || near(k)) { wrap.appendChild(paragraph(blocks[k], root, stops)); k += 1; continue; }
235
+ let e = k;
236
+ while (e < blocks.length && !changed[e] && !near(e)) e += 1;
237
+ const n = e - k;
238
+ const id = `${keyPrefix}p${k}`;
239
+ if (n < L.proseFoldMin || st.unfolded.has(id)) {
240
+ for (let j = k; j < e; j += 1) wrap.appendChild(paragraph(blocks[j], root, stops));
241
+ if (n >= L.proseFoldMin) wrap.appendChild(foldButton(id, t('soma.kit.diff_fold_paragraphs', root, { n }), true));
242
+ } else wrap.appendChild(foldButton(id, t('soma.kit.diff_unfold_paragraphs', root, { n }), false));
243
+ k = e;
244
+ }
245
+ box.appendChild(wrap);
246
+ }
247
+
248
+ const valueText = (v: unknown, root: HTMLElement): string => (v === undefined || v === null || v === '' ? t('soma.kit.diff_value_empty', root) : typeof v === 'object' ? JSON.stringify(v) : String(v));
249
+
250
+ /** 字段「旧 → 新」(整值比较) */
251
+ function valueChange(before: unknown, after: unknown, root: HTMLElement): HTMLElement {
252
+ const line = mk('p', KIT_DIFF_FIELD_BODY_CLASS);
253
+ const del = mk('del', KIT_DIFF_DEL_CLASS);
254
+ del.append(mk('span', 'sr-only', t('soma.kit.diff_sr_del', root)), document.createTextNode(valueText(before, root)));
255
+ const arrow = mk('span', KIT_DIFF_VALUE_ARROW_CLASS);
256
+ arrow.setAttribute('aria-hidden', 'true');
257
+ arrow.appendChild(kitIcon('arrow-right', 'xs', 'rtl:-scale-x-100'));
258
+ const ins = mk('ins', KIT_DIFF_INS_CLASS);
259
+ ins.append(mk('span', 'sr-only', t('soma.kit.diff_sr_ins', root)), document.createTextNode(valueText(after, root)));
260
+ line.append(del, arrow, ins);
261
+ return line;
262
+ }
263
+
264
+ function stateLabel(state: KitItemState, root: HTMLElement): string {
265
+ return t(state === 'added' ? 'soma.kit.diff_state_added' : state === 'removed' ? 'soma.kit.diff_state_removed' : state === 'same' ? 'soma.kit.diff_state_same' : state === 'modified' ? 'soma.kit.diff_state_modified' : 'soma.kit.diff_state_moved', root);
266
+ }
267
+
268
+ function itemCard(entry: KitItemDiffEntry, root: HTMLElement, st: UiState): HTMLElement {
269
+ const card = mk('li', kitDiffItemRecipe(STATE_TONE[entry.state]));
270
+ card.setAttribute('data-kit-diff-item', entry.state);
271
+ const head = mk('div', KIT_DIFF_HEAD_CLASS);
272
+ if (entry.state !== 'same') {
273
+ const badges: Array<[KitDiffTone, 'move' | string, string]> = entry.state === 'moved-modified'
274
+ ? [['move', 'move', stateLabel('moved', root)], ['mod', STATE_SYMBOL.modified, stateLabel('modified', root)]]
275
+ : [[STATE_TONE[entry.state], entry.state === 'moved' ? 'move' : STATE_SYMBOL[entry.state], stateLabel(entry.state, root)]];
276
+ badges.forEach(([tone, sym, label], i) => {
277
+ const b = mk('span', kitDiffBadgeRecipe(tone));
278
+ if (sym === 'move') b.appendChild(kitIcon('sort', 'xs'));
279
+ else if (sym !== '') { const s = mk('span', '', sym); s.setAttribute('aria-hidden', 'true'); b.appendChild(s); }
280
+ b.appendChild(document.createTextNode(label));
281
+ if (i === 0) {
282
+ b.setAttribute(STOP_ATTR, '');
283
+ b.tabIndex = -1;
284
+ const changedNames = entry.fields.filter((f) => f.state !== 'same').map((f) => f.label).join('、');
285
+ b.setAttribute('data-kit-diff-say', `${stateLabel(entry.state === 'moved-modified' ? 'modified' : entry.state, root)}${changedNames !== '' ? `,${changedNames}` : ''}`);
286
+ }
287
+ head.appendChild(b);
288
+ });
289
+ }
290
+ const titleField = entry.fields.find((f) => f.type === 'text');
291
+ const titleProse = titleField !== undefined && titleField.state === 'changed' && titleField.prose !== undefined && String(titleField.after ?? '') === entry.title ? titleField.prose : undefined;
292
+ const title = mk('p', entry.state === 'removed' ? KIT_DIFF_TITLE_REMOVED_CLASS : KIT_DIFF_TITLE_CLASS);
293
+ if (titleProse !== undefined && titleProse.kind !== 'rewrite') appendFragments(title, titleProse.blocks.flatMap((b) => b.fragments), root, false);
294
+ else title.textContent = entry.title !== '' ? entry.title : `#${(entry.afterIndex ?? entry.beforeIndex ?? 0) + 1}`;
295
+ head.appendChild(title);
296
+ card.appendChild(head);
297
+
298
+ if (entry.state === 'moved' || entry.state === 'moved-modified') {
299
+ card.appendChild(mk('p', KIT_DIFF_NOTE_CLASS, t('soma.kit.diff_moved_from', root, { from: (entry.beforeIndex ?? 0) + 1, to: (entry.afterIndex ?? 0) + 1 })));
300
+ }
301
+ // 被删条目默认收起(裁决 #9)
302
+ if (entry.state === 'removed' && !st.openRemoved.has(entry.key)) {
303
+ const btn = textActionButton(`diff-removed:${entry.key}`, t('soma.kit.diff_show_removed', root), 'primary');
304
+ btn.setAttribute('aria-expanded', 'false');
305
+ card.appendChild(btn);
306
+ return card;
307
+ }
308
+ const whole = entry.state === 'added' || entry.state === 'removed';
309
+ const shown: KitItemFieldDiff[] = [];
310
+ const hiddenSame: KitItemFieldDiff[] = [];
311
+ for (const f of entry.fields) {
312
+ if (f === titleField) {
313
+ // 标题在卡头;标题被整段改写(头部只显示新标题)时,另起一行给出「旧 / 新」
314
+ if (!whole && f.state !== 'same' && !(titleProse !== undefined && titleProse.kind !== 'rewrite')) shown.push(f);
315
+ continue;
316
+ }
317
+ if (whole) { if (!blank(entry.state === 'added' ? f.after : f.before)) shown.push(f); continue; }
318
+ if (f.state === 'same') hiddenSame.push(f); else shown.push(f);
319
+ }
320
+ const fieldsBox = mk('div', KIT_DIFF_FIELDS_CLASS);
321
+ const showSame = st.openFields.has(entry.key);
322
+ const fieldRow = (f: KitItemFieldDiff): HTMLElement => {
323
+ const row = mk('div', KIT_DIFF_FIELD_ROW_CLASS);
324
+ const label = mk('div', KIT_DIFF_FIELD_LABEL_CLASS);
325
+ label.appendChild(mk('span', '', f.label));
326
+ if (entry.state !== 'added' && entry.state !== 'removed' && f.state !== 'same') {
327
+ label.appendChild(mk('span', KIT_DIFF_FIELD_MARK_CLASS, t(f.state === 'added' ? 'soma.kit.diff_field_added' : f.state === 'removed' ? 'soma.kit.diff_field_removed' : 'soma.kit.diff_field_changed', root)));
328
+ }
329
+ row.appendChild(label);
330
+ if (entry.state === 'added' || entry.state === 'removed' || f.state === 'same') {
331
+ row.appendChild(mk('p', KIT_DIFF_FIELD_BODY_CLASS, valueText(entry.state === 'removed' ? f.before : f.after, root)));
332
+ } else if (f.prose !== undefined) {
333
+ const body = mk('div', KIT_DIFF_FIELD_BODY_CLASS);
334
+ renderProse(body, f.prose, root, st, false, `${entry.key}.${f.name}.`, false);
335
+ row.appendChild(body);
336
+ } else row.appendChild(valueChange(f.before, f.after, root));
337
+ return row;
338
+ };
339
+ for (const f of shown) fieldsBox.appendChild(fieldRow(f));
340
+ if (hiddenSame.length > 0) {
341
+ if (showSame) for (const f of hiddenSame) fieldsBox.appendChild(fieldRow(f));
342
+ const btn = textActionButton(`diff-fields:${entry.key}`, t(showSame ? 'soma.kit.diff_fold_fields' : 'soma.kit.diff_unfold_fields', root, { n: hiddenSame.length }), 'primary');
343
+ btn.setAttribute('aria-expanded', showSame ? 'true' : 'false');
344
+ fieldsBox.appendChild(btn);
345
+ }
346
+ if (fieldsBox.childElementCount > 0) card.appendChild(fieldsBox);
347
+ return card;
348
+ }
349
+
350
+ function renderItems(box: HTMLElement, diff: KitItemDiff, root: HTMLElement, st: UiState, only: boolean): void {
351
+ const list = mk('ol', KIT_DIFF_LIST_CLASS);
352
+ let k = 0;
353
+ const items = diff.items;
354
+ while (k < items.length) {
355
+ if (!only || items[k].state !== 'same') { list.appendChild(itemCard(items[k], root, st)); k += 1; continue; }
356
+ let e = k;
357
+ while (e < items.length && items[e].state === 'same') e += 1;
358
+ const n = e - k;
359
+ const id = `i${k}`;
360
+ const li = mk('li', '');
361
+ if (n < L.itemFoldMin || st.unfolded.has(id)) {
362
+ for (let j = k; j < e; j += 1) list.appendChild(itemCard(items[j], root, st));
363
+ if (n >= L.itemFoldMin) { li.appendChild(foldButton(id, t('soma.kit.diff_fold_items', root, { n }), true)); list.appendChild(li); }
364
+ } else { li.appendChild(foldButton(id, t('soma.kit.diff_unfold_items', root, { n }), false)); list.appendChild(li); }
365
+ k = e;
366
+ }
367
+ box.appendChild(list);
368
+ }
369
+
370
+ // ── 组件 ─────────────────────────────────────────────────────────────────────
371
+
372
+ export function createTextDiff(): SomaComponentDefinition {
373
+ const states = new WeakMap<HTMLElement, UiState>();
374
+ const stateOf = (root: HTMLElement): UiState => {
375
+ let st = states.get(root);
376
+ if (st === undefined) {
377
+ st = { sig: '', computed: null, onlyChanges: null, unfolded: new Set(), openRemoved: new Set(), openFields: new Set(), pos: -1 };
378
+ states.set(root, st);
379
+ }
380
+ return st;
381
+ };
382
+
383
+ return {
384
+ contract: {
385
+ name: 'TextDiff',
386
+ layer: 'data',
387
+ props: {
388
+ data: { type: 'object', default: {}, desc: '{ before, after }:两段文本 → 散文差异;两组对象数组 → 条目差异(可带 key / fields / title / noun);标量 → 「旧 → 新」;或 { fragments: [{ v, op }] } 已算好的片段' },
389
+ map: { type: 'object', default: {}, desc: '键名对照:before / after' },
390
+ show_unchanged: { type: 'enum', values: ['auto', 'on', 'off'], default: 'auto', desc: '未变内容:auto = 有改动且未变占比超过阈值时只看改动;on = 全部显示;off = 只看改动' },
391
+ empty_text: { type: 'string', default: '', desc: '两侧都为空时的文案;缺省取内置文案(按页面语言)' },
392
+ class: { type: 'string', default: '', desc: '外部传入的类,追加在根节点类串末尾' },
393
+ },
394
+ emits: {
395
+ navigate: { payload: { index: { type: 'number' }, total: { type: 'number' } }, desc: '上一处 / 下一处跳转后抛(第 index 处,共 total 处,从 1 起)' },
396
+ },
397
+ },
398
+ services: ['engines'],
399
+ templateHtml: `<section data-kit-container="card" data-soma-id="root" class="${KIT_DIFF_ROOT_CLASS}"></section>`,
400
+ controllerFactory: createKitController((api) => {
401
+ const stopsOf = (root: HTMLElement): HTMLElement[] => Array.from(root.querySelectorAll<HTMLElement>(`[${STOP_ATTR}]`));
402
+ const jump = (root: HTMLElement, dir: 1 | -1): void => {
403
+ const stops = stopsOf(root);
404
+ if (stops.length === 0) return;
405
+ const st = stateOf(root);
406
+ st.pos = st.pos < 0 ? (dir > 0 ? 0 : stops.length - 1) : (st.pos + dir + stops.length) % stops.length;
407
+ const el = stops[st.pos];
408
+ el.focus();
409
+ el.scrollIntoView?.({ block: 'nearest' });
410
+ const posEl = root.querySelector<HTMLElement>('[data-kit-diff-pos]');
411
+ if (posEl) posEl.textContent = t('soma.kit.diff_position', root, { i: st.pos + 1, k: stops.length });
412
+ const live = root.querySelector<HTMLElement>('[data-kit-diff-live]');
413
+ const say = el.getAttribute('data-kit-diff-say') ?? '';
414
+ if (live) live.textContent = `${t('soma.kit.diff_position', root, { i: st.pos + 1, k: stops.length })}${say !== '' ? `:${say}` : ''}`;
415
+ api.emit('navigate', { index: st.pos + 1, total: stops.length });
416
+ };
417
+ return {
418
+ attach(root) {
419
+ const onClick = (event: Event): void => {
420
+ const btn = (event.target as HTMLElement | null)?.closest<HTMLElement>('[data-kit-action]');
421
+ if (!btn || !root.contains(btn)) return;
422
+ const action = btn.getAttribute('data-kit-action') ?? '';
423
+ const st = stateOf(root);
424
+ if (action === 'diff-prev' || action === 'diff-next') { jump(root, action === 'diff-next' ? 1 : -1); return; }
425
+ if (action === 'diff-only') st.onlyChanges = btn.getAttribute('aria-pressed') !== 'true';
426
+ else if (action.startsWith('diff-fold:')) { const id = action.slice('diff-fold:'.length); if (st.unfolded.has(id)) st.unfolded.delete(id); else st.unfolded.add(id); }
427
+ else if (action.startsWith('diff-removed:')) st.openRemoved.add(action.slice('diff-removed:'.length));
428
+ else if (action.startsWith('diff-fields:')) { const id = action.slice('diff-fields:'.length); if (st.openFields.has(id)) st.openFields.delete(id); else st.openFields.add(id); }
429
+ else return;
430
+ st.pos = -1;
431
+ api.refresh();
432
+ };
433
+ // F7 / Shift+F7:组件内有焦点时跳到下一处 / 上一处(VS Code 同款)
434
+ const onKey = (event: KeyboardEvent): void => {
435
+ if (event.key !== 'F7') return;
436
+ event.preventDefault();
437
+ jump(root, event.shiftKey ? -1 : 1);
438
+ };
439
+ root.addEventListener('click', onClick);
440
+ root.addEventListener('keydown', onKey as EventListener);
441
+ return () => {
442
+ root.removeEventListener('click', onClick);
443
+ root.removeEventListener('keydown', onKey as EventListener);
444
+ states.delete(root);
445
+ };
446
+ },
447
+ async render(root, p, renderApi) {
448
+ root.className = joinClass(KIT_DIFF_ROOT_CLASS, p.class);
449
+ const st = stateOf(root);
450
+ const map = { ...KIT_TEXT_DIFF_DEFAULT_MAP, ...recOf(p.map) } as Record<string, string>;
451
+ const shape = textDiffShapeOf(recOf(p.data), map);
452
+ const sig = signatureOf(shape);
453
+ if (sig !== st.sig) {
454
+ st.sig = sig;
455
+ st.computed = null;
456
+ st.onlyChanges = null;
457
+ st.unfolded.clear();
458
+ st.openRemoved.clear();
459
+ st.openFields.clear();
460
+ st.pos = -1;
461
+ }
462
+ const mode = str(p.show_unchanged, 'auto');
463
+
464
+ if (shape.kind === 'empty') { root.replaceChildren(emptyNode(str(p.empty_text, t('soma.kit.empty_content', root)))); return; }
465
+ if (shape.kind === 'value') { drawValue(root, shape.before, shape.after); return; }
466
+ if (shape.kind === 'mismatch') { drawMismatch(root, shape.before, shape.after); return; }
467
+ if (shape.kind === 'fragments') { drawFragments(root, shape); return; }
468
+
469
+ if (st.computed === null) {
470
+ const port = kitEnginePort<KitDiffEnginePort>(renderApi.services, 'diff');
471
+ // 计算超过加载反馈的延迟阈值才出骨架(与全 kit 同一条:structure.loadingFeedback.delayMs,快路径零闪屏)
472
+ const hint = setTimeout(() => { if (st.computed === null && renderApi.isCurrent()) drawComputing(root); }, KIT_LOADING_GATE_DEFAULTS.delayMs);
473
+ try {
474
+ if (port === null) st.computed = { kind: 'failed' };
475
+ else if (shape.kind === 'items') {
476
+ st.computed = { kind: 'items', noun: shape.noun, items: await port.diffItems(shape.before, shape.after, { ...(shape.key ? { key: shape.key } : {}), ...(shape.fields ? { fields: shape.fields } : {}), ...(shape.title ? { title: shape.title } : {}) }) };
477
+ } else if (shape.kind === 'code') {
478
+ st.computed = { kind: 'prose', unit: 'lines', prose: linesToProse(await port.diff(shape.before, shape.after, 'lines')) };
479
+ } else st.computed = { kind: 'prose', unit: 'chars', prose: await port.diffProse(shape.before, shape.after) };
480
+ } catch {
481
+ st.computed = { kind: 'failed' };
482
+ } finally {
483
+ clearTimeout(hint);
484
+ }
485
+ if (!renderApi.isCurrent()) return;
486
+ }
487
+ const computed = st.computed;
488
+ if (computed.kind === 'failed') { drawFailed(root, shape); return; }
489
+ drawComputed(root, computed, st, mode);
490
+ },
491
+ };
492
+ }),
493
+ };
494
+
495
+ // ── 各形态的绘制 ──
496
+
497
+ function summaryBar(root: HTMLElement, text: string, notes: readonly string[], tools: { readonly onlyToggle: boolean; readonly only: boolean; readonly navTotal: number }): HTMLElement {
498
+ const region = mk('div', 'flex flex-col gap-2');
499
+ region.setAttribute('role', 'region');
500
+ region.setAttribute('data-kit-container', 'plain');
501
+ region.setAttribute('aria-label', t('soma.kit.diff_summary_label', root));
502
+ const row = mk('div', KIT_DIFF_SUMMARY_CLASS);
503
+ row.appendChild(mk('p', KIT_DIFF_SUMMARY_TEXT_CLASS, text));
504
+ const box = mk('div', KIT_DIFF_TOOLS_CLASS);
505
+ if (tools.onlyToggle) {
506
+ const btn = actionButton({ key: 'diff-only', label: t('soma.kit.diff_only_changes', root), tone: 'neutral', disabled: false, reason: '' });
507
+ if (tools.only) btn.className = KIT_DIFF_TOGGLE_ACTIVE_CLASS;
508
+ btn.setAttribute('aria-pressed', tools.only ? 'true' : 'false');
509
+ box.appendChild(btn);
510
+ }
511
+ if (tools.navTotal >= L.navMin) {
512
+ box.appendChild(actionButton({ key: 'diff-prev', label: t('soma.kit.diff_prev', root), tone: 'neutral', disabled: false, reason: '' }));
513
+ box.appendChild(actionButton({ key: 'diff-next', label: t('soma.kit.diff_next', root), tone: 'neutral', disabled: false, reason: '' }));
514
+ const pos = mk('span', KIT_DIFF_NAV_POS_CLASS, t('soma.kit.diff_total', root, { k: tools.navTotal }));
515
+ pos.setAttribute('data-kit-diff-pos', '');
516
+ box.appendChild(pos);
517
+ }
518
+ if (box.childElementCount > 0) row.appendChild(box);
519
+ region.appendChild(row);
520
+ for (const n of notes) region.appendChild(mk('p', KIT_DIFF_SUMMARY_NOTE_CLASS, n));
521
+ const live = mk('span', 'sr-only');
522
+ live.setAttribute('aria-live', 'polite');
523
+ live.setAttribute('data-kit-diff-live', '');
524
+ region.appendChild(live);
525
+ return region;
526
+ }
527
+
528
+ function degradedNotes(root: HTMLElement, d: string | undefined, granularity?: string, rewrite = false): string[] {
529
+ const out: string[] = [];
530
+ if (granularity === 'chars') out.push(t('soma.kit.diff_by_char', root));
531
+ if (d === 'too-large' && rewrite) out.push(t('soma.kit.diff_degraded_too_large', root));
532
+ else if (d === 'timeout' || d === 'too-large') out.push(t('soma.kit.diff_degraded_long', root));
533
+ if (d === 'too-many-items') out.push(t('soma.kit.diff_too_many_items', root));
534
+ return out;
535
+ }
536
+
537
+ function drawComputed(root: HTMLElement, c: Exclude<Computed, { kind: 'failed' }>, st: UiState, mode: string): void {
538
+ root.textContent = '';
539
+ if (c.kind === 'prose') {
540
+ const prose = c.prose;
541
+ const mono = c.unit === 'lines';
542
+ if (prose.kind === 'same') {
543
+ root.appendChild(summaryBar(root, t(prose.formatOnly ? 'soma.kit.diff_format_only' : 'soma.kit.diff_same', root), [], { onlyToggle: false, only: false, navTotal: 0 }));
544
+ const body = mk('div', '');
545
+ renderProse(body, prose, root, st, false, '', false, mono);
546
+ root.appendChild(body);
547
+ return;
548
+ }
549
+ const eqBlocks = prose.blocks.filter((b) => b.op === 'eq').length;
550
+ const auto = onlyChangesDefault(eqBlocks, prose.blocks.length, prose.stats.changes);
551
+ const only = mode === 'off' ? true : mode === 'on' ? false : st.onlyChanges ?? auto;
552
+ const navTotal = prose.kind === 'rewrite' ? 1 : prose.stats.changes;
553
+ const text = t(mono ? 'soma.kit.diff_lines' : 'soma.kit.diff_chars', root, { ins: prose.stats.insChars, del: prose.stats.delChars });
554
+ root.appendChild(summaryBar(root, text, degradedNotes(root, prose.degraded, prose.granularity, prose.kind === 'rewrite'), { onlyToggle: mode === 'auto' && eqBlocks > 0, only, navTotal }));
555
+ const body = mk('div', '');
556
+ renderProse(body, prose, root, st, only, '', true, mono);
557
+ root.appendChild(body);
558
+ return;
559
+ }
560
+ const d = c.items;
561
+ const s = d.stats;
562
+ const noun = c.noun !== '' ? c.noun : t('soma.kit.diff_item_noun', root);
563
+ if (d.degraded === 'too-many-items') {
564
+ root.appendChild(summaryBar(root, t('soma.kit.diff_items_total', root, { n: s.total, noun }), degradedNotes(root, d.degraded), { onlyToggle: false, only: false, navTotal: 0 }));
565
+ return;
566
+ }
567
+ const changed = s.total - s.same;
568
+ const parts = [
569
+ t('soma.kit.diff_items_total', root, { n: s.total, noun }),
570
+ [s.added > 0 ? t('soma.kit.diff_count_added', root, { n: s.added }) : '', s.removed > 0 ? t('soma.kit.diff_count_removed', root, { n: s.removed }) : '',
571
+ s.modified > 0 ? t('soma.kit.diff_count_modified', root, { n: s.modified }) : '', s.moved > 0 ? t('soma.kit.diff_count_moved', root, { n: s.moved }) : '',
572
+ s.same > 0 ? t('soma.kit.diff_count_same', root, { n: s.same }) : ''].filter((x) => x !== '').join(' · '),
573
+ ].filter((x) => x !== '').join(':');
574
+ const notes = degradedNotes(root, d.degraded);
575
+ if (d.pairing === 'content' && (s.total > 0)) notes.unshift(t('soma.kit.diff_pairing_content', root, { noun }));
576
+ if (d.movesSkipped && changed > 0 && d.degraded === undefined && s.total > 0) notes.push(t('soma.kit.diff_moves_skipped', root));
577
+ if (changed === 0) {
578
+ root.appendChild(summaryBar(root, t('soma.kit.diff_same', root), notes, { onlyToggle: false, only: false, navTotal: 0 }));
579
+ renderItems(root, d, root, st, false);
580
+ return;
581
+ }
582
+ const auto = onlyChangesDefault(s.same, s.total, changed);
583
+ const only = mode === 'off' ? true : mode === 'on' ? false : st.onlyChanges ?? auto;
584
+ root.appendChild(summaryBar(root, parts, notes, { onlyToggle: mode === 'auto' && s.same > 0, only, navTotal: changed }));
585
+ renderItems(root, d, root, st, only);
586
+ }
587
+
588
+ function drawComputing(root: HTMLElement): void {
589
+ const box = mk('div', 'flex flex-col gap-2');
590
+ box.setAttribute('role', 'status');
591
+ box.setAttribute('aria-busy', 'true');
592
+ box.appendChild(mk('span', 'sr-only', t('soma.kit.diff_computing', root)));
593
+ box.append(mk('div', KIT_SKELETON_BAR_MID), mk('div', KIT_SKELETON_BAR_LINE), mk('div', KIT_SKELETON_BAR_LINE));
594
+ root.replaceChildren(box);
595
+ }
596
+
597
+ function sideBySideFallback(root: HTMLElement, before: unknown, after: unknown, note: string): void {
598
+ root.textContent = '';
599
+ root.appendChild(summaryBar(root, note, [], { onlyToggle: false, only: false, navTotal: 0 }));
600
+ const old = mk('div', KIT_DIFF_BLOCK_OLD_CLASS);
601
+ old.append(mk('span', KIT_DIFF_STACK_LABEL_CLASS, t('soma.kit.diff_before', root)), mk('p', KIT_DIFF_FIELD_BODY_CLASS, valueText(before, root)));
602
+ const neu = mk('div', KIT_DIFF_BLOCK_NEW_CLASS);
603
+ neu.append(mk('span', KIT_DIFF_STACK_LABEL_CLASS, t('soma.kit.diff_after', root)), mk('p', KIT_DIFF_FIELD_BODY_CLASS, valueText(after, root)));
604
+ root.append(old, neu);
605
+ }
606
+
607
+ function drawMismatch(root: HTMLElement, before: unknown, after: unknown): void {
608
+ sideBySideFallback(root, before, after, t('soma.kit.diff_type_mismatch', root));
609
+ }
610
+
611
+ function drawFailed(root: HTMLElement, shape: KitTextDiffShape): void {
612
+ const before = 'before' in shape ? shape.before : '';
613
+ const after = 'after' in shape ? shape.after : '';
614
+ sideBySideFallback(root, before, after, t('soma.kit.diff_engine_failed', root));
615
+ }
616
+
617
+ function drawValue(root: HTMLElement, before: unknown, after: unknown): void {
618
+ root.textContent = '';
619
+ const same = valueText(before, root) === valueText(after, root);
620
+ root.appendChild(summaryBar(root, t(same ? 'soma.kit.diff_same' : 'soma.kit.diff_value_changed', root), [], { onlyToggle: false, only: false, navTotal: 0 }));
621
+ root.appendChild(same ? mk('p', KIT_DIFF_FIELD_BODY_CLASS, valueText(after, root)) : valueChange(before, after, root));
622
+ }
623
+
624
+ function drawFragments(root: HTMLElement, shape: Extract<KitTextDiffShape, { kind: 'fragments' }>): void {
625
+ root.textContent = '';
626
+ if (shape.invalid) {
627
+ root.appendChild(summaryBar(root, t('soma.kit.diff_fragments_invalid', root), [], { onlyToggle: false, only: false, navTotal: 0 }));
628
+ root.appendChild(mk('p', KIT_DIFF_FIELD_BODY_CLASS, shape.after));
629
+ return;
630
+ }
631
+ let ins = 0;
632
+ let del = 0;
633
+ for (const f of shape.fragments) { if (f.op === 'ins') ins += Array.from(f.v).length; else if (f.op === 'del') del += Array.from(f.v).length; }
634
+ let changes = 0;
635
+ let inChange = false;
636
+ for (const f of shape.fragments) { if (f.op === 'eq') inChange = false; else if (!inChange) { changes += 1; inChange = true; } }
637
+ root.appendChild(summaryBar(root, t('soma.kit.diff_chars', root, { ins, del }), [], { onlyToggle: false, only: false, navTotal: changes }));
638
+ const p = mk('p', KIT_DIFF_FIELD_BODY_CLASS);
639
+ appendFragments(p, shape.fragments, root, true);
640
+ root.appendChild(p);
641
+ }
642
+ }
643
+
644
+ /** 按行片段 → 段级块(代码形态的最小实现:每行一块,增 / 删 / 未变;并排、行号、折叠见第 ⑥ 批) */
645
+ export function linesToProse(parts: readonly { op: 'equal' | 'insert' | 'delete'; text: string }[]): KitProseDiff {
646
+ const blocks: KitProseBlock[] = [];
647
+ let ins = 0;
648
+ let del = 0;
649
+ let changes = 0;
650
+ let inChange = false;
651
+ for (const part of parts) {
652
+ const lines = part.text.replace(/\n$/u, '').split('\n');
653
+ const op = part.op === 'equal' ? 'eq' : part.op === 'insert' ? 'ins' : 'del';
654
+ if (op === 'eq') inChange = false;
655
+ else if (!inChange) { changes += 1; inChange = true; }
656
+ for (const line of lines) {
657
+ blocks.push({ op, fragments: [{ op, v: line === '' ? ' ' : line }] });
658
+ if (op === 'ins') ins += 1; else if (op === 'del') del += 1;
659
+ }
660
+ }
661
+ const same = changes === 0;
662
+ return { kind: same ? 'same' : 'inline', formatOnly: false, similarity: same ? 1 : 0, blocks, stats: { insChars: ins, delChars: del, changes }, granularity: 'words' };
663
+ }