soma-kit 0.1.13 → 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 (312) 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 +18 -2
  5. package/spec/generated/kit-page.schema.json +95 -0
  6. package/spec/kit-grammar.json +332 -75
  7. package/spec/kit-grammar.schema.json +1 -27
  8. package/src/app/app-config.ts +11 -5
  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 +20 -8
  15. package/src/app/kit-view-context.ts +30 -4
  16. package/src/app/server-pages.ts +5 -1
  17. package/src/app/server.ts +15 -5
  18. package/src/app/theme-endpoint.ts +1 -1
  19. package/src/app/theme-runtime.ts +7 -2
  20. package/src/base/alert.ts +23 -20
  21. package/src/base/anchored-layer.ts +1 -1
  22. package/src/base/button.ts +34 -17
  23. package/src/base/cascader.ts +8 -4
  24. package/src/base/check-core.ts +9 -6
  25. package/src/base/color-picker.ts +10 -6
  26. package/src/base/command-palette.ts +10 -4
  27. package/src/base/context-menu.ts +5 -2
  28. package/src/base/date-range.ts +9 -6
  29. package/src/base/date.ts +10 -6
  30. package/src/base/delta.ts +4 -2
  31. package/src/base/divider.ts +15 -66
  32. package/src/base/end-edge.ts +14 -2
  33. package/src/base/fab.ts +11 -6
  34. package/src/base/gap-value.ts +25 -5
  35. package/src/base/hint-tips.ts +1 -1
  36. package/src/base/illustrations.ts +2 -1
  37. package/src/base/index.ts +20 -4
  38. package/src/base/inline-error.ts +84 -0
  39. package/src/base/input.ts +54 -18
  40. package/src/base/kbd.ts +4 -3
  41. package/src/base/link.ts +1 -1
  42. package/src/base/listbox-core.ts +70 -22
  43. package/src/base/mentions.ts +6 -3
  44. package/src/base/menu-button.ts +73 -50
  45. package/src/base/menu-core.ts +9 -2
  46. package/src/base/motion/hover-3d.ts +4 -1
  47. package/src/base/motion/hover-gallery.ts +4 -1
  48. package/src/base/otp.ts +7 -3
  49. package/src/base/overlay-runtime.ts +3 -2
  50. package/src/base/overlay-shell.ts +141 -0
  51. package/src/base/popover.ts +7 -6
  52. package/src/base/popup.ts +47 -41
  53. package/src/base/qty-stepper.ts +14 -9
  54. package/src/base/reason-tip.ts +2 -2
  55. package/src/{frames → base}/resize-handle.ts +1 -1
  56. package/src/base/segmented.ts +44 -35
  57. package/src/base/select.ts +1 -0
  58. package/src/base/shared.ts +52 -18
  59. package/src/base/state-panel.ts +34 -13
  60. package/src/base/status-tone.ts +1 -1
  61. package/src/base/tag-input.ts +13 -8
  62. package/src/base/tag.ts +56 -57
  63. package/src/base/text.ts +38 -14
  64. package/src/base/textarea.ts +1 -1
  65. package/src/base/time-picker.ts +9 -5
  66. package/src/base/tree-select.ts +12 -9
  67. package/src/base/upload.ts +26 -17
  68. package/src/biz/approval-desk/compile.ts +28 -1
  69. package/src/biz/approval-desk/shell.ts +10 -9
  70. package/src/biz/auth-panel/compile.ts +1 -1
  71. package/src/biz/auth-panel/shell.ts +7 -6
  72. package/src/biz/category-crud/compile.ts +20 -6
  73. package/src/biz/category-crud/shell.ts +10 -7
  74. package/src/biz/checkout-page/compile.ts +1 -1
  75. package/src/biz/checkout-page/shell.ts +15 -13
  76. package/src/biz/compose.ts +5 -5
  77. package/src/biz/data-components.ts +4 -0
  78. package/src/biz/define.ts +1 -1
  79. package/src/biz/import-wizard/compile.ts +1 -1
  80. package/src/biz/import-wizard/shell.ts +17 -13
  81. package/src/biz/index.ts +4 -3
  82. package/src/biz/landing-page/compile.ts +1 -1
  83. package/src/biz/landing-page/shell.ts +6 -5
  84. package/src/biz/link/shared.ts +8 -1
  85. package/src/biz/master-sub/compile.ts +269 -27
  86. package/src/biz/master-sub/detail-head.ts +62 -0
  87. package/src/biz/master-sub/index.ts +5 -4
  88. package/src/biz/master-sub/shell.ts +138 -69
  89. package/src/biz/multi-board/compile.ts +166 -11
  90. package/src/biz/multi-board/composition.ts +58 -0
  91. package/src/biz/multi-board/index.ts +25 -10
  92. package/src/biz/multi-board/prose-fold.ts +143 -0
  93. package/src/biz/multi-board/shell.ts +96 -24
  94. package/src/biz/names.ts +1 -0
  95. package/src/biz/notification-center/compile.ts +9 -2
  96. package/src/biz/notification-center/shell.ts +15 -7
  97. package/src/biz/page-templates/domain-templates.ts +7 -3
  98. package/src/biz/page-templates/result-page/compile.ts +1 -1
  99. package/src/biz/page-templates/result-page/shell.ts +5 -4
  100. package/src/biz/page-templates/shared.ts +1 -1
  101. package/src/biz/page-templates/sign-in-page/compile.ts +1 -1
  102. package/src/biz/page-templates/sign-in-page/shell.ts +18 -18
  103. package/src/biz/record-detail/compile.ts +5 -2
  104. package/src/biz/record-detail/shell.ts +12 -11
  105. package/src/biz/settings-center/compile.ts +1 -1
  106. package/src/biz/settings-center/shell.ts +14 -10
  107. package/src/biz/shared/action-host.ts +12 -5
  108. package/src/biz/shared/compile-helpers.ts +83 -4
  109. package/src/biz/shared/coordinator.ts +104 -21
  110. package/src/biz/shared/overlay-compile.ts +76 -4
  111. package/src/biz/shared/overlay-shell.ts +65 -112
  112. package/src/biz/single-form/compile.ts +2 -2
  113. package/src/biz/single-form/shell.ts +13 -7
  114. package/src/biz/standard-crud/compile.ts +24 -4
  115. package/src/biz/standard-crud/shell.ts +38 -30
  116. package/src/biz/standard-crud/summary.ts +42 -0
  117. package/src/biz/step-form/compile.ts +1 -1
  118. package/src/biz/step-form/hub.ts +4 -0
  119. package/src/biz/step-form/shell.ts +16 -12
  120. package/src/biz/types.ts +15 -3
  121. package/src/cli/app-layer-check.ts +375 -0
  122. package/src/cli/kit-cli.ts +35 -8
  123. package/src/cli/kit-init.ts +149 -0
  124. package/src/cli/layout-cli.ts +7 -7
  125. package/src/compile/access-gate-attach.ts +27 -0
  126. package/src/compile/action-host-attach.ts +1 -1
  127. package/src/compile/compile-page.ts +36 -230
  128. package/src/compile/component-candidates.ts +4 -1
  129. package/src/compile/hints.ts +5 -58
  130. package/src/compile/index.ts +2 -2
  131. package/src/compile/layout-lint/index.ts +4 -1
  132. package/src/compile/layout-lint/rules-composition.ts +97 -18
  133. package/src/compile/layout-lint/rules-form.ts +6 -7
  134. package/src/compile/layout-lint/rules-table.ts +98 -14
  135. package/src/compile/page-composition.ts +191 -0
  136. package/src/compile/parse.ts +4 -0
  137. package/src/compile/producer-fingerprint.ts +56 -0
  138. package/src/compile/redirect.ts +1 -1
  139. package/src/compile/stages.ts +169 -0
  140. package/src/compile/styles.ts +80 -32
  141. package/src/compile/types.ts +5 -3
  142. package/src/data/access-gate.ts +112 -0
  143. package/src/data/amount-breakdown.ts +6 -2
  144. package/src/data/anchor-nav.ts +4 -1
  145. package/src/data/approval-flow.ts +13 -5
  146. package/src/data/assignment-picker.ts +35 -20
  147. package/src/data/async-result-panel.ts +7 -3
  148. package/src/data/breadcrumbs.ts +13 -9
  149. package/src/data/calendar.ts +10 -4
  150. package/src/data/carousel.ts +13 -5
  151. package/src/data/chart.ts +745 -48
  152. package/src/data/checklist.ts +9 -5
  153. package/src/data/code-view.ts +220 -26
  154. package/src/data/comment-thread.ts +9 -3
  155. package/src/data/confirm-dialog.ts +57 -20
  156. package/src/data/diff.ts +4 -1
  157. package/src/data/dock.ts +5 -1
  158. package/src/data/embed.ts +1 -1
  159. package/src/data/engine-ports.ts +126 -0
  160. package/src/data/field-mapper.ts +16 -7
  161. package/src/data/flow-editor.ts +106 -29
  162. package/src/data/footer.ts +8 -2
  163. package/src/data/gantt.ts +192 -27
  164. package/src/data/hero.ts +8 -2
  165. package/src/data/image-viewer.ts +7 -3
  166. package/src/data/index.ts +22 -8
  167. package/src/data/item-list.ts +11 -3
  168. package/src/data/json-view.ts +844 -0
  169. package/src/data/kanban.ts +13 -8
  170. package/src/data/markdown-view.ts +487 -0
  171. package/src/data/matrix.ts +400 -0
  172. package/src/data/media-grid.ts +5 -2
  173. package/src/data/mega-menu.ts +4 -3
  174. package/src/data/menu-dom.ts +9 -8
  175. package/src/data/menu.ts +35 -17
  176. package/src/data/mockup.ts +12 -8
  177. package/src/data/modal-dialog.ts +108 -57
  178. package/src/data/navbar.ts +13 -7
  179. package/src/data/notice-list.ts +53 -20
  180. package/src/data/notify-renderer.ts +21 -10
  181. package/src/data/object-form.ts +248 -151
  182. package/src/data/pager.ts +15 -10
  183. package/src/data/panel-head.ts +406 -0
  184. package/src/data/permission-matrix.ts +19 -9
  185. package/src/data/permission-tree.ts +30 -13
  186. package/src/data/pricing-table.ts +10 -4
  187. package/src/data/reaction-bar.ts +6 -3
  188. package/src/data/record-card.ts +30 -14
  189. package/src/data/record-picker.ts +8 -4
  190. package/src/data/redirect.ts +1 -1
  191. package/src/data/request-console.ts +20 -7
  192. package/src/data/resident.ts +6 -10
  193. package/src/data/result-panel.ts +2 -2
  194. package/src/data/rich-text.ts +58 -96
  195. package/src/data/row-editor.ts +12 -7
  196. package/src/data/rule-builder.ts +22 -11
  197. package/src/data/shape-util.ts +26 -14
  198. package/src/data/stat-group.ts +369 -84
  199. package/src/data/static-lazy.ts +7 -0
  200. package/src/data/static-registry.ts +14 -2
  201. package/src/data/steps.ts +6 -2
  202. package/src/data/survey.ts +13 -4
  203. package/src/data/system-switcher.ts +17 -7
  204. package/src/data/text-diff.ts +663 -0
  205. package/src/data/timeline.ts +1 -1
  206. package/src/data/tour-guide.ts +8 -4
  207. package/src/data/transfer.ts +24 -11
  208. package/src/data/tree-table.ts +84 -17
  209. package/src/data/tree.ts +6 -3
  210. package/src/data/virtual-rows.ts +22 -11
  211. package/src/data/wrap.ts +2 -2
  212. package/src/data/wrapped-candidates.ts +22 -1
  213. package/src/frames/index.ts +4 -2
  214. package/src/frames/inherited-shell.ts +178 -0
  215. package/src/frames/list-summary.ts +123 -0
  216. package/src/frames/page-bar.ts +10 -16
  217. package/src/frames/resident-components.ts +20 -0
  218. package/src/frames/shared.ts +37 -17
  219. package/src/frames/split-frame/shell.ts +17 -11
  220. package/src/frames/split-frame/wiring.ts +2 -2
  221. package/src/frames/tabs-frame/shell.ts +17 -9
  222. package/src/frames/top-main-frame.ts +1 -1
  223. package/src/frames/types.ts +6 -3
  224. package/src/frames/workspace-frame/extras.ts +19 -5
  225. package/src/frames/workspace-frame/shell.ts +4 -3
  226. package/src/frames/workspace-frame/state.ts +8 -2
  227. package/src/frames/workspace-frame/tab-scroll.ts +28 -0
  228. package/src/frames/workspace-frame/view.ts +156 -91
  229. package/src/generated/kit-grammar-runtime.ts +227 -58
  230. package/src/i18n/kit-text.ts +141 -2
  231. package/src/i18n/resolve-text-refs.ts +1 -1
  232. package/src/object-renderer/action-group.ts +169 -0
  233. package/src/object-renderer/action-more.ts +160 -0
  234. package/src/object-renderer/arrange.ts +86 -26
  235. package/src/object-renderer/candidates.ts +4 -0
  236. package/src/object-renderer/collection-parts.ts +72 -20
  237. package/src/object-renderer/collection-table.ts +178 -65
  238. package/src/object-renderer/collection.ts +129 -83
  239. package/src/object-renderer/compile-data.ts +1 -1
  240. package/src/object-renderer/defaults.ts +10 -5
  241. package/src/object-renderer/emit-events.ts +1 -1
  242. package/src/object-renderer/emit-object.ts +7 -0
  243. package/src/object-renderer/emit-static.ts +243 -87
  244. package/src/object-renderer/field-value.ts +12 -239
  245. package/src/object-renderer/filter-plan.ts +84 -0
  246. package/src/object-renderer/filter-toolbar.ts +103 -0
  247. package/src/{compile → object-renderer}/fragment.ts +13 -2
  248. package/src/object-renderer/index.ts +6 -1
  249. package/src/object-renderer/layout-facts.ts +46 -6
  250. package/src/object-renderer/layout-plan.ts +136 -43
  251. package/src/object-renderer/layout-plan.types.ts +42 -5
  252. package/src/object-renderer/overlay-decide.ts +82 -0
  253. package/src/object-renderer/parts.ts +7 -259
  254. package/src/object-renderer/render-object.ts +60 -47
  255. package/src/object-renderer/table-actions.ts +135 -56
  256. package/src/object-renderer/table-gap.ts +37 -0
  257. package/src/object-renderer/table-tools.ts +63 -25
  258. package/src/object-renderer/types.ts +16 -22
  259. package/src/recipes/app-blocks.ts +66 -0
  260. package/src/recipes/code-view.ts +56 -0
  261. package/src/recipes/compact-group.ts +31 -0
  262. package/src/recipes/container.ts +54 -13
  263. package/src/recipes/control.ts +77 -157
  264. package/src/recipes/desc-list.ts +14 -0
  265. package/src/recipes/divider.ts +53 -0
  266. package/src/recipes/emphasis.ts +60 -0
  267. package/src/recipes/frame-bleed.ts +33 -0
  268. package/src/recipes/index.ts +34 -1
  269. package/src/recipes/inherited-shell.ts +37 -0
  270. package/src/recipes/json-view.ts +49 -0
  271. package/src/recipes/markdown.ts +86 -0
  272. package/src/recipes/overlay.ts +149 -18
  273. package/src/recipes/page-width.ts +20 -0
  274. package/src/recipes/placeholder.ts +21 -5
  275. package/src/recipes/rail-grid.ts +3 -0
  276. package/src/recipes/stat-state.ts +65 -0
  277. package/src/recipes/state.ts +20 -28
  278. package/src/recipes/status.ts +17 -8
  279. package/src/recipes/strip.ts +72 -0
  280. package/src/recipes/surface-edge.ts +16 -0
  281. package/src/recipes/surface.ts +10 -6
  282. package/src/recipes/table-gap.ts +80 -0
  283. package/src/recipes/table-native-edit.ts +242 -0
  284. package/src/recipes/table-row.ts +120 -11
  285. package/src/recipes/tabs.ts +126 -0
  286. package/src/recipes/text-diff.ts +90 -0
  287. package/src/recipes/title-row.ts +7 -5
  288. package/src/recipes/typography.ts +24 -43
  289. package/src/shared/diagnostics.ts +16 -0
  290. package/src/shared/envelope.ts +1 -1
  291. package/src/shared/field-value-format.ts +246 -0
  292. package/src/shared/focus-ring.ts +8 -0
  293. package/src/shared/hints.ts +56 -0
  294. package/src/{base → shared}/icons.ts +12 -0
  295. package/src/shared/kit-error.ts +1 -1
  296. package/src/{object-renderer → shared}/merge-class.ts +3 -2
  297. package/src/shared/path-guard.ts +1 -1
  298. package/src/shared/primitives-types.ts +8 -0
  299. package/src/shared/theme-runtime-shared.ts +19 -0
  300. package/src/theme/kit-theme-text.ts +1 -1
  301. package/src/theme/kit-theme.css +49 -14
  302. package/src/theme/kit-theme.tpl +49 -14
  303. package/src/theme/nine-dim-structure.ts +129 -37
  304. package/src/theme/surface-layers.ts +17 -4
  305. package/src/theme/theme-tokens.ts +16 -5
  306. package/src/theme/typography.ts +21 -17
  307. package/src/app/envelope.ts +0 -1
  308. package/src/app/notify-renderer.ts +0 -1
  309. package/src/app/paged-list-adapter.ts +0 -1
  310. package/src/app/theme-runtime-shared.ts +0 -1
  311. package/src/compile/kit-error.ts +0 -1
  312. /package/src/{base → shared}/class-candidates.ts +0 -0
@@ -30,29 +30,35 @@ import { kitKey, kitText } from '../i18n/kit-text';
30
30
  import { createKeyboardWiring } from 'soma-core/keyboard';
31
31
  import { SOMA_SIZE_UNITS } from 'soma-foundation/theme';
32
32
  import { setKitFace } from '../recipes';
33
+ import { kitShellRecipe } from '../recipes/container';
34
+ import { kitSurfaceRecipe } from '../recipes/surface';
35
+ import { kitEmphasisButtonRecipe } from '../recipes/emphasis';
36
+ import { mergeClass } from '../shared/merge-class';
33
37
  import { provideCtxRows } from './context-menu';
34
38
 
35
39
  // ───────── 样式常量:Tailwind 类串与候选类清单 ─────────
36
40
 
37
41
  const ROOT_CLASS = '@container flex flex-col gap-2';
38
42
  const BOARD_CLASS = 'flex items-start gap-3 overflow-x-auto pb-2';
39
- const LANE_CLASS = 'flex w-72 shrink-0 flex-col gap-2 rounded-lg border border-border-subtle bg-surface-sunken p-2';
43
+ // 泳道 = 凹槽面的壳配方,卡片 = 壳配方(容器边 + 容器阴影令牌,KT-B2);移动菜单 = 浮起表面(KT-B4);提示条浅底无描边
44
+ const LANE_CLASS = mergeClass('flex w-72 shrink-0 flex-col gap-2 p-2', kitShellRecipe({ tone: 'sunken', shadow: false }));
40
45
  const LANE_HEAD_CLASS = 'flex items-center justify-between gap-2 px-1 text-sm';
41
46
  const LANE_TITLE_CLASS = 'font-medium text-fg';
42
47
  const COUNT_CLASS = 'text-fg-muted';
43
48
  const COUNT_OVER_CLASS = 'font-medium text-danger-on-soft';
44
49
  const LANE_BODY_CLASS = 'flex min-h-16 flex-col gap-2 rounded-md';
45
50
  const DROP_CLASS = 'ring-2 ring-inset ring-ring';
46
- const CARD_CLASS = 'flex flex-col gap-1 rounded-lg border border-border-subtle bg-surface p-3 text-sm text-fg shadow-xs transition-colors state-layer focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring';
51
+ const CARD_EDGE = kitShellRecipe({ tone: 'base' });
52
+ const CARD_CLASS = `flex flex-col gap-1 ${CARD_EDGE} p-3 text-sm text-fg transition-colors state-layer focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring`;
47
53
  const CARD_DRAG_CLASS = 'cursor-grab active:cursor-grabbing';
48
54
  const CARD_TITLE_CLASS = 'font-medium text-fg';
49
55
  const FACT_CLASS = 'flex items-baseline justify-between gap-2 text-xs text-fg-muted';
50
56
  const FACT_VALUE_CLASS = 'truncate text-fg';
51
57
  const EMPTY_CLASS = 'px-2 py-3 text-center text-sm text-fg-muted';
52
- const MOVE_BTN_CLASS = 'inline-flex h-7 items-center self-start rounded-md border border-button-edge bg-surface px-4 text-xs text-fg state-layer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50';
53
- const MENU_CLASS = 'flex flex-col gap-1 rounded-md border border-border bg-surface p-1';
58
+ const MOVE_BTN_CLASS = mergeClass(kitEmphasisButtonRecipe('button.toolbar'), 'self-start');
59
+ const MENU_CLASS = mergeClass('flex flex-col gap-1 p-1', kitSurfaceRecipe('raised'));
54
60
  const MENU_ITEM_CLASS = 'flex h-7 items-center rounded-md px-2 text-start text-xs text-fg hover:bg-state-layer-hover active:bg-state-layer-press focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:text-fg-subtle';
55
- const NOTICE_CLASS = 'rounded-md border border-border-subtle bg-warning-soft px-3 py-1.5 text-xs text-warning-on-soft';
61
+ const NOTICE_CLASS = 'rounded-md bg-warning-soft px-3 py-1.5 text-xs text-warning-on-soft';
56
62
  const HIDDEN_CLASS = 'hidden';
57
63
  const LIVE_CLASS = 'sr-only';
58
64
 
@@ -223,8 +229,6 @@ export function createKanban(): SomaComponentDefinition {
223
229
  const port = (api.services as { data?: SomaDataPort } | undefined)?.data;
224
230
  return port && typeof port === 'object' ? port : undefined;
225
231
  };
226
- const notifyPort = (): { toast?: (o: { level: string; message: string }) => void } | undefined =>
227
- (api.services as { notify?: { toast?: (o: { level: string; message: string }) => void } } | undefined)?.notify;
228
232
 
229
233
  const config = (): KitKanbanConfig => {
230
234
  const p = P();
@@ -275,7 +279,7 @@ export function createKanban(): SomaComponentDefinition {
275
279
  }
276
280
  showNotice(text);
277
281
  announce(text);
278
- notifyPort()?.toast?.({ level: 'danger', message: text });
282
+ // 错误不用轻提示(KT-K-feedback-3,§6.1 G-17):保存失败已由看板自己的 notice + announce 就地呈现,不再重复发轻提示
279
283
  paint();
280
284
  // 连着移了好几次、中间结果不可知:以服务端为准重取
281
285
  if (several) {
@@ -467,6 +471,7 @@ export function createKanban(): SomaComponentDefinition {
467
471
  const limit = cfg.wip[lane.value];
468
472
  const over = limit !== undefined && list.length > limit;
469
473
  const col = el('section', LANE_CLASS);
474
+ col.setAttribute('data-kit-container', 'card');
470
475
  col.setAttribute('aria-label', lane.label);
471
476
  col.setAttribute('data-kit-lane-box', lane.value);
472
477
  const head = el('div', LANE_HEAD_CLASS);
@@ -0,0 +1,487 @@
1
+ // MarkdownView:Markdown 展示(layer: data,写死形状,accept: single;内容展示批次 ④,规格 knowledge/Kit主题规则与算法.md §10.18)。
2
+ //
3
+ // 数据:Markdown 原文字符串,或 { source | markdown | content | text },或字符串数组(按块拼接、中间分割线);`path` 取 data 里的点路径。
4
+ // 原文只经 core 端口 engines.markdown 解析成块树,这里按节点类型 createElement / textContent 出 DOM(不用 innerHTML、不渲染原始 HTML)。
5
+ // 自动决定:标题层级(heading_offset 叠加)、目录(二级以上标题够多且正文够长才出)、顶层成段正文首行缩进两字(裁决 #4:
6
+ // 列表 / 引用 / 表格 / 脚注里的段落不缩进;只有一段的短内容不缩进)、代码块(与 CodeView 同一画法:语言推断、行号、着色、复制)、
7
+ // 表格横向滚动壳、图片懒加载与失败替换、外链新窗口 + 图标 + 读屏提示、任务列表只读勾选。
8
+ // 流式(stream: true,AI 逐字输出):原文不断增长,按帧节流整段重解析,只替换从第一个变化的块起之后的 DOM,前面已输出的文字保持可选中。
9
+ // 降级:空 → 空态;引擎不可用 / 过长 / 解析失败 → 纯文本分段 + 说明;原始 HTML 与不安全地址各有计数提示。
10
+
11
+ import type { SomaComponentDefinition } from 'soma-core';
12
+ import { KIT_CONTENT_LIMITS } from 'soma-foundation/kit-limits';
13
+ import { bool, createKitController, joinClass, str } from '../base/shared';
14
+ import { kitIcon } from '../shared/icons';
15
+ import { kitText } from '../i18n/kit-text';
16
+ import { KIT_PART_ATTRIBUTE, KIT_PART_WELL } from '../recipes';
17
+ import { KIT_CODE_LANG_CLASS, KIT_CODE_NOTE_CLASS, KIT_CODE_VIEW_RECIPE_CLASS_CANDIDATES } from '../recipes/code-view';
18
+ import {
19
+ KIT_MARKDOWN_RECIPE_CLASS_CANDIDATES, KIT_MD_BODY_CLASS, KIT_MD_CODE_CLASS, KIT_MD_DEL_CLASS, KIT_MD_FNREF_CLASS, KIT_MD_FOOTNOTES_CLASS,
20
+ KIT_MD_HR_CLASS, KIT_MD_HTML_CLASS, KIT_MD_IMG_CLASS, KIT_MD_LINK_CLASS, KIT_MD_LIST_CLASS, KIT_MD_LIST_STYLE, KIT_MD_LI_CLASS,
21
+ KIT_MD_P_CLASS, KIT_MD_P_INDENT_CLASS, KIT_MD_P_TIGHT_CLASS, KIT_MD_QUOTE_CLASS, KIT_MD_TABLE_CLASS, KIT_MD_TABLE_WRAP_CLASS,
22
+ KIT_MD_TASK_CLASS, KIT_MD_TD_CLASS, KIT_MD_TH_CLASS, kitMdHeadingClass,
23
+ KIT_MD_CODE_HEAD_CLASS, KIT_MD_CODE_WELL_CLASS, KIT_MD_EXT_ICON_CLASS, KIT_MD_IMG_FAIL_CLASS, KIT_MD_PLAIN_P_CLASS, KIT_MD_ROOT_CLASS,
24
+ KIT_MD_STRONG_CLASS, KIT_MD_TASK_BOX_CLASS, KIT_MD_TOC_CLASS, KIT_MD_TOC_ITEM_CLASS, KIT_MD_TOC_TITLE_CLASS,
25
+ } from '../recipes/markdown';
26
+ import { classTokens, emptyNode, mk } from './shape-util';
27
+ import { codeWrapDefault, paintCodeLines } from './code-view';
28
+ import {
29
+ kitEnginePort, type KitHighlightEnginePort, type KitMarkdownEnginePort, type KitMdBlock, type KitMdInline, type KitMdMeta, type KitMdResult,
30
+ } from './engine-ports';
31
+ import { KIT_STATE_PANEL_CLASS_CANDIDATES } from '../base/state-panel';
32
+ import { TEXT_ACTION_CLASS_TOKENS, textActionButton } from './text-action-button';
33
+
34
+ const ML = KIT_CONTENT_LIMITS.markdownView;
35
+
36
+ // ── 纯函数 ────────────────────────────────────────────────────────────
37
+
38
+ /** 数据 → Markdown 原文:字符串原样;{ source | markdown | content | text };字符串数组以分割线拼接;数字 / 布尔转字符串;其余空串 */
39
+ export function markdownSourceOf(raw: unknown): string {
40
+ if (raw === null || raw === undefined) return '';
41
+ if (typeof raw === 'string') return raw;
42
+ if (typeof raw === 'number' || typeof raw === 'boolean') return String(raw);
43
+ if (Array.isArray(raw)) return raw.map(markdownSourceOf).filter((s) => s.trim() !== '').join('\n\n---\n\n');
44
+ if (typeof raw === 'object') {
45
+ const o = raw as Record<string, unknown>;
46
+ for (const k of ['source', 'markdown', 'content', 'text']) if (typeof o[k] === 'string') return o[k] as string;
47
+ }
48
+ return '';
49
+ }
50
+
51
+ /** 目录:二级及以上(叠加偏移前的 depth ≤ 3)标题数 ≥ tocMinHeadings 且正文字数 ≥ tocMinChars */
52
+ export function markdownTocOf(meta: KitMdMeta, mode: string): KitMdMeta['outline'] {
53
+ if (mode === 'off') return [];
54
+ const list = meta.outline.filter((o) => o.depth <= 3);
55
+ return list.length >= ML.tocMinHeadings && meta.counts.chars >= ML.tocMinChars ? list : [];
56
+ }
57
+
58
+ /** 首行缩进(裁决 #4):只有顶层段落;全文只有一个顶层段落且短于 indentMinChars 字 → 不缩进 */
59
+ export function markdownIndentTopLevel(blocks: readonly KitMdBlock[]): boolean {
60
+ const paras = blocks.filter((b) => b.t === 'paragraph');
61
+ if (paras.length === 0) return false;
62
+ if (paras.length === 1 && blocks.length === 1) {
63
+ const p = paras[0]!;
64
+ return p.t === 'paragraph' && Array.from(inlinePlain(p.inline)).length >= ML.indentMinChars;
65
+ }
66
+ return true;
67
+ }
68
+
69
+ function inlinePlain(nodes: readonly KitMdInline[]): string {
70
+ let s = '';
71
+ for (const n of nodes) {
72
+ if (n.t === 'text' || n.t === 'code') s += n.v;
73
+ else if (n.t === 'image') s += n.alt;
74
+ else if (n.t === 'strong' || n.t === 'em' || n.t === 'del' || n.t === 'link') s += inlinePlain(n.c);
75
+ }
76
+ return s;
77
+ }
78
+
79
+ /** 只含图片(与空白)的段落:不缩进 */
80
+ const imageOnly = (nodes: readonly KitMdInline[]): boolean =>
81
+ nodes.length > 0 && nodes.every((n) => n.t === 'image' || (n.t === 'text' && n.v.trim() === '') || n.t === 'br');
82
+
83
+ // ── 块树渲染(MarkdownView 与 RichTextEditor 的 Markdown 来源共用) ─────────────────
84
+
85
+ // 类串全部来自配方 recipes/markdown.ts(G101:组件文件不手写圆角 / 字阶)
86
+ const CODE_WELL_CLASS = KIT_MD_CODE_WELL_CLASS;
87
+ const CODE_HEAD_CLASS = KIT_MD_CODE_HEAD_CLASS;
88
+ const TASK_BOX_CLASS = KIT_MD_TASK_BOX_CLASS;
89
+ const EXT_ICON_CLASS = KIT_MD_EXT_ICON_CLASS;
90
+ const IMG_FAIL_CLASS = KIT_MD_IMG_FAIL_CLASS;
91
+ const ROOT_CLASS = KIT_MD_ROOT_CLASS;
92
+ const TOC_CLASS = KIT_MD_TOC_CLASS;
93
+ const TOC_TITLE_CLASS = KIT_MD_TOC_TITLE_CLASS;
94
+ const TOC_ITEM_CLASS = KIT_MD_TOC_ITEM_CLASS;
95
+ const NOTE_CLASS = KIT_CODE_NOTE_CLASS;
96
+ const PLAIN_P_CLASS = KIT_MD_PLAIN_P_CLASS;
97
+
98
+ export const KIT_MARKDOWN_VIEW_CLASS_CANDIDATES: readonly string[] = classTokens(
99
+ NOTE_CLASS, KIT_CODE_LANG_CLASS, KIT_CODE_VIEW_RECIPE_CLASS_CANDIDATES, KIT_MARKDOWN_RECIPE_CLASS_CANDIDATES, KIT_STATE_PANEL_CLASS_CANDIDATES,
100
+ TEXT_ACTION_CLASS_TOKENS, 'sr-only', 'min-w-0', 'text-start', 'text-end', 'text-center',
101
+ );
102
+
103
+ export interface KitMdRenderContext {
104
+ /** 组件根(取页面语言的文案) */
105
+ readonly root: HTMLElement;
106
+ /** 标题层级偏移(0–5) */
107
+ readonly headingOffset: number;
108
+ /** 本实例的 id 前缀(同页多个 Markdown 不撞 id) */
109
+ readonly idPrefix: string;
110
+ /** 顶层段落是否首行缩进 */
111
+ readonly indent: boolean;
112
+ readonly highlight: KitHighlightEnginePort | null;
113
+ /** 代码块是否出复制钮 */
114
+ readonly copyCode: boolean;
115
+ }
116
+
117
+ function inlineInto(host: HTMLElement, nodes: readonly KitMdInline[], ctx: KitMdRenderContext): void {
118
+ for (const n of nodes) {
119
+ switch (n.t) {
120
+ case 'text': host.appendChild(document.createTextNode(n.v)); break;
121
+ case 'br': host.appendChild(document.createElement('br')); break;
122
+ case 'code': host.appendChild(mk('code', KIT_MD_CODE_CLASS, n.v)); break;
123
+ case 'strong': { const el = mk('strong', KIT_MD_STRONG_CLASS); inlineInto(el, n.c, ctx); host.appendChild(el); break; }
124
+ case 'em': { const el = mk('em', ''); inlineInto(el, n.c, ctx); host.appendChild(el); break; }
125
+ case 'del': { const el = mk('del', KIT_MD_DEL_CLASS); inlineInto(el, n.c, ctx); host.appendChild(el); break; }
126
+ case 'link': {
127
+ const a = mk('a', KIT_MD_LINK_CLASS);
128
+ a.href = n.href.startsWith('#md-') ? `#${ctx.idPrefix}${n.href.slice(1)}` : n.href;
129
+ if (n.title) a.title = n.title;
130
+ inlineInto(a, n.c, ctx);
131
+ if (n.external) {
132
+ a.target = '_blank';
133
+ a.rel = 'noopener noreferrer nofollow';
134
+ const icon = kitIcon('external-link', 'xs', EXT_ICON_CLASS);
135
+ icon.setAttribute('aria-hidden', 'true');
136
+ a.appendChild(icon);
137
+ a.appendChild(mk('span', 'sr-only', kitText('soma.kit.md_external', undefined, ctx.root)));
138
+ }
139
+ host.appendChild(a);
140
+ break;
141
+ }
142
+ case 'image': {
143
+ const img = mk('img', KIT_MD_IMG_CLASS);
144
+ img.src = n.src;
145
+ img.alt = n.alt;
146
+ if (n.title) img.title = n.title;
147
+ img.setAttribute('loading', 'lazy');
148
+ img.setAttribute('decoding', 'async');
149
+ img.setAttribute('referrerpolicy', 'no-referrer');
150
+ img.addEventListener('error', () => {
151
+ img.replaceWith(mk('span', IMG_FAIL_CLASS, kitText('soma.kit.md_image_failed', { alt: n.alt !== '' ? n.alt : n.src }, ctx.root)));
152
+ }, { once: true });
153
+ host.appendChild(img);
154
+ break;
155
+ }
156
+ case 'fnref': {
157
+ const sup = mk('sup', KIT_MD_FNREF_CLASS);
158
+ const a = mk('a', KIT_MD_LINK_CLASS, `[${n.n}]`);
159
+ a.href = `#${ctx.idPrefix}${n.id}`;
160
+ a.setAttribute('aria-label', kitText('soma.kit.md_fnref', { n: n.n }, ctx.root));
161
+ sup.appendChild(a);
162
+ host.appendChild(sup);
163
+ break;
164
+ }
165
+ default: break;
166
+ }
167
+ }
168
+ }
169
+
170
+ /** 一个块 → DOM(level = 0 表示顶层,用于首行缩进判定) */
171
+ export function renderMdBlock(b: KitMdBlock, ctx: KitMdRenderContext, level: number): HTMLElement {
172
+ switch (b.t) {
173
+ case 'heading': {
174
+ const depth = Math.min(6, b.depth + ctx.headingOffset);
175
+ const h = mk(`h${depth}` as 'h1', kitMdHeadingClass(depth));
176
+ h.id = `${ctx.idPrefix}${b.id}`;
177
+ inlineInto(h, b.inline, ctx);
178
+ return h;
179
+ }
180
+ case 'paragraph': {
181
+ const cls = b.tight ? KIT_MD_P_TIGHT_CLASS : level === 0 && ctx.indent && !imageOnly(b.inline) ? KIT_MD_P_INDENT_CLASS : KIT_MD_P_CLASS;
182
+ const p = mk('p', cls);
183
+ inlineInto(p, b.inline, ctx);
184
+ return p;
185
+ }
186
+ case 'list': {
187
+ const tasky = b.items.some((it) => it.task !== null);
188
+ const list = mk(b.ordered ? 'ol' : 'ul', `${KIT_MD_LIST_CLASS} ${tasky ? '' : KIT_MD_LIST_STYLE[b.ordered ? 'ol' : 'ul']}`.trim());
189
+ if (b.ordered && b.start !== undefined) (list as HTMLOListElement).start = b.start;
190
+ for (const it of b.items) {
191
+ const li = mk('li', it.task !== null ? KIT_MD_TASK_CLASS : KIT_MD_LI_CLASS);
192
+ if (it.task !== null) {
193
+ const box = mk('span', TASK_BOX_CLASS);
194
+ box.setAttribute('role', 'checkbox');
195
+ box.setAttribute('aria-checked', it.task ? 'true' : 'false');
196
+ box.setAttribute('aria-disabled', 'true');
197
+ box.setAttribute('aria-label', kitText(it.task ? 'soma.kit.md_task_done' : 'soma.kit.md_task_todo', undefined, ctx.root));
198
+ if (it.task) box.appendChild(kitIcon('check', 'xs'));
199
+ li.appendChild(box);
200
+ const body = mk('div', 'min-w-0');
201
+ for (const c of it.blocks) body.appendChild(renderMdBlock(c, ctx, level + 1));
202
+ li.appendChild(body);
203
+ } else {
204
+ for (const c of it.blocks) li.appendChild(renderMdBlock(c, ctx, level + 1));
205
+ }
206
+ list.appendChild(li);
207
+ }
208
+ return list;
209
+ }
210
+ case 'quote': {
211
+ const q = mk('blockquote', KIT_MD_QUOTE_CLASS);
212
+ for (const c of b.blocks) q.appendChild(renderMdBlock(c, ctx, level + 1));
213
+ return q;
214
+ }
215
+ case 'code': {
216
+ const well = mk('div', CODE_WELL_CLASS);
217
+ well.setAttribute(KIT_PART_ATTRIBUTE, KIT_PART_WELL);
218
+ well.setAttribute('data-kit-md-code', '');
219
+ const hl = ctx.highlight;
220
+ const language = hl === null ? 'text' : hl.resolveLanguage({ fence: b.lang, sample: b.text.length <= KIT_CONTENT_LIMITS.codeView.sniffMaxChars ? b.text : '' });
221
+ const label = language !== 'text' && hl !== null ? hl.languageLabel(language) : b.lang;
222
+ if (label !== '' || ctx.copyCode) {
223
+ const head = mk('div', CODE_HEAD_CLASS);
224
+ head.appendChild(mk('span', KIT_CODE_LANG_CLASS, label));
225
+ if (ctx.copyCode) head.appendChild(textActionButton('md-copy-code', kitText('soma.kit.copy', undefined, ctx.root), 'primary'));
226
+ well.appendChild(head);
227
+ }
228
+ well.setAttribute('role', 'region');
229
+ well.setAttribute('data-kit-container', 'plain');
230
+ well.setAttribute('aria-label', kitText('soma.kit.code_region', { name: label !== '' ? label : kitText('soma.kit.code_plain', undefined, ctx.root) }, ctx.root));
231
+ paintCodeLines(well, b.text, { language: b.closed ? language : 'text', wrap: codeWrapDefault(language, b.text.split('\n')), port: b.closed ? hl : null, root: ctx.root });
232
+ return well;
233
+ }
234
+ case 'table': {
235
+ const wrap = mk('div', KIT_MD_TABLE_WRAP_CLASS);
236
+ wrap.tabIndex = 0;
237
+ wrap.setAttribute('role', 'region');
238
+ wrap.setAttribute('data-kit-container', 'plain');
239
+ wrap.setAttribute('aria-label', kitText('soma.kit.md_table', undefined, ctx.root));
240
+ const table = mk('table', KIT_MD_TABLE_CLASS);
241
+ const alignClass = (i: number): string => (b.align[i] === 'right' ? ' text-end' : b.align[i] === 'center' ? ' text-center' : ' text-start');
242
+ const thead = mk('thead', '');
243
+ const hr = mk('tr', '');
244
+ b.head.forEach((cell, i) => { const th = mk('th', `${KIT_MD_TH_CLASS}${alignClass(i)}`); th.scope = 'col'; inlineInto(th, cell, ctx); hr.appendChild(th); });
245
+ thead.appendChild(hr);
246
+ table.appendChild(thead);
247
+ const tbody = mk('tbody', '');
248
+ for (const row of b.rows) {
249
+ const tr = mk('tr', '');
250
+ row.forEach((cell, i) => { const td = mk('td', `${KIT_MD_TD_CLASS}${alignClass(i)}`); inlineInto(td, cell, ctx); tr.appendChild(td); });
251
+ tbody.appendChild(tr);
252
+ }
253
+ table.appendChild(tbody);
254
+ wrap.appendChild(table);
255
+ return wrap;
256
+ }
257
+ case 'hr': return mk('hr', KIT_MD_HR_CLASS);
258
+ case 'html': return mk('pre', KIT_MD_HTML_CLASS, b.text);
259
+ case 'footnotes': {
260
+ const sec = mk('section', KIT_MD_FOOTNOTES_CLASS);
261
+ sec.setAttribute('data-kit-container', 'plain');
262
+ sec.setAttribute('aria-label', kitText('soma.kit.md_footnotes', undefined, ctx.root));
263
+ const ol = mk('ol', `${KIT_MD_LIST_CLASS} ${KIT_MD_LIST_STYLE.ol}`);
264
+ for (const f of b.items) {
265
+ const li = mk('li', KIT_MD_LI_CLASS);
266
+ li.id = `${ctx.idPrefix}${f.id}`;
267
+ for (const c of f.blocks) li.appendChild(renderMdBlock(c, ctx, level + 1));
268
+ ol.appendChild(li);
269
+ }
270
+ sec.appendChild(ol);
271
+ return sec;
272
+ }
273
+ default: return mk('div', '');
274
+ }
275
+ }
276
+
277
+ /** 纯文本降级:按空行分段 */
278
+ export function renderMdPlain(host: HTMLElement, text: string): void {
279
+ for (const para of text.split(/\n{2,}/u)) if (para.trim() !== '') host.appendChild(mk('p', PLAIN_P_CLASS, para));
280
+ }
281
+
282
+ /** 块尾提示:原始 HTML、不安全地址、截断 */
283
+ export function mdNotes(meta: KitMdMeta, root: HTMLElement): HTMLElement[] {
284
+ const out: HTMLElement[] = [];
285
+ if (meta.dropped.html > 0) out.push(mk('p', NOTE_CLASS, kitText('soma.kit.md_html_dropped', { n: meta.dropped.html }, root)));
286
+ if (meta.dropped.unsafeUrls > 0) out.push(mk('p', NOTE_CLASS, kitText('soma.kit.md_unsafe_urls', { n: meta.dropped.unsafeUrls }, root)));
287
+ if (meta.truncated) out.push(mk('p', NOTE_CLASS, kitText('soma.kit.md_truncated', undefined, root)));
288
+ return out;
289
+ }
290
+
291
+ // ── 组件 ──────────────────────────────────────────────────────────────
292
+
293
+ interface ViewState {
294
+ source: string | null;
295
+ result: KitMdResult | null;
296
+ seq: number;
297
+ /** 流式:已画块的指纹与节点 */
298
+ keys: string[];
299
+ nodes: HTMLElement[];
300
+ timer: ReturnType<typeof setTimeout> | null;
301
+ lastParse: number;
302
+ indent: boolean;
303
+ }
304
+
305
+ let instanceSeq = 0;
306
+
307
+ export function createMarkdownView(): SomaComponentDefinition {
308
+ const states = new WeakMap<HTMLElement, ViewState>();
309
+ const prefixes = new WeakMap<HTMLElement, string>();
310
+ const stateOf = (root: HTMLElement): ViewState => {
311
+ let st = states.get(root);
312
+ if (st === undefined) { st = { source: null, result: null, seq: 0, keys: [], nodes: [], timer: null, lastParse: 0, indent: false }; states.set(root, st); }
313
+ return st;
314
+ };
315
+ const prefixOf = (root: HTMLElement): string => {
316
+ let p = prefixes.get(root);
317
+ if (p === undefined) { instanceSeq += 1; p = `kmd${instanceSeq}-`; prefixes.set(root, p); }
318
+ return p;
319
+ };
320
+
321
+ return {
322
+ contract: {
323
+ name: 'MarkdownView',
324
+ layer: 'data',
325
+ props: {
326
+ data: { type: 'any', default: '', desc: 'Markdown 原文字符串,或 { source | markdown | content | text },或字符串数组(按块拼接);经 core 端口 engines.markdown 解析' },
327
+ path: { type: 'string', default: '', desc: '只看 data 里的一个点路径(如 detail.description)' },
328
+ heading_offset: { type: 'number', default: 0, desc: '标题层级偏移(0–5):嵌在详情里时 # 从更低的层级开始,组件不另改层级' },
329
+ toc: { type: 'enum', values: ['auto', 'off'], default: 'auto', desc: '目录:auto = 二级以上标题够多且正文够长才出(阈值 kit-limits#content.markdownView)' },
330
+ stream: { type: 'boolean', default: false, desc: '流式(AI 逐字输出):原文不断增长,按帧节流重解析,只替换变化的块' },
331
+ copy_code: { type: 'boolean', default: true, desc: '代码块出「复制」钮' },
332
+ empty_text: { type: 'string', default: '', desc: '没有内容时的文案;缺省取内置文案' },
333
+ aria_label: { type: 'string', default: '', desc: '正文区的无障碍名称' },
334
+ class: { type: 'string', default: '', desc: '外部传入的类,追加在根节点类串末尾' },
335
+ },
336
+ emits: {
337
+ copy: { payload: { ok: { type: 'boolean' } }, desc: '代码块复制后抛;不带文本' },
338
+ },
339
+ },
340
+ services: ['engines'],
341
+ templateHtml: `<article data-kit-container="plain" data-soma-id="root" class="${ROOT_CLASS}"></article>`,
342
+ controllerFactory: createKitController((api) => ({
343
+ attach(root) {
344
+ const onClick = (event: Event): void => {
345
+ const btn = (event.target as HTMLElement | null)?.closest<HTMLElement>('[data-kit-action="md-copy-code"]');
346
+ if (!btn || !root.contains(btn)) return;
347
+ const well = btn.closest<HTMLElement>('[data-kit-md-code]');
348
+ const text = Array.from(well?.querySelectorAll<HTMLElement>('[data-kit-code-lines] > div') ?? [])
349
+ .map((row) => (row.lastElementChild?.textContent ?? '').replace(/^ $/u, '')).join('\n');
350
+ void (async () => {
351
+ let ok = false;
352
+ try { if (typeof navigator !== 'undefined' && navigator.clipboard) { await navigator.clipboard.writeText(text); ok = true; } } catch { ok = false; }
353
+ if (ok) {
354
+ btn.textContent = kitText('soma.kit.copied', undefined, root);
355
+ setTimeout(() => { btn.textContent = kitText('soma.kit.copy', undefined, root); }, KIT_CONTENT_LIMITS.codeView.copyFeedbackMs);
356
+ }
357
+ api.emit('copy', { ok });
358
+ })();
359
+ };
360
+ root.addEventListener('click', onClick);
361
+ return () => {
362
+ root.removeEventListener('click', onClick);
363
+ const st = states.get(root);
364
+ if (st?.timer) clearTimeout(st.timer);
365
+ states.delete(root);
366
+ };
367
+ },
368
+ render(root, p, renderApi) {
369
+ const st = stateOf(root);
370
+ const source = markdownSourceOf(pathOf(p.data, str(p.path)));
371
+ const stream = bool(p.stream);
372
+ if (source === st.source && st.result !== null) { paint(root, p, renderApi.services, st, false); return; }
373
+ st.source = source;
374
+ if (source.trim() === '') { st.result = null; st.seq += 1; paintEmpty(root, p); return; }
375
+ const port = kitEnginePort<KitMarkdownEnginePort>(renderApi.services, 'markdown');
376
+ if (port === null) { st.result = { ok: false, reason: 'engine-load-failed', plainText: source }; paint(root, p, renderApi.services, st, false); return; }
377
+ const run = (): void => {
378
+ st.timer = null;
379
+ st.lastParse = Date.now();
380
+ const mine = (st.seq += 1);
381
+ const text = st.source ?? '';
382
+ void port.parse(text).then((res) => {
383
+ if (st.seq !== mine) return;
384
+ st.result = res;
385
+ paint(root, api.props(), renderApi.services, st, stream);
386
+ }, () => {
387
+ if (st.seq !== mine) return;
388
+ st.result = { ok: false, reason: 'parse-error', plainText: text };
389
+ paint(root, api.props(), renderApi.services, st, false);
390
+ });
391
+ };
392
+ // 流式:距上次解析不足节流间隔就推迟到间隔末(最后一次一定会解析)
393
+ if (stream) {
394
+ if (st.timer !== null) return;
395
+ const wait = Math.max(0, ML.streamThrottleMs - (Date.now() - st.lastParse));
396
+ st.timer = setTimeout(run, wait);
397
+ return;
398
+ }
399
+ run();
400
+ },
401
+ })),
402
+ };
403
+
404
+ function pathOf(data: unknown, path: string): unknown {
405
+ if (path.trim() === '') return data;
406
+ let cur: unknown = data;
407
+ for (const part of path.trim().split('.')) {
408
+ if (cur === null || typeof cur !== 'object') return undefined;
409
+ cur = (cur as Record<string, unknown>)[part];
410
+ }
411
+ return cur;
412
+ }
413
+
414
+ function paintEmpty(root: HTMLElement, p: Record<string, unknown>): void {
415
+ const st = stateOf(root);
416
+ st.keys = [];
417
+ st.nodes = [];
418
+ root.className = joinClass(ROOT_CLASS, p.class);
419
+ root.textContent = '';
420
+ root.appendChild(emptyNode(str(p.empty_text, kitText('soma.kit.empty_content', undefined, root))));
421
+ }
422
+
423
+ function paint(root: HTMLElement, p: Record<string, unknown>, services: unknown, st: ViewState, incremental: boolean): void {
424
+ const res = st.result;
425
+ root.className = joinClass(ROOT_CLASS, p.class);
426
+ if (res === null) { paintEmpty(root, p); return; }
427
+ root.setAttribute('aria-busy', bool(p.stream) ? 'true' : 'false');
428
+ if (!res.ok) {
429
+ st.keys = [];
430
+ st.nodes = [];
431
+ root.textContent = '';
432
+ const body = mk('div', KIT_MD_BODY_CLASS);
433
+ renderMdPlain(body, res.plainText);
434
+ root.appendChild(body);
435
+ const key = res.reason === 'too-long' ? 'soma.kit.md_too_long' : res.reason === 'engine-load-failed' ? 'soma.kit.md_engine_failed' : 'soma.kit.md_parse_failed';
436
+ root.appendChild(mk('p', NOTE_CLASS, kitText(key, undefined, root)));
437
+ return;
438
+ }
439
+ const ctx: KitMdRenderContext = {
440
+ root, headingOffset: Math.max(0, Math.min(5, Math.floor(Number(p.heading_offset) || 0))), idPrefix: prefixOf(root),
441
+ indent: markdownIndentTopLevel(res.blocks), highlight: kitEnginePort<KitHighlightEnginePort>(services, 'highlight'),
442
+ copyCode: p.copy_code === undefined ? true : bool(p.copy_code),
443
+ };
444
+ const keys = res.blocks.map((b) => JSON.stringify(b));
445
+ let body = root.querySelector<HTMLElement>(':scope > [data-kit-md-body]');
446
+ // 流式增量:正文容器还在就从第一个变化的块起替换;否则整段重画
447
+ if (!incremental || body === null || st.nodes.length === 0 || st.nodes.some((n) => !body!.contains(n))) {
448
+ root.textContent = '';
449
+ const toc = markdownTocOf(res.meta, str(p.toc, 'auto'));
450
+ if (toc.length > 0) root.appendChild(tocNode(toc, ctx));
451
+ body = mk('div', KIT_MD_BODY_CLASS);
452
+ body.setAttribute('data-kit-md-body', '');
453
+ const label = str(p.aria_label);
454
+ if (label !== '') { body.setAttribute('role', 'region'); body.setAttribute('data-kit-container', 'plain'); body.setAttribute('aria-label', label); }
455
+ root.appendChild(body);
456
+ st.keys = [];
457
+ st.nodes = [];
458
+ }
459
+ let from = 0;
460
+ // 缩进判定随全文变化(单段 → 多段),变了就从头替换
461
+ if (ctx.indent === st.indent) while (from < keys.length && from < st.keys.length && keys[from] === st.keys[from]) from += 1;
462
+ st.indent = ctx.indent;
463
+ for (const n of st.nodes.slice(from)) n.remove();
464
+ const nodes = st.nodes.slice(0, from);
465
+ for (let i = from; i < res.blocks.length; i += 1) {
466
+ const el = renderMdBlock(res.blocks[i]!, ctx, 0);
467
+ body.appendChild(el);
468
+ nodes.push(el);
469
+ }
470
+ st.keys = keys;
471
+ st.nodes = nodes;
472
+ for (const old of Array.from(root.querySelectorAll(':scope > [data-kit-md-note]'))) old.remove();
473
+ for (const note of mdNotes(res.meta, root)) { note.setAttribute('data-kit-md-note', ''); root.appendChild(note); }
474
+ }
475
+
476
+ function tocNode(toc: KitMdMeta['outline'], ctx: KitMdRenderContext): HTMLElement {
477
+ const nav = mk('nav', TOC_CLASS);
478
+ nav.setAttribute('aria-label', kitText('soma.kit.md_toc', undefined, ctx.root));
479
+ nav.appendChild(mk('span', TOC_TITLE_CLASS, kitText('soma.kit.md_toc', undefined, ctx.root)));
480
+ for (const o of toc) {
481
+ const a = mk('a', `${KIT_MD_LINK_CLASS} ${TOC_ITEM_CLASS[o.depth] ?? 'ps-4'}`, o.text);
482
+ a.href = `#${ctx.idPrefix}${o.id}`;
483
+ nav.appendChild(a);
484
+ }
485
+ return nav;
486
+ }
487
+ }