soma-kit 0.1.14 → 0.1.16

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 (505) hide show
  1. package/README.md +1 -1
  2. package/package.json +8 -5
  3. package/packs/ai/model-card.ts +3 -3
  4. package/packs/finance/reconcile-desk/compile.ts +1 -1
  5. package/packs/finance/reconcile-desk/shell.ts +1 -1
  6. package/packs/ops/error-budget-card.ts +3 -3
  7. package/packs/ops/release-readiness-card.ts +3 -3
  8. package/packs/security/control-evidence-card.ts +3 -3
  9. package/packs/security/finding-card.ts +3 -2
  10. package/packs/shared/card-util.ts +17 -0
  11. package/spec/generated/kit-app.schema.json +2148 -338
  12. package/spec/generated/kit-page.schema.json +1152 -87
  13. package/spec/kit-grammar.json +1084 -136
  14. package/spec/kit-grammar.schema.json +167 -26
  15. package/src/app/app-config.ts +220 -187
  16. package/src/app/component-gate.ts +2 -2
  17. package/src/app/compose-apps.ts +5 -2
  18. package/src/app/define-kit-actions.ts +200 -22
  19. package/src/app/define-kit-app.ts +54 -8
  20. package/src/app/define-kit-view.ts +1 -1
  21. package/src/app/index.ts +12 -7
  22. package/src/app/kit-view-context.ts +50 -3
  23. package/src/app/list-page-defaults.ts +14 -0
  24. package/src/app/server-pages.ts +239 -7
  25. package/src/app/server.ts +466 -25
  26. package/src/app/theme-endpoint.ts +68 -24
  27. package/src/app/theme-runtime.ts +421 -87
  28. package/src/app/theme-shards.ts +69 -0
  29. package/src/app/tier-compat.ts +107 -0
  30. package/src/base/action-busy.ts +215 -38
  31. package/src/base/affix.ts +137 -0
  32. package/src/base/alert.ts +107 -59
  33. package/src/base/anchored-layer.ts +8 -7
  34. package/src/base/avatar.ts +147 -61
  35. package/src/base/badge.ts +186 -0
  36. package/src/base/button-group.ts +227 -0
  37. package/src/base/button.ts +365 -53
  38. package/src/base/card.ts +233 -0
  39. package/src/base/cascader.ts +147 -32
  40. package/src/base/check-core.ts +196 -33
  41. package/src/base/checkbox.ts +67 -2
  42. package/src/base/choice.ts +132 -31
  43. package/src/base/collapse.ts +249 -0
  44. package/src/base/color-picker.ts +404 -28
  45. package/src/base/combobox.ts +6 -2
  46. package/src/base/command-palette.ts +155 -37
  47. package/src/base/context-menu.ts +26 -6
  48. package/src/base/countdown.ts +37 -15
  49. package/src/base/date-range.ts +115 -94
  50. package/src/base/date.ts +487 -76
  51. package/src/base/delta.ts +20 -11
  52. package/src/base/divider.ts +64 -97
  53. package/src/base/end-edge.ts +10 -4
  54. package/src/base/fab.ts +64 -23
  55. package/src/base/gap-value.ts +35 -16
  56. package/src/base/hint-tips.ts +100 -30
  57. package/src/base/identity-cells.ts +839 -0
  58. package/src/base/illustrations.ts +6 -4
  59. package/src/base/image.ts +40 -19
  60. package/src/base/index.ts +92 -24
  61. package/src/base/inline-error.ts +90 -0
  62. package/src/base/input.ts +174 -38
  63. package/src/base/kbd.ts +31 -17
  64. package/src/base/kit-contract.ts +400 -0
  65. package/src/base/link.ts +41 -20
  66. package/src/base/listbox-core.ts +324 -95
  67. package/src/base/loading-gate.ts +3 -0
  68. package/src/base/look.ts +197 -0
  69. package/src/base/mentions.ts +58 -22
  70. package/src/base/menu-button.ts +129 -42
  71. package/src/base/menu-core.ts +210 -26
  72. package/src/base/month-grid.ts +60 -3
  73. package/src/base/motion/aura.ts +52 -10
  74. package/src/base/motion/hover-3d.ts +10 -5
  75. package/src/base/motion/hover-gallery.ts +19 -12
  76. package/src/base/motion/limits.ts +10 -0
  77. package/src/base/motion/marquee.ts +18 -11
  78. package/src/base/motion/text-rotate.ts +34 -16
  79. package/src/base/notification.ts +292 -0
  80. package/src/base/number.ts +93 -12
  81. package/src/base/otp.ts +143 -27
  82. package/src/base/overlay-runtime.ts +32 -24
  83. package/src/base/overlay-shell.ts +186 -0
  84. package/src/base/period-picker.ts +868 -0
  85. package/src/base/popover.ts +625 -74
  86. package/src/base/popup.ts +219 -78
  87. package/src/base/portal-core.ts +99 -2
  88. package/src/base/price-text.ts +51 -17
  89. package/src/base/progress.ts +100 -18
  90. package/src/base/qr-code.ts +64 -17
  91. package/src/base/qty-stepper.ts +145 -21
  92. package/src/base/radio.ts +43 -2
  93. package/src/base/range.ts +194 -39
  94. package/src/base/rating.ts +117 -31
  95. package/src/base/reason-tip.ts +60 -18
  96. package/src/base/relation-cells.ts +541 -0
  97. package/src/{frames → base}/resize-handle.ts +6 -4
  98. package/src/base/row-fresh.ts +84 -0
  99. package/src/base/section-spy.ts +79 -0
  100. package/src/base/segmented.ts +99 -56
  101. package/src/base/select.ts +8 -2
  102. package/src/base/shared.ts +520 -73
  103. package/src/base/spinner.ts +107 -0
  104. package/src/base/state-panel.ts +77 -22
  105. package/src/base/status-tone.ts +1 -1
  106. package/src/base/sticky-edge.ts +96 -29
  107. package/src/base/swap.ts +39 -21
  108. package/src/base/switch.ts +158 -38
  109. package/src/base/tabs.ts +292 -0
  110. package/src/base/tag-input.ts +129 -55
  111. package/src/base/tag.ts +203 -91
  112. package/src/base/text.ts +491 -77
  113. package/src/base/textarea.ts +89 -40
  114. package/src/base/time-picker.ts +341 -57
  115. package/src/base/time-range.ts +846 -0
  116. package/src/base/tree-select.ts +346 -89
  117. package/src/base/upload.ts +612 -158
  118. package/src/base/view-transition.ts +7 -3
  119. package/src/base/virtual-list.ts +49 -14
  120. package/src/biz/approval-desk/compile.ts +98 -6
  121. package/src/biz/approval-desk/index.ts +2 -0
  122. package/src/biz/approval-desk/shell.ts +53 -13
  123. package/src/biz/auth-panel/compile.ts +14 -4
  124. package/src/biz/auth-panel/shell.ts +28 -8
  125. package/src/biz/category-crud/compile.ts +64 -13
  126. package/src/biz/category-crud/index.ts +2 -0
  127. package/src/biz/category-crud/shell.ts +30 -8
  128. package/src/biz/checkout-page/compile.ts +38 -4
  129. package/src/biz/checkout-page/index.ts +1 -0
  130. package/src/biz/checkout-page/shell.ts +28 -10
  131. package/src/biz/compose.ts +9 -4
  132. package/src/biz/data-components.ts +2 -0
  133. package/src/biz/define.ts +1 -1
  134. package/src/biz/import-wizard/compile.ts +5 -2
  135. package/src/biz/import-wizard/index.ts +1 -0
  136. package/src/biz/import-wizard/shell.ts +36 -20
  137. package/src/biz/index.ts +5 -4
  138. package/src/biz/landing-page/compile.ts +4 -3
  139. package/src/biz/landing-page/shell.ts +25 -5
  140. package/src/biz/layout-contracts.ts +918 -0
  141. package/src/biz/link/hub.ts +199 -8
  142. package/src/biz/link/shared.ts +62 -16
  143. package/src/biz/master-sub/compile.ts +318 -38
  144. package/src/biz/master-sub/detail-head.ts +145 -21
  145. package/src/biz/master-sub/index.ts +6 -3
  146. package/src/biz/master-sub/shell.ts +232 -66
  147. package/src/biz/multi-board/compile.ts +89 -38
  148. package/src/biz/multi-board/composition.ts +7 -20
  149. package/src/biz/multi-board/index.ts +25 -9
  150. package/src/biz/multi-board/prose-fold.ts +17 -13
  151. package/src/biz/multi-board/shell.ts +153 -38
  152. package/src/biz/names.ts +1 -0
  153. package/src/biz/notification-center/compile.ts +28 -7
  154. package/src/biz/notification-center/index.ts +2 -0
  155. package/src/biz/notification-center/shell.ts +51 -11
  156. package/src/biz/page-templates/domain-templates.ts +147 -20
  157. package/src/biz/page-templates/result-page/compile.ts +5 -2
  158. package/src/biz/page-templates/result-page/index.ts +1 -0
  159. package/src/biz/page-templates/result-page/shell.ts +20 -6
  160. package/src/biz/page-templates/shared.ts +1 -1
  161. package/src/biz/page-templates/sign-in-page/compile.ts +20 -9
  162. package/src/biz/page-templates/sign-in-page/index.ts +1 -0
  163. package/src/biz/page-templates/sign-in-page/shell.ts +30 -14
  164. package/src/biz/record-detail/compile.ts +43 -12
  165. package/src/biz/record-detail/index.ts +1 -0
  166. package/src/biz/record-detail/shell.ts +42 -11
  167. package/src/biz/settings-center/compile.ts +5 -2
  168. package/src/biz/settings-center/index.ts +1 -0
  169. package/src/biz/settings-center/shell.ts +33 -9
  170. package/src/biz/shared/action-host.ts +146 -48
  171. package/src/biz/shared/compile-helpers.ts +134 -32
  172. package/src/biz/shared/coordinator.ts +727 -163
  173. package/src/biz/shared/focus-return.ts +180 -0
  174. package/src/biz/shared/object-aliases.ts +7 -1
  175. package/src/biz/shared/overlay-compile.ts +102 -24
  176. package/src/biz/shared/overlay-shell.ts +97 -116
  177. package/src/biz/shared/page-form-actions.ts +151 -0
  178. package/src/biz/shared/page-form.ts +255 -0
  179. package/src/biz/shared/pipeline.ts +74 -0
  180. package/src/biz/shared/runtime-hub.ts +101 -8
  181. package/src/biz/shared/verbs.ts +129 -0
  182. package/src/biz/single-form/compile.ts +6 -4
  183. package/src/biz/single-form/index.ts +2 -0
  184. package/src/biz/single-form/shell.ts +22 -8
  185. package/src/biz/standard-crud/compile.ts +213 -38
  186. package/src/biz/standard-crud/index.ts +2 -1
  187. package/src/biz/standard-crud/shell.ts +90 -13
  188. package/src/biz/standard-crud/summary.ts +2 -35
  189. package/src/biz/step-form/compile.ts +13 -4
  190. package/src/biz/step-form/hub.ts +168 -49
  191. package/src/biz/step-form/index.ts +1 -0
  192. package/src/biz/step-form/shell.ts +35 -17
  193. package/src/biz/types.ts +49 -6
  194. package/src/cli/app-layer-check.ts +375 -0
  195. package/src/cli/kit-cli.ts +179 -33
  196. package/src/cli/kit-init.ts +152 -3
  197. package/src/cli/migrate/theme-map.ts +35 -28
  198. package/src/cli/migrate/ts-rules.ts +2 -2
  199. package/src/cli/migrate/types.ts +3 -3
  200. package/src/cli/migrate/yaml-rules.ts +11 -9
  201. package/src/cli/view-writes.ts +13 -0
  202. package/src/compile/access-gate-attach.ts +1 -1
  203. package/src/compile/action-host-attach.ts +1 -1
  204. package/src/compile/closed-set.ts +102 -6
  205. package/src/compile/compile-page.ts +461 -273
  206. package/src/compile/component-candidates.ts +58 -5
  207. package/src/compile/danger-tier.ts +65 -0
  208. package/src/compile/hints.ts +6 -59
  209. package/src/compile/index.ts +2 -2
  210. package/src/compile/info-structure.ts +155 -0
  211. package/src/compile/layout-lint/index.ts +4 -1
  212. package/src/compile/layout-lint/rules-composition.ts +44 -13
  213. package/src/compile/layout-lint/rules-table.ts +4 -19
  214. package/src/compile/look-page.ts +551 -0
  215. package/src/compile/look.ts +376 -0
  216. package/src/compile/page-composition.ts +405 -67
  217. package/src/compile/page-hierarchy.ts +131 -0
  218. package/src/compile/page-pipeline-look.ts +156 -0
  219. package/src/compile/page-pipeline.ts +200 -0
  220. package/src/compile/parse.ts +12 -11
  221. package/src/compile/redirect.ts +1 -1
  222. package/src/compile/relation-render.ts +120 -0
  223. package/src/compile/remove-guard.ts +115 -41
  224. package/src/compile/stages.ts +786 -0
  225. package/src/compile/styles.ts +286 -48
  226. package/src/compile/types.ts +63 -6
  227. package/src/compile/view-check.ts +190 -1
  228. package/src/data/access-gate.ts +17 -9
  229. package/src/data/amount-breakdown.ts +52 -23
  230. package/src/data/anchor-nav.ts +77 -16
  231. package/src/data/approval-flow.ts +217 -126
  232. package/src/data/assignment-picker.ts +182 -94
  233. package/src/data/async-result-panel.ts +114 -46
  234. package/src/data/audit-log.ts +461 -0
  235. package/src/data/breadcrumbs.ts +150 -24
  236. package/src/data/calendar.ts +436 -97
  237. package/src/data/card-grid.ts +319 -0
  238. package/src/data/carousel.ts +81 -41
  239. package/src/data/cell-value.ts +253 -0
  240. package/src/data/chart.ts +1053 -96
  241. package/src/data/checklist.ts +82 -38
  242. package/src/data/code-view.ts +296 -44
  243. package/src/data/comment-thread.ts +611 -86
  244. package/src/data/compare-view.ts +227 -0
  245. package/src/data/confirm-dialog.ts +250 -39
  246. package/src/data/context-menu.ts +95 -21
  247. package/src/data/d9-limits.ts +2 -0
  248. package/src/data/d9-util.ts +13 -5
  249. package/src/data/diff.ts +109 -49
  250. package/src/data/display-util.ts +9 -4
  251. package/src/data/dock.ts +38 -18
  252. package/src/data/embed.ts +143 -8
  253. package/src/data/engine-ports.ts +135 -0
  254. package/src/data/field-mapper.ts +116 -54
  255. package/src/data/file-list.ts +522 -0
  256. package/src/data/flow-editor.ts +695 -158
  257. package/src/data/flow-node-options.ts +24 -5
  258. package/src/data/flow-remote-options.ts +94 -19
  259. package/src/data/footer.ts +88 -26
  260. package/src/data/form-draft-registry.ts +183 -12
  261. package/src/data/gantt.ts +640 -117
  262. package/src/data/graph-view.ts +51 -0
  263. package/src/data/heat-calendar.ts +412 -0
  264. package/src/data/hero.ts +40 -13
  265. package/src/data/image-viewer.ts +265 -62
  266. package/src/data/index.ts +75 -6
  267. package/src/data/item-list.ts +219 -58
  268. package/src/data/json-view.ts +909 -0
  269. package/src/data/kanban.ts +346 -91
  270. package/src/data/kit-contract.ts +230 -0
  271. package/src/data/leaderboard.ts +343 -0
  272. package/src/data/level-class.ts +21 -0
  273. package/src/data/log-stream.ts +347 -0
  274. package/src/data/markdown-view.ts +597 -0
  275. package/src/data/matrix.ts +234 -120
  276. package/src/data/media-grid.ts +165 -38
  277. package/src/data/mega-menu.ts +43 -26
  278. package/src/data/menu-bar.ts +254 -0
  279. package/src/data/menu-dom.ts +55 -19
  280. package/src/data/menu.ts +138 -48
  281. package/src/data/mockup.ts +37 -25
  282. package/src/data/modal-dialog.ts +126 -98
  283. package/src/data/navbar.ts +152 -66
  284. package/src/data/notice-list.ts +101 -49
  285. package/src/data/notify-renderer.ts +80 -15
  286. package/src/data/object-form.ts +1504 -164
  287. package/src/data/org-chart.ts +544 -0
  288. package/src/data/outcome-watch.ts +90 -21
  289. package/src/data/pager.ts +129 -45
  290. package/src/data/panel-head.ts +238 -76
  291. package/src/data/permission-matrix.ts +379 -120
  292. package/src/data/permission-tree.ts +146 -78
  293. package/src/data/pricing-table.ts +112 -43
  294. package/src/data/prompt-dialog.ts +49 -21
  295. package/src/data/reaction-bar.ts +67 -32
  296. package/src/data/record-card.ts +245 -72
  297. package/src/data/record-picker.ts +61 -28
  298. package/src/data/redirect.ts +39 -15
  299. package/src/data/request-console.ts +141 -38
  300. package/src/data/resident.ts +11 -13
  301. package/src/data/result-panel.ts +65 -27
  302. package/src/data/rich-text.ts +260 -127
  303. package/src/data/row-confirm.ts +47 -0
  304. package/src/data/row-editor.ts +384 -105
  305. package/src/data/rule-builder.ts +136 -81
  306. package/src/data/schedule-grid.ts +238 -0
  307. package/src/data/segment-bar.ts +221 -0
  308. package/src/data/shape-util.ts +90 -36
  309. package/src/data/stage-flow.ts +244 -0
  310. package/src/data/staged-rows.ts +207 -24
  311. package/src/data/stat-group.ts +493 -100
  312. package/src/data/static-lazy.ts +21 -0
  313. package/src/data/static-registry.ts +46 -4
  314. package/src/data/status-strip.ts +171 -0
  315. package/src/data/steps.ts +69 -36
  316. package/src/data/summary-strip.ts +136 -0
  317. package/src/data/summary-util.ts +116 -0
  318. package/src/data/survey.ts +134 -47
  319. package/src/data/system-switcher.ts +53 -24
  320. package/src/data/target-progress.ts +208 -0
  321. package/src/data/text-action-button.ts +28 -7
  322. package/src/data/text-diff.ts +731 -0
  323. package/src/data/tile-grid.ts +343 -0
  324. package/src/data/timeline.ts +205 -36
  325. package/src/data/tour-guide.ts +113 -47
  326. package/src/data/transfer.ts +204 -47
  327. package/src/data/tree-table.ts +228 -81
  328. package/src/data/tree.ts +193 -69
  329. package/src/data/trend-line.ts +68 -12
  330. package/src/data/virtual-rows.ts +248 -98
  331. package/src/data/waterfall.ts +171 -0
  332. package/src/data/watermark.ts +35 -6
  333. package/src/data/wrap.ts +28 -6
  334. package/src/frames/blank-frame.ts +6 -4
  335. package/src/frames/index.ts +4 -4
  336. package/src/frames/inherited-shell.ts +219 -0
  337. package/src/frames/page-bar.ts +208 -28
  338. package/src/frames/page-status.ts +3 -2
  339. package/src/frames/resident-components.ts +18 -0
  340. package/src/frames/shared.ts +73 -26
  341. package/src/frames/single-frame.ts +20 -4
  342. package/src/frames/split-frame/shell.ts +27 -17
  343. package/src/frames/split-frame/wiring.ts +16 -12
  344. package/src/frames/tabs-frame/shell.ts +14 -7
  345. package/src/frames/tabs-frame/wiring.ts +2 -1
  346. package/src/frames/top-main-frame.ts +55 -3
  347. package/src/frames/types.ts +5 -2
  348. package/src/frames/workspace-frame/extras.ts +23 -7
  349. package/src/frames/workspace-frame/index.ts +1 -1
  350. package/src/frames/workspace-frame/pipeline-key.ts +6 -0
  351. package/src/frames/workspace-frame/shell.ts +24 -3
  352. package/src/frames/workspace-frame/state.ts +42 -8
  353. package/src/frames/workspace-frame/view.ts +773 -194
  354. package/src/generated/kit-grammar-runtime.ts +1061 -77
  355. package/src/generated/kit-page.ts +272 -0
  356. package/src/i18n/index.ts +2 -0
  357. package/src/i18n/kit-text.ts +210 -5
  358. package/src/i18n/resolve-text-refs.ts +1 -1
  359. package/src/object-renderer/action-group.ts +204 -22
  360. package/src/object-renderer/action-more.ts +66 -19
  361. package/src/object-renderer/arrange.ts +270 -28
  362. package/src/object-renderer/category-tone.ts +96 -0
  363. package/src/object-renderer/collapse-wiring.ts +19 -9
  364. package/src/object-renderer/collection-expand.ts +3 -3
  365. package/src/object-renderer/collection-parts.ts +459 -103
  366. package/src/object-renderer/collection-table.ts +406 -59
  367. package/src/object-renderer/collection.ts +333 -71
  368. package/src/object-renderer/compile-data.ts +13 -3
  369. package/src/object-renderer/defaults.ts +14 -5
  370. package/src/object-renderer/emit-events.ts +46 -20
  371. package/src/object-renderer/emit-object.ts +35 -6
  372. package/src/object-renderer/emit-static.ts +831 -153
  373. package/src/object-renderer/field-value.ts +12 -239
  374. package/src/object-renderer/filter-plan.ts +3 -3
  375. package/src/object-renderer/filter-toolbar.ts +190 -0
  376. package/src/object-renderer/form-detail.ts +87 -2
  377. package/src/{compile → object-renderer}/fragment.ts +2 -2
  378. package/src/object-renderer/index.ts +1 -1
  379. package/src/object-renderer/key-field.ts +21 -0
  380. package/src/object-renderer/layout-facts.ts +55 -7
  381. package/src/object-renderer/layout-plan.ts +6 -3
  382. package/src/object-renderer/overlay-decide.ts +124 -0
  383. package/src/object-renderer/pick-component.ts +8 -2
  384. package/src/object-renderer/pipeline-mode.ts +6 -0
  385. package/src/object-renderer/relation-field.ts +79 -0
  386. package/src/object-renderer/render-object.ts +72 -27
  387. package/src/object-renderer/request-actions.ts +119 -21
  388. package/src/object-renderer/table-actions.ts +479 -111
  389. package/src/object-renderer/table-gap.ts +2 -1
  390. package/src/object-renderer/table-reorder.ts +237 -0
  391. package/src/object-renderer/table-summary.ts +26 -12
  392. package/src/object-renderer/table-tools.ts +437 -130
  393. package/src/object-renderer/types.ts +100 -17
  394. package/src/object-renderer/value-present.ts +49 -0
  395. package/src/page-target/ai-surface.ts +15 -22
  396. package/src/page-target/compile.ts +5 -6
  397. package/src/page-target/drift.ts +0 -7
  398. package/src/page-target/intent-schema.ts +46 -43
  399. package/src/page-target/target.ts +4 -5
  400. package/src/page-target/writer-policy.ts +4 -5
  401. package/src/recipes/app-blocks.ts +66 -0
  402. package/src/recipes/chrome-surface.ts +20 -0
  403. package/src/recipes/code-view.ts +57 -0
  404. package/src/recipes/color-role.ts +442 -0
  405. package/src/recipes/compact-group.ts +32 -0
  406. package/src/recipes/composition-projector.ts +321 -0
  407. package/src/recipes/container.ts +93 -26
  408. package/src/recipes/control.ts +85 -8
  409. package/src/recipes/desc-list.ts +108 -0
  410. package/src/recipes/divider.ts +74 -0
  411. package/src/recipes/emphasis.ts +102 -13
  412. package/src/recipes/field-text.ts +72 -0
  413. package/src/recipes/form-section.ts +177 -0
  414. package/src/recipes/frame-bleed.ts +6 -5
  415. package/src/recipes/index.ts +39 -5
  416. package/src/recipes/inherited-shell.ts +43 -0
  417. package/src/recipes/json-view.ts +50 -0
  418. package/src/recipes/look.ts +56 -0
  419. package/src/recipes/mark.ts +138 -0
  420. package/src/recipes/markdown.ts +96 -0
  421. package/src/recipes/overlay.ts +151 -37
  422. package/src/recipes/page-width.ts +51 -0
  423. package/src/recipes/pipeline-runtime.ts +366 -0
  424. package/src/recipes/placeholder.ts +38 -20
  425. package/src/recipes/rail-grid.ts +6 -3
  426. package/src/recipes/self-owned.ts +59 -0
  427. package/src/recipes/slot-align.ts +5 -3
  428. package/src/recipes/stat-state.ts +6 -6
  429. package/src/recipes/state.ts +64 -11
  430. package/src/recipes/status.ts +21 -20
  431. package/src/recipes/strip.ts +114 -0
  432. package/src/recipes/surface-edge.ts +3 -1
  433. package/src/recipes/surface.ts +40 -7
  434. package/src/recipes/table-gap.ts +4 -3
  435. package/src/recipes/table-native-edit.ts +25 -12
  436. package/src/recipes/table-row.ts +56 -20
  437. package/src/recipes/tabs.ts +140 -31
  438. package/src/recipes/text-diff.ts +97 -0
  439. package/src/recipes/text-fit.ts +132 -0
  440. package/src/recipes/title-row.ts +72 -5
  441. package/src/recipes/typography.ts +2 -2
  442. package/src/shared/action-func.ts +106 -0
  443. package/src/shared/color-scheme.ts +127 -0
  444. package/src/shared/confirm-decl.ts +5 -2
  445. package/src/shared/danger-facts.ts +55 -0
  446. package/src/shared/diagnostics.ts +16 -0
  447. package/src/shared/dom-attrs-registry.ts +1009 -0
  448. package/src/shared/dom-attrs.ts +743 -0
  449. package/src/shared/envelope.ts +1 -1
  450. package/src/shared/field-kind.ts +49 -0
  451. package/src/shared/field-value-format.ts +292 -0
  452. package/src/shared/focus-ring.ts +8 -0
  453. package/src/shared/glyphs.ts +127 -0
  454. package/src/shared/hints.ts +56 -0
  455. package/src/{base → shared}/icons.ts +40 -1
  456. package/src/shared/identifier-field.ts +66 -0
  457. package/src/shared/kit-error.ts +1 -1
  458. package/src/shared/list-pager.ts +23 -0
  459. package/src/shared/list-title.ts +29 -0
  460. package/src/{object-renderer → shared}/merge-class.ts +3 -2
  461. package/src/shared/order-value.ts +15 -0
  462. package/src/shared/page-attrs-runtime.ts +327 -0
  463. package/src/shared/page-attrs.ts +262 -0
  464. package/src/shared/path-guard.ts +1 -1
  465. package/src/shared/pipeline-mode.ts +64 -0
  466. package/src/shared/primitives-types.ts +8 -0
  467. package/src/shared/row-key.ts +15 -0
  468. package/src/shared/theme-runtime-shared.ts +181 -21
  469. package/src/shared/theme-usage.ts +16 -0
  470. package/src/shared/value-table-contract.ts +68 -0
  471. package/src/spatial/action-func.ts +4 -0
  472. package/src/spatial/declared-actions.ts +116 -0
  473. package/src/spatial/emit.ts +660 -0
  474. package/src/spatial/expand.ts +1482 -0
  475. package/src/spatial/field-types.ts +48 -0
  476. package/src/spatial/index.ts +82 -0
  477. package/src/spatial/layout.ts +697 -0
  478. package/src/spatial/look-apply.ts +206 -0
  479. package/src/spatial/page-decl.ts +44 -0
  480. package/src/spatial/page-object.ts +349 -0
  481. package/src/spatial/recognize.ts +491 -0
  482. package/src/spatial/self-report.ts +571 -0
  483. package/src/spatial/shape.ts +205 -0
  484. package/src/spatial/spatial-map.ts +136 -0
  485. package/src/spatial/tone.ts +145 -0
  486. package/src/theme/index.ts +11 -2
  487. package/src/theme/kit-theme-text.ts +1 -1
  488. package/src/theme/kit-theme.css +563 -28
  489. package/src/theme/kit-theme.tpl +527 -28
  490. package/src/theme/look-carrier.ts +65 -0
  491. package/src/theme/nine-dim-structure.ts +538 -176
  492. package/src/theme/private-vars.ts +153 -0
  493. package/src/theme/surface-layers.ts +12 -3
  494. package/src/theme/theme-tokens.ts +1602 -90
  495. package/src/theme/theme-types.ts +38 -59
  496. package/src/theme/value-table.ts +2379 -0
  497. package/src/app/envelope.ts +0 -1
  498. package/src/app/notify-renderer.ts +0 -1
  499. package/src/app/paged-list-adapter.ts +0 -1
  500. package/src/app/theme-runtime-shared.ts +0 -1
  501. package/src/compile/kit-error.ts +0 -1
  502. package/src/frames/list-summary.ts +0 -100
  503. package/src/recipes/nowrap.ts +0 -16
  504. package/src/theme/block-theme.ts +0 -202
  505. /package/src/{base → shared}/class-candidates.ts +0 -0
@@ -11,6 +11,7 @@
11
11
  // 本文件依次是:数据与配置形状、类串表、几何、撤销栈、分层布局、输入解析、图编辑规则、组件。
12
12
  // 纯函数(布局、几何、规则、撤销栈、解析)均已导出,供业务组件与测试直接用。
13
13
 
14
+ import { kitApplyLevelClass } from './level-class';
14
15
  import type { SomaComponentDefinition } from 'soma-core';
15
16
  import { mappingPrefixOf } from './flow-remote-options';
16
17
  import { clearFlowNodeField, withNodeOptions } from './flow-node-options';
@@ -18,10 +19,25 @@ import { FLOW_EDITOR_CONTRACT } from './flow-editor-contract';
18
19
  import { designFlowEditorGeometry } from 'soma-foundation/layout';
19
20
  import { KIT_DATA_LIMITS } from 'soma-foundation/kit-limits';
20
21
  import { applyCommon, bool, createKitController, joinClass, num, str } from '../base/shared';
22
+ import { KIT_TIPS_SCOPE_ATTR } from '../base/hint-tips';
21
23
  import { kitText, type KitTextKey } from '../i18n/kit-text';
22
24
  import { setKitFace } from '../recipes';
25
+ import { KIT_DIMMED_CLASS, KIT_FOCUS_RING } from '../recipes/state';
26
+ import { kitControlEdgeRecipe } from '../recipes/control';
27
+ import { kitShellRecipe } from '../recipes/container';
28
+ import { kitSurfaceRecipe } from '../recipes/surface';
29
+ import { mergeClass } from '../shared/merge-class';
30
+ import { kitClosedValueRecipe } from '../recipes/field-text';
31
+ import {
32
+ KIT_CANVAS_DOT_FILL_CLASS,
33
+ KIT_COLOR_ROLE_CLASS_CANDIDATES,
34
+ kitResolveStatusOrCategoryTone,
35
+ kitToneAccentBorderClass,
36
+ kitToneSoftBadgeClass,
37
+ } from '../recipes/color-role';
23
38
  import { kitEmphasisButtonRecipe } from '../recipes/emphasis';
24
- import { kitIcon, type KitIconName } from '../base/icons';
39
+ import { KIT_ICON_CLASS_CANDIDATES, kitIcon, resolveKitIconName, type KitIconName, type KitIconSize } from '../shared/icons';
40
+ import { kitGlyph } from '../shared/glyphs';
25
41
  import { createInput, KIT_INPUT_CLASS_CANDIDATES } from '../base/input';
26
42
  import { createTextarea, KIT_TEXTAREA_CLASS_CANDIDATES } from '../base/textarea';
27
43
  import { createSwitch, KIT_SWITCH_CLASS_CANDIDATES } from '../base/switch';
@@ -30,6 +46,10 @@ import { KIT_QTY_STEPPER_CLASS_CANDIDATES } from '../base/qty-stepper';
30
46
  import { KIT_LISTBOX_CLASS_CANDIDATES } from '../base/listbox-core';
31
47
  import { createFieldMapper, KIT_FIELD_MAPPER_CLASS_CANDIDATES } from './field-mapper';
32
48
  import { createKitEmbedBag, mountKitComponent, mountKitSelectField } from './embed';
49
+ import { kitMarkDataFacts, kitMarkLevel, kitMarkPart, kitMarkPicked } from './kit-contract';
50
+ import {
51
+ KIT_ATTR_CONTAINER, KIT_ATTR_FLOW_DRAFT_EDGE, KIT_ATTR_GRAPH_SUMMARY, KIT_ATTR_PORT_ACTIVE, KIT_ATTR_RETRY, KIT_ATTR_STATE,
52
+ } from '../shared/dom-attrs';
33
53
 
34
54
  // ════════════════════════════════════════════════════════════════
35
55
  // 数据与配置形状(纯类型 + 默认文案,无 DOM)
@@ -129,6 +149,12 @@ export interface FlowNodeType {
129
149
  }
130
150
 
131
151
  export type FlowLayoutMode = 'manual' | 'layered';
152
+ export type FlowDirection = 'LR' | 'TB';
153
+
154
+ export interface FlowEditorModeOptions {
155
+ /** GraphView 只读拓扑图模式:强制只读、无配置面板、支持 node_pick / edge_pick / retry 与无障碍邻接摘要表 */
156
+ graphView?: boolean;
157
+ }
132
158
 
133
159
  export interface FlowIssue {
134
160
  target: 'node' | 'edge';
@@ -148,6 +174,7 @@ export interface FlowSuggestion {
148
174
  export interface FlowConfig {
149
175
  nodeTypes: Record<string, FlowNodeType>;
150
176
  layout: FlowLayoutMode;
177
+ direction: FlowDirection;
151
178
  readonly: boolean;
152
179
  /** 允许成环,缺省 false:连线会形成环时拒绝 */
153
180
  allowCycles: boolean;
@@ -177,7 +204,7 @@ const FLOW_TEXT_KEYS: Readonly<Record<string, KitTextKey>> = {
177
204
 
178
205
  /** 默认文案(占位 `{x}` 原样保留);`at` 是元素(读页面语言)或语言串,缺省取 zh-CN */
179
206
  export function flowDefaultTexts(at?: Element | string | null): Record<string, string> {
180
- const out: Record<string, string> = { add: '+ {type}', nodeAria: '{type}:{label}' };
207
+ const out: Record<string, string> = { add: '{type}', nodeAria: '{type}:{label}' };
181
208
  for (const [k, key] of Object.entries(FLOW_TEXT_KEYS)) out[k] = kitText(key, undefined, at);
182
209
  return out;
183
210
  }
@@ -194,29 +221,36 @@ export function fmt(template: string, vars: Record<string, string | number>): st
194
221
  // hidden 与布局类分写两层:外层只管显隐,内层管布局。
195
222
  // ════════════════════════════════════════════════════════════════
196
223
 
224
+ const EDGE_STILL = kitControlEdgeRecipe({ wrapper: true, hover: false });
225
+ const EDGE_LIVE = kitControlEdgeRecipe({ wrapper: true });
226
+ const IN_PORT_BASE = `pointer-events-none absolute -left-1 top-10 -mt-1 h-2 w-2 rounded-full ${EDGE_STILL} bg-surface`;
197
227
  export const FLOW_CLASS = Object.freeze({
198
- root: 'flex w-full flex-col gap-2',
228
+ root: '@container flex w-full flex-col gap-2',
199
229
  toolbar: 'flex flex-wrap items-center gap-2',
200
- btn: kitEmphasisButtonRecipe('button.toolbar'),
201
- btnPrimary: 'inline-flex h-8 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border border-primary bg-primary px-3 text-sm text-primary-fg transition-colors hover:bg-primary-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
230
+ btnGroup: 'inline-flex shrink-0 flex-nowrap items-center gap-1',
231
+ btn: mergeClass(kitEmphasisButtonRecipe('button.toolbar'), 'shrink-0 whitespace-nowrap'),
232
+ btnPrimary: 'inline-flex h-8 shrink-0 items-center gap-1 whitespace-nowrap rounded-control border border-primary bg-primary px-3 text-sm text-primary-fg transition-colors hover:bg-primary-hover ' + KIT_FOCUS_RING.button + ' disabled:cursor-not-allowed disabled:bg-control-disabled disabled:text-fg-disabled',
202
233
  zoomLabel: 'text-xs text-fg-muted',
203
- row: 'flex w-full items-start gap-2',
204
- panelOuter: 'w-80 shrink-0',
205
- panel: 'flex h-120 flex-col gap-3 overflow-y-auto rounded-md border border-border-subtle bg-surface p-3',
206
- panelTitle: 'text-sm font-semibold text-fg',
234
+ row: 'flex w-full flex-col items-stretch gap-2 @2xl:flex-row @2xl:items-start',
235
+ panelOuter: 'w-full shrink-0 @2xl:w-80',
236
+ // 配置面板与画布外缘 = 壳配方(容器边,KT-B2);节点 / 端口 / 节点条的轮廓 = 控件轮廓(KT-B1);右键菜单 = 浮起表面(KT-B4)
237
+ panel: mergeClass('flex max-h-120 flex-col gap-3 overflow-y-auto p-3 @2xl:h-120', kitShellRecipe({ tone: 'base', shadow: false })),
238
+ panelHead: 'flex items-center justify-between gap-2',
239
+ panelTitle: 'min-w-0 flex-1 truncate text-sm font-semibold text-fg',
240
+ panelClose: 'inline-flex size-7 shrink-0 items-center justify-center rounded-item p-0 text-fg-muted transition-colors hover:bg-state-layer-hover active:bg-state-layer-press ' + KIT_FOCUS_RING.button,
207
241
  panelField: 'flex flex-col gap-1',
208
242
  panelFull: 'w-full',
209
243
  panelLabel: 'text-xs font-medium text-fg-muted',
210
244
  panelReq: 'ms-1 text-danger-on-soft',
211
245
  panelHelp: 'text-xs text-fg-muted',
212
- panelWarn: 'rounded-md bg-warning-soft px-2 py-1 text-xs text-warning-on-soft',
213
- stage: 'relative h-120 w-full touch-none select-none overflow-hidden rounded-md border border-border-subtle bg-surface-sunken focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
246
+ panelWarn: 'rounded-item bg-warning-soft px-2 py-1 text-xs text-warning-on-soft',
247
+ stage: mergeClass(mergeClass('relative h-120 min-w-0 w-full flex-1 touch-none select-none overflow-hidden', KIT_FOCUS_RING.button), kitShellRecipe({ tone: 'sunken', shadow: false })),
214
248
  svgRoot: 'absolute left-0 top-0 h-full w-full',
215
- gridDot: 'fill-border',
249
+ gridDot: KIT_CANVAS_DOT_FILL_CLASS,
216
250
  gridRect: 'h-full w-full',
217
251
  overlaySvg: 'pointer-events-none absolute left-0 top-0 h-full w-full',
218
252
  fo: 'overflow-visible',
219
- nodeBase: 'relative box-border flex h-auto min-h-full w-full flex-col justify-between gap-1 rounded-lg border px-3 py-2 text-sm text-fg shadow-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
253
+ nodeBase: 'relative box-border flex h-auto min-h-full w-full flex-col justify-between gap-1 rounded-card border px-3 py-2 text-sm text-fg shadow-xs ' + KIT_FOCUS_RING.button,
220
254
  head: 'flex items-center gap-2',
221
255
  body: 'flex min-w-0 flex-col',
222
256
  barCap: 'min-w-0 flex-1 truncate',
@@ -225,22 +259,25 @@ export const FLOW_CLASS = Object.freeze({
225
259
  line: 'truncate text-xs text-fg-muted',
226
260
  lineError: 'truncate text-xs text-danger-on-soft',
227
261
  lineWarning: 'truncate text-xs text-warning-on-soft',
228
- cfgBtn: 'shrink-0 rounded-sm px-1 text-xs text-fg-muted transition-colors hover:bg-state-layer-hover active:bg-state-layer-press focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
229
- inPort: 'pointer-events-none absolute -left-1 top-10 -mt-1 h-2 w-2 rounded-full border border-border bg-surface',
230
- outPort: 'absolute -right-2 top-10 -mt-2 h-4 w-4 p-0 cursor-crosshair rounded-full border border-border bg-surface hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
231
- bar: 'box-border flex h-full w-full items-center gap-1 rounded-md border border-border bg-surface px-2 text-xs text-fg shadow-sm',
262
+ cfgBtn: 'inline-flex size-6 shrink-0 items-center justify-center rounded-item p-0 text-xs text-fg-muted transition-colors hover:bg-state-layer-hover active:bg-state-layer-press ' + KIT_FOCUS_RING.button,
263
+ inPort: IN_PORT_BASE,
264
+ inPortSnap: mergeClass(IN_PORT_BASE, 'bg-primary ring-2 ring-primary'),
265
+ outPort: `absolute -right-2 top-10 -mt-2 h-4 w-4 p-0 cursor-crosshair rounded-full ${EDGE_LIVE} bg-surface hover:bg-state-layer-hover ${KIT_FOCUS_RING.button}`,
266
+ draftEdge: 'fill-none stroke-primary stroke-2 pointer-events-none',
267
+ bar: `box-border flex h-full w-full max-w-full items-center gap-1 overflow-hidden rounded-float ${EDGE_STILL} bg-surface px-2 text-xs text-fg shadow-sm`,
232
268
  edgeG: 'group cursor-pointer outline-none',
233
269
  edgeHit: 'fill-none stroke-transparent stroke-12',
234
270
  edgeLabel: 'fill-fg-muted text-xs',
235
271
  edgeLabelBg: 'fill-surface stroke-border-subtle',
236
272
  emptyOuter: '',
237
273
  emptyInner: 'pointer-events-none absolute inset-0 flex items-center justify-center px-4 text-center text-sm text-fg-muted',
238
- errorInner: 'rounded-md border border-danger bg-danger-soft px-3 py-2 text-sm text-danger-on-soft',
274
+ errorRow: 'flex flex-wrap items-center justify-between gap-2',
275
+ errorInner: 'min-w-0 flex-1 rounded-item border border-danger bg-danger-soft px-3 py-2 text-sm text-danger-on-soft',
239
276
  marqueeRect: 'fill-primary-soft stroke-primary opacity-50',
240
277
  menuFo: 'pointer-events-auto overflow-visible',
241
- menuInner: 'box-border flex w-full flex-col gap-1 rounded-md border border-border bg-surface p-1 shadow-lg',
242
- menuItem: 'rounded-sm px-2 py-1 text-start text-sm text-fg transition-colors hover:bg-state-layer-hover active:bg-state-layer-press focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring',
243
- menuItemDanger: 'rounded-sm px-2 py-1 text-start text-sm text-danger-on-soft transition-colors hover:bg-state-layer-hover active:bg-state-layer-press focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring',
278
+ menuInner: mergeClass('box-border flex w-full flex-col gap-1 p-1', kitSurfaceRecipe('raised')),
279
+ menuItem: 'rounded-item px-2 py-1 text-start text-sm text-fg transition-colors hover:bg-state-layer-hover active:bg-state-layer-press ' + KIT_FOCUS_RING.item,
280
+ menuItemDanger: 'rounded-item px-2 py-1 text-start text-sm text-danger-on-soft transition-colors hover:bg-state-layer-hover active:bg-state-layer-press ' + KIT_FOCUS_RING.item,
244
281
  status: 'text-xs text-fg-muted',
245
282
  srOnly: 'sr-only',
246
283
  hidden: 'hidden',
@@ -250,12 +287,13 @@ export const FLOW_CLASS = Object.freeze({
250
287
 
251
288
  export const FLOW_NODE_BG = Object.freeze({
252
289
  normal: 'bg-surface',
253
- selected: 'bg-primary-soft ring-2 ring-primary',
254
- ghost: 'bg-primary-soft opacity-80',
290
+ // 选中 = 主色环(不再直写 primary-soft 作选中底,KT-HB-F);建议虚影 = 面底 + 降透明
291
+ selected: 'bg-surface ring-2 ring-primary',
292
+ ghost: mergeClass('bg-surface', KIT_DIMMED_CLASS),
255
293
  });
256
294
 
257
295
  export const FLOW_NODE_BORDER = Object.freeze({
258
- normal: 'border-border',
296
+ normal: kitControlEdgeRecipe({ wrapper: true, hover: false }),
259
297
  error: 'border-danger',
260
298
  warning: 'border-warning',
261
299
  ghost: 'border-dashed border-primary',
@@ -279,13 +317,14 @@ export const FLOW_MARKER_FILL = Object.freeze({
279
317
  ghost: 'fill-primary',
280
318
  });
281
319
 
320
+ // 节点类型 / 状态小标签 = 闭集值出口(F7 kitClosedValueRecipe),仅追加 shrink-0
282
321
  export const FLOW_TONE_BADGE: Readonly<Record<FlowTone, string>> = Object.freeze({
283
- neutral: 'shrink-0 rounded-sm bg-surface-sunken px-1 text-xs text-fg-muted',
284
- info: 'shrink-0 rounded-sm bg-info-soft px-1 text-xs text-info-on-soft',
285
- success: 'shrink-0 rounded-sm bg-success-soft px-1 text-xs text-success-on-soft',
286
- warning: 'shrink-0 rounded-sm bg-warning-soft px-1 text-xs text-warning-on-soft',
287
- danger: 'shrink-0 rounded-sm bg-danger-soft px-1 text-xs text-danger-on-soft',
288
- primary: 'shrink-0 rounded-sm bg-primary-soft px-1 text-xs text-primary-on-soft',
322
+ neutral: mergeClass(kitClosedValueRecipe('neutral'), 'shrink-0'),
323
+ info: mergeClass(kitClosedValueRecipe('info'), 'shrink-0'),
324
+ success: mergeClass(kitClosedValueRecipe('success'), 'shrink-0'),
325
+ warning: mergeClass(kitClosedValueRecipe('warning'), 'shrink-0'),
326
+ danger: mergeClass(kitClosedValueRecipe('danger'), 'shrink-0'),
327
+ primary: mergeClass(kitClosedValueRecipe('primary'), 'shrink-0'),
289
328
  });
290
329
 
291
330
  export const FLOW_TONE_DOT: Readonly<Record<FlowTone, string>> = Object.freeze({
@@ -301,6 +340,10 @@ function split(value: string): string[] {
301
340
  return value.split(/\s+/).filter((c) => c !== '');
302
341
  }
303
342
 
343
+ const FLOW_AUTO_TONE_CANDIDATES: readonly string[] = (
344
+ ['neutral', 'primary', 'info', 'success', 'warning', 'danger', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8'] as const
345
+ ).flatMap((t) => [...split(kitToneSoftBadgeClass(t)), ...split(kitToneAccentBorderClass(t))]);
346
+
304
347
  /** 本组件自带的全部类(供编译器并入候选类):由上面的表推出,不手抄 */
305
348
  export const KIT_FLOW_EDITOR_CLASS_CANDIDATES: readonly string[] = Object.freeze(
306
349
  [...new Set([
@@ -312,6 +355,10 @@ export const KIT_FLOW_EDITOR_CLASS_CANDIDATES: readonly string[] = Object.freeze
312
355
  ...Object.values(FLOW_MARKER_FILL).flatMap(split),
313
356
  ...Object.values(FLOW_TONE_BADGE).flatMap(split),
314
357
  ...Object.values(FLOW_TONE_DOT).flatMap(split),
358
+ ...FLOW_AUTO_TONE_CANDIDATES,
359
+ ...KIT_COLOR_ROLE_CLASS_CANDIDATES,
360
+ 'inline-flex', 'size-5', 'items-center', 'justify-center', 'p-0',
361
+ ...KIT_ICON_CLASS_CANDIDATES,
315
362
  // 配置面板嵌入的基础组件与 FieldMapper
316
363
  ...KIT_INPUT_CLASS_CANDIDATES,
317
364
  ...KIT_TEXTAREA_CLASS_CANDIDATES,
@@ -363,15 +410,40 @@ export function inPort(p: Pt): Pt {
363
410
  return { x: p.x, y: p.y + FLOW_GEOMETRY.nodeH / 2 };
364
411
  }
365
412
 
413
+ /** 拖拽端口橡皮筋预览连线:起点锚定源端口中心,终点跟随画布世界坐标(或吸附至目标入端口中心)的三次贝塞尔路径 */
414
+ export function draftEdgePath(fromPort: Pt, toPt: Pt, direction: FlowDirection = 'LR'): string {
415
+ if (direction === 'TB') {
416
+ const dy = Math.max(FLOW_GEOMETRY.bezierMin, Math.abs(toPt.y - fromPort.y) / 2);
417
+ const c1 = { x: fromPort.x, y: fromPort.y + dy };
418
+ const c2 = { x: toPt.x, y: toPt.y - dy };
419
+ return `M ${r2(fromPort.x)} ${r2(fromPort.y)} C ${r2(c1.x)} ${r2(c1.y)} ${r2(c2.x)} ${r2(c2.y)} ${r2(toPt.x)} ${r2(toPt.y)}`;
420
+ }
421
+ const dx = Math.max(FLOW_GEOMETRY.bezierMin, Math.abs(toPt.x - fromPort.x) / 2);
422
+ const c1 = { x: fromPort.x + dx, y: fromPort.y };
423
+ const c2 = { x: toPt.x - dx, y: toPt.y };
424
+ return `M ${r2(fromPort.x)} ${r2(fromPort.y)} C ${r2(c1.x)} ${r2(c1.y)} ${r2(c2.x)} ${r2(c2.y)} ${r2(toPt.x)} ${r2(toPt.y)}`;
425
+ }
426
+
366
427
  /** 连线:从 from 的出端口到 to 的入端口的三次贝塞尔;mid 是 t=0.5 处,放连线标签 */
367
- export function edgeGeometry(from: Pt, to: Pt): { d: string; mid: Pt } {
428
+ export function edgeGeometry(from: Pt, to: Pt, direction: FlowDirection = 'LR'): { d: string; mid: Pt } {
429
+ if (direction === 'TB') {
430
+ const a = { x: from.x + FLOW_GEOMETRY.nodeW / 2, y: from.y + FLOW_GEOMETRY.nodeH };
431
+ const b = { x: to.x + FLOW_GEOMETRY.nodeW / 2, y: to.y };
432
+ const dy = Math.max(FLOW_GEOMETRY.bezierMin, Math.abs(b.y - a.y) / 2);
433
+ const c1 = { x: a.x, y: a.y + dy };
434
+ const c2 = { x: b.x, y: b.y - dy };
435
+ return {
436
+ d: draftEdgePath(a, b, 'TB'),
437
+ mid: { x: r2((a.x + 3 * c1.x + 3 * c2.x + b.x) / 8), y: r2((a.y + 3 * c1.y + 3 * c2.y + b.y) / 8) },
438
+ };
439
+ }
368
440
  const a = outPort(from);
369
441
  const b = inPort(to);
370
442
  const dx = Math.max(FLOW_GEOMETRY.bezierMin, Math.abs(b.x - a.x) / 2);
371
443
  const c1 = { x: a.x + dx, y: a.y };
372
444
  const c2 = { x: b.x - dx, y: b.y };
373
445
  return {
374
- d: `M ${r2(a.x)} ${r2(a.y)} C ${r2(c1.x)} ${r2(c1.y)} ${r2(c2.x)} ${r2(c2.y)} ${r2(b.x)} ${r2(b.y)}`,
446
+ d: draftEdgePath(a, b, 'LR'),
375
447
  mid: { x: r2((a.x + 3 * c1.x + 3 * c2.x + b.x) / 8), y: r2((a.y + 3 * c1.y + 3 * c2.y + b.y) / 8) },
376
448
  };
377
449
  }
@@ -507,7 +579,7 @@ export interface LayeredResult {
507
579
  backEdges: string[];
508
580
  }
509
581
 
510
- export function layeredLayout(nodes: readonly FlowNode[], edges: readonly FlowEdge[]): LayeredResult {
582
+ export function layeredLayout(nodes: readonly FlowNode[], edges: readonly FlowEdge[], direction: FlowDirection = 'LR'): LayeredResult {
511
583
  const ids = nodes.map((n) => n.id);
512
584
  const known = new Set(ids);
513
585
  const order = new Map(ids.map((id, i) => [id, i] as const));
@@ -561,7 +633,12 @@ export function layeredLayout(nodes: readonly FlowNode[], edges: readonly FlowEd
561
633
  const r = rank.get(id)!;
562
634
  const k = slot.get(r) ?? 0;
563
635
  slot.set(r, k + 1);
564
- positions.set(id, { x: pad + r * (nodeW + gapX), y: pad + k * (nodeH + gapY) });
636
+ positions.set(
637
+ id,
638
+ direction === 'TB'
639
+ ? { x: pad + k * (nodeW + gapX), y: pad + r * (nodeH + gapY) }
640
+ : { x: pad + r * (nodeW + gapX), y: pad + k * (nodeH + gapY) },
641
+ );
565
642
  }
566
643
  return { positions, ranks: rank, backEdges: edges.filter((e) => back.has(e.id)).map((e) => e.id) };
567
644
  }
@@ -893,8 +970,12 @@ export function suggestionsOf(raw: unknown): FlowSuggestion[] {
893
970
  return out;
894
971
  }
895
972
 
896
- function layoutOf(raw: unknown): FlowLayoutMode {
897
- return raw === 'layered' ? 'layered' : 'manual';
973
+ function layoutOf(raw: unknown, fallback: FlowLayoutMode = 'manual'): FlowLayoutMode {
974
+ return raw === 'layered' ? 'layered' : raw === 'manual' ? 'manual' : fallback;
975
+ }
976
+
977
+ function directionOf(raw: unknown): FlowDirection {
978
+ return typeof raw === 'string' && raw.toUpperCase() === 'TB' ? 'TB' : 'LR';
898
979
  }
899
980
 
900
981
  function tonesOf(raw: unknown): Record<string, FlowTone> {
@@ -919,14 +1000,19 @@ export function pickOf(props: Record<string, unknown>, key: string): unknown {
919
1000
  return empty ? rec(rec(props.data).config)[key] : v;
920
1001
  }
921
1002
 
922
- export function configOf(props: Record<string, unknown>, at?: Element | null): FlowConfig {
1003
+ export function configOf(
1004
+ props: Record<string, unknown>,
1005
+ at?: Element | null,
1006
+ defaults?: { readonly?: boolean; layout?: FlowLayoutMode },
1007
+ ): FlowConfig {
923
1008
  const dataCfg = rec(rec(props.data).config);
924
1009
  const pick = (key: string): unknown => pickOf(props, key);
925
1010
  return {
926
1011
  // nodeOptions:展示对象给的节点字段候选项(页面 nodeOptions: view.<成员>),并进对应 select 字段的 options
927
1012
  nodeTypes: nodeTypesOf(withNodeOptions(pick('nodeTypes'), pick('nodeOptions'))),
928
- layout: layoutOf(pick('layout')),
929
- readonly: bool(props.readonly) || bool(props.disabled) || bool(dataCfg.readonly),
1013
+ layout: layoutOf(pick('layout'), defaults?.layout ?? 'manual'),
1014
+ direction: directionOf(pick('direction')),
1015
+ readonly: defaults?.readonly === true || bool(props.readonly) || bool(props.disabled) || bool(dataCfg.readonly),
930
1016
  allowCycles: bool(pick('allowCycles')),
931
1017
  statusTones: tonesOf(pick('statusTones')),
932
1018
  texts: textsOf(pick('texts'), at),
@@ -1133,20 +1219,26 @@ export function moveInChain(
1133
1219
  return { ok: true, graph: { ...graph, nodes, edges }, a, b };
1134
1220
  }
1135
1221
 
1136
- /** 序号(只读):声明了 numbered 前缀的节点类型,按「分层、再按节点输入顺序」依次编号 `<前缀><n>`,随图实时重算,不保存 */
1137
- export function ordinalsOf(graph: FlowGraph, types: Readonly<Record<string, FlowNodeType>>): Map<string, string> {
1222
+ /** 序号(只读):声明了 numbered 前缀的节点类型(或 autoNumber 开启时全部节点),按「分层、再按节点输入顺序」依次编号,随图实时重算,不保存 */
1223
+ export function ordinalsOf(graph: FlowGraph, types: Readonly<Record<string, FlowNodeType>>, autoNumber = false): Map<string, string> {
1138
1224
  const out = new Map<string, string>();
1139
- if (!Object.values(types).some((t) => (t.numbered ?? '') !== '')) return out;
1225
+ const hasTyped = Object.values(types).some((t) => (t.numbered ?? '') !== '');
1226
+ if (!autoNumber && !hasTyped) return out;
1140
1227
  const ranks = layeredLayout(graph.nodes, graph.edges).ranks;
1141
1228
  const order = new Map(graph.nodes.map((n, i) => [n.id, i] as const));
1142
1229
  const counters = new Map<string, number>();
1230
+ let globalSeq = 0;
1143
1231
  const sorted = [...graph.nodes].sort((x, y) => ((ranks.get(x.id) ?? 0) - (ranks.get(y.id) ?? 0)) || (order.get(x.id)! - order.get(y.id)!));
1144
1232
  for (const n of sorted) {
1145
1233
  const prefix = types[n.type]?.numbered ?? '';
1146
- if (prefix === '') continue;
1147
- const c = (counters.get(n.type) ?? 0) + 1;
1148
- counters.set(n.type, c);
1149
- out.set(n.id, `${prefix}${c}`);
1234
+ if (prefix !== '') {
1235
+ const c = (counters.get(n.type) ?? 0) + 1;
1236
+ counters.set(n.type, c);
1237
+ out.set(n.id, `${prefix}${c}`);
1238
+ } else if (autoNumber) {
1239
+ globalSeq += 1;
1240
+ out.set(n.id, String(globalSeq));
1241
+ }
1150
1242
  }
1151
1243
  return out;
1152
1244
  }
@@ -1196,9 +1288,10 @@ interface DragPortLike {
1196
1288
 
1197
1289
  type Level = 'error' | 'warning' | '';
1198
1290
  type Press =
1199
- | { kind: 'node'; key: string; sx: number; sy: number; moved: boolean; additive: boolean; origin: Map<string, Pt> | null }
1200
- | { kind: 'pan'; sx: number; sy: number; moved: boolean; start: FlowView; additive: boolean }
1201
- | { kind: 'marquee'; sx: number; sy: number; moved: boolean; ax: number; ay: number };
1291
+ | { kind: 'node'; key: string; sx: number; sy: number; moved: boolean; hadButtons: boolean; additive: boolean; origin: Map<string, Pt> | null }
1292
+ | { kind: 'pan'; sx: number; sy: number; moved: boolean; hadButtons: boolean; start: FlowView; additive: boolean }
1293
+ | { kind: 'marquee'; sx: number; sy: number; moved: boolean; hadButtons: boolean; ax: number; ay: number }
1294
+ | { kind: 'port'; fromId: string; sx: number; sy: number; moved: boolean; hadButtons: boolean; snapTo: string | null };
1202
1295
 
1203
1296
  function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls = '', attrs: Record<string, string> = {}): HTMLElementTagNameMap[K] {
1204
1297
  const e = document.createElement(tag);
@@ -1230,7 +1323,9 @@ function place(target: Element, at: Pt, w: number, h: number): void {
1230
1323
  const keyOfNode = (id: string): string => `n:${id}`;
1231
1324
  const keyOfEdge = (id: string): string => `e:${id}`;
1232
1325
 
1233
- export function createFlowEditor(): SomaComponentDefinition {
1326
+ export function createFlowEditor(mode: FlowEditorModeOptions = {}): SomaComponentDefinition {
1327
+ const isGraphView = mode.graphView === true;
1328
+ const cfgDefaults = isGraphView ? { readonly: true, layout: 'layered' as const } : undefined;
1234
1329
  return {
1235
1330
  contract: FLOW_EDITOR_CONTRACT,
1236
1331
  services: ['engines', 'data'],
@@ -1242,9 +1337,21 @@ export function createFlowEditor(): SomaComponentDefinition {
1242
1337
  // ---- 状态
1243
1338
  let root: HTMLElement | null = null;
1244
1339
  let mounted = false;
1245
- let cfg: FlowConfig = configOf({});
1340
+ let cfg: FlowConfig = configOf({}, null, cfgDefaults);
1246
1341
  let graph: FlowGraph = { nodes: [], edges: [] };
1247
1342
  let history: FlowHistory = emptyHistory();
1343
+ const emittedSigs = new Set<string>();
1344
+ const recordEmitted = (g: FlowGraph): void => {
1345
+ if (emittedSigs.size >= 50) {
1346
+ const firstKey = emittedSigs.values().next().value;
1347
+ if (firstKey !== undefined) emittedSigs.delete(firstKey);
1348
+ }
1349
+ emittedSigs.add(graphSig(g));
1350
+ };
1351
+ const topologySig = (g: FlowGraph): string => JSON.stringify([
1352
+ g.nodes.map((n) => [n.id, n.type]),
1353
+ g.edges.map((e) => [e.id, e.from, e.to]),
1354
+ ]);
1248
1355
  let external: FlowIssue[] = [];
1249
1356
  let suggestions: FlowSuggestion[] = [];
1250
1357
  let rejected = new Set<string>();
@@ -1269,8 +1376,17 @@ export function createFlowEditor(): SomaComponentDefinition {
1269
1376
  // H2a:面板 select 字段的候选签名(宿主异步取到 / 换了候选就重画,不受「正在打字」保护)
1270
1377
  let panelOptsSig = '';
1271
1378
  let panelForce = false;
1379
+ // 面板代次守卫:节点切换、面板清空或卸载时递增,拦截旧嵌入控件迟到的异步变更回调
1380
+ let panelGen = 0;
1272
1381
  let hintEls: Array<{ el: HTMLElement; field: FlowField }> = [];
1273
1382
  const panelEmbeds = createKitEmbedBag();
1383
+ // 边标签外框按文本签名缓存(消除拖动节点、平移或面板键入时每帧对全图边重复触发 getBBox() 同步布局回流)
1384
+ const labelBoxCache = new Map<string, { w: number; h: number; dx: number; dy: number }>();
1385
+ // 端口拖拽橡皮筋预览线状态与 SVG 节点(仅在拖拽期间挂入 svgLayer,释放/取消/卸载即移除)
1386
+ let draftEdgeEl: SVGPathElement | null = null;
1387
+ let draftState: { fromId: string; endPt: Pt; snapTo: string | null } | null = null;
1388
+ let suppressNextPortClick = false;
1389
+ let recentPortDrop = '';
1274
1390
 
1275
1391
  // ---- 骨架元素(建一次)
1276
1392
  let panelOuter!: HTMLElement;
@@ -1292,14 +1408,19 @@ export function createFlowEditor(): SomaComponentDefinition {
1292
1408
  let emptyInner!: HTMLElement;
1293
1409
  let errorOuter!: HTMLElement;
1294
1410
  let errorInner!: HTMLElement;
1411
+ let retryBtn: HTMLButtonElement | null = null;
1412
+ let summaryTable: HTMLTableElement | null = null;
1295
1413
  let statusEl!: HTMLElement;
1296
1414
  let removers: Array<() => void> = [];
1297
1415
  let dndCleanups: Array<() => void> = [];
1298
1416
  let offMove: (() => void) | null = null;
1299
1417
 
1300
1418
  const t = (key: string, vars: Record<string, string | number> = {}): string => fmt(cfg.texts[key] ?? key, vars);
1301
- const editable = (): boolean => !cfg.readonly;
1419
+ const editable = (): boolean => !isGraphView && !cfg.readonly;
1302
1420
  const movable = (): boolean => editable() && cfg.layout === 'manual';
1421
+ const canZoom = (): boolean => P().zoomable !== false && P().zoomable !== 'false';
1422
+ const canPan = (): boolean => P().pannable !== false && P().pannable !== 'false';
1423
+ const autoFit = (): boolean => P().fit !== false && P().fit !== 'false';
1303
1424
  const dndPort = (): DragPortLike | null => {
1304
1425
  const engines = (api.services as { engines?: { dnd?: DragPortLike } } | undefined)?.engines;
1305
1426
  return engines?.dnd ?? null;
@@ -1312,7 +1433,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1312
1433
 
1313
1434
  // ---- 位置与问题
1314
1435
  const computePositions = (): Map<string, Pt> => {
1315
- const lay = layeredLayout(graph.nodes, graph.edges).positions;
1436
+ const lay = layeredLayout(graph.nodes, graph.edges, cfg.direction).positions;
1316
1437
  const out = new Map<string, Pt>();
1317
1438
  for (const n of graph.nodes) {
1318
1439
  const auto = lay.get(n.id) ?? { x: 0, y: 0 };
@@ -1368,10 +1489,21 @@ export function createFlowEditor(): SomaComponentDefinition {
1368
1489
  };
1369
1490
 
1370
1491
  const emitSelect = (lastKey?: string): void => {
1492
+ if (isGraphView) return;
1371
1493
  const k = lastKey ?? [...selected][selected.size - 1];
1372
1494
  if (k === undefined) api.emit('select', { id: '', kind: 'none' });
1373
1495
  else api.emit('select', { id: k.slice(2), kind: k.startsWith('n:') ? 'node' : 'edge' });
1374
1496
  };
1497
+ const emitNodePick = (id: string): void => {
1498
+ if (!isGraphView) return;
1499
+ const n = nodeById(id);
1500
+ if (n) api.emit('node_pick', { id, node: { ...n, ...(n.meta ? { meta: { ...n.meta } } : {}) } });
1501
+ };
1502
+ const emitEdgePick = (id: string): void => {
1503
+ if (!isGraphView) return;
1504
+ const ed = graph.edges.find((x) => x.id === id);
1505
+ if (ed) api.emit('edge_pick', { id, edge: { ...ed } });
1506
+ };
1375
1507
 
1376
1508
  const setSelection = (keys: Iterable<string>, lastKey?: string): void => {
1377
1509
  const next = new Set(keys);
@@ -1391,6 +1523,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1391
1523
  history = pushHistory(history, graph, FLOW_GEOMETRY.historyLimit, coalesce);
1392
1524
  graph = next;
1393
1525
  pruneSelection();
1526
+ recordEmitted(graph);
1394
1527
  api.emit('change', payload(graph));
1395
1528
  paint();
1396
1529
  };
@@ -1501,7 +1634,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1501
1634
 
1502
1635
  const autoLayout = (): void => {
1503
1636
  if (!movable()) return;
1504
- const lay = layeredLayout(graph.nodes, graph.edges).positions;
1637
+ const lay = layeredLayout(graph.nodes, graph.edges, cfg.direction).positions;
1505
1638
  commit(setPositions(graph, lay));
1506
1639
  fit();
1507
1640
  };
@@ -1510,6 +1643,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1510
1643
  const r = undoHistory(history, graph);
1511
1644
  if (!r) return;
1512
1645
  history = r.history; graph = r.graph; pruneSelection();
1646
+ recordEmitted(graph);
1513
1647
  api.emit('change', payload(graph));
1514
1648
  paint();
1515
1649
  };
@@ -1517,13 +1651,14 @@ export function createFlowEditor(): SomaComponentDefinition {
1517
1651
  const r = redoHistory(history, graph);
1518
1652
  if (!r) return;
1519
1653
  history = r.history; graph = r.graph; pruneSelection();
1654
+ recordEmitted(graph);
1520
1655
  api.emit('change', payload(graph));
1521
1656
  paint();
1522
1657
  };
1523
1658
 
1524
1659
  // ---- 内置节点配置面板:选中单个节点,按类型的 kind 字段画表单;改动 -> 新图 -> change(经 core 事件写回)+ node_change
1525
1660
  const panelTarget = (): { node: FlowNode; fields: FlowField[] } | null => {
1526
- if (P().panel === false) return null;
1661
+ if (isGraphView || P().panel === false) return null;
1527
1662
  const ids = selectedNodeIds();
1528
1663
  if (ids.length !== 1 || selectedEdgeIds().length > 0) return null;
1529
1664
  const node = nodeById(ids[0]!);
@@ -1532,7 +1667,8 @@ export function createFlowEditor(): SomaComponentDefinition {
1532
1667
  };
1533
1668
 
1534
1669
  let panelRefocus = '';
1535
- const setField = (id: string, f: FlowField, value: unknown): void => {
1670
+ const setField = (id: string, f: FlowField, value: unknown, gen = panelGen): void => {
1671
+ if (!mounted || !root || gen !== panelGen) return;
1536
1672
  const cur = nodeById(id);
1537
1673
  if (!cur || !editable()) return;
1538
1674
  const latest = panelFieldsOf(typeOf(cur)).find((x) => x.key === f.key) ?? f;
@@ -1552,7 +1688,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1552
1688
  return Array.isArray(v) ? v.map(String).join('、') : str(v);
1553
1689
  };
1554
1690
 
1555
- const buildMapping = (row: HTMLElement, id: string, f: FlowField, meta: Record<string, unknown>): void => {
1691
+ const buildMapping = (row: HTMLElement, id: string, f: FlowField, meta: Record<string, unknown>, gen: number): void => {
1556
1692
  const { targets, waiting } = mappingTargets(f, meta);
1557
1693
  if (waiting) {
1558
1694
  const by = panelFieldsOf(typeOf(nodeById(id)!)).find((x) => x.key === f.targets_by);
@@ -1573,15 +1709,16 @@ export function createFlowEditor(): SomaComponentDefinition {
1573
1709
  empty_text: f.empty_text ?? t('mapEmpty'),
1574
1710
  }, {
1575
1711
  change: (p: { value?: unknown }) => {
1712
+ if (!mounted || !root || gen !== panelGen) return;
1576
1713
  const { mapping, dropped } = cleanFlowMapping(p.value, prefix);
1577
1714
  warn.className = dropped.length > 0 ? FLOW_CLASS.panelWarn : FLOW_CLASS.hidden;
1578
1715
  warn.textContent = dropped.length > 0 ? t('dropped', { prefix, names: dropped.join('、') }) : '';
1579
- setField(id, f, mapping);
1716
+ setField(id, f, mapping, gen);
1580
1717
  },
1581
1718
  });
1582
1719
  };
1583
1720
 
1584
- const buildField = (node: FlowNode, f: FlowField): HTMLElement => {
1721
+ const buildField = (node: FlowNode, f: FlowField, gen: number): HTMLElement => {
1585
1722
  const meta = node.meta ?? {};
1586
1723
  const id = node.id;
1587
1724
  const ro = !editable();
@@ -1591,7 +1728,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1591
1728
  if (f.required) { const r = el('span', FLOW_CLASS.panelReq, { 'aria-hidden': 'true' }); r.textContent = '*'; lab.appendChild(r); }
1592
1729
  row.appendChild(lab);
1593
1730
  const common = { aria_label: f.label, disabled: ro, placeholder: f.placeholder ?? '' };
1594
- const set = (v: unknown): void => setField(id, f, v);
1731
+ const set = (v: unknown): void => setField(id, f, v, gen);
1595
1732
  switch (f.kind) {
1596
1733
  case 'text': mountCtl(createInput(), row, { ...common, value: str(meta[f.key]) }, { change: (p) => set(str(p.value)) }); break;
1597
1734
  case 'textarea': mountCtl(createTextarea(), row, { ...common, value: str(meta[f.key]) }, { change: (p) => set(str(p.value)) }); break;
@@ -1608,7 +1745,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1608
1745
  row.appendChild(sel.el);
1609
1746
  break;
1610
1747
  }
1611
- case 'mapping': buildMapping(row, id, f, meta); break;
1748
+ case 'mapping': buildMapping(row, id, f, meta, gen); break;
1612
1749
  default: break;
1613
1750
  }
1614
1751
  if (f.help) { const h = el('p', FLOW_CLASS.panelHelp); h.textContent = f.help; row.appendChild(h); }
@@ -1621,15 +1758,26 @@ export function createFlowEditor(): SomaComponentDefinition {
1621
1758
  };
1622
1759
 
1623
1760
  const buildPanel = (node: FlowNode, fields: readonly FlowField[]): void => {
1761
+ const gen = ++panelGen;
1624
1762
  panelEmbeds.release(panelInner);
1625
1763
  panelInner.textContent = '';
1626
1764
  hintEls = [];
1765
+ const head = el('div', FLOW_CLASS.panelHead);
1627
1766
  panelTitleEl = el('h3', FLOW_CLASS.panelTitle);
1628
- panelInner.appendChild(panelTitleEl);
1629
- for (const f of fields) panelInner.appendChild(buildField(node, f));
1767
+ panelTitleEl.setAttribute(KIT_TIPS_SCOPE_ATTR, '');
1768
+ const closeBtn = el('button', FLOW_CLASS.panelClose, {
1769
+ type: 'button',
1770
+ 'data-flow-act': 'panel-close',
1771
+ 'aria-label': kitText('soma.kit.close', undefined, root),
1772
+ });
1773
+ closeBtn.appendChild(kitIcon('close', 'sm'));
1774
+ head.append(panelTitleEl, closeBtn);
1775
+ panelInner.appendChild(head);
1776
+ for (const f of fields) panelInner.appendChild(buildField(node, f, gen));
1630
1777
  };
1631
1778
 
1632
1779
  const clearPanel = (): void => {
1780
+ panelGen += 1;
1633
1781
  panelEmbeds.release(panelInner);
1634
1782
  panelInner.textContent = '';
1635
1783
  hintEls = [];
@@ -1639,8 +1787,15 @@ export function createFlowEditor(): SomaComponentDefinition {
1639
1787
  };
1640
1788
 
1641
1789
  const focusPanel = (key = ''): void => {
1642
- const scope = key === '' ? panelInner : panelInner.querySelector<HTMLElement>(`[data-flow-field="${key}"]`) ?? panelInner;
1643
- scope.querySelector<HTMLElement>('[role="combobox"], input:not([type="hidden"]), textarea, button')?.focus();
1790
+ if (key !== '') {
1791
+ const scope = panelInner.querySelector<HTMLElement>(`[data-flow-field="${key}"]`);
1792
+ if (scope) {
1793
+ scope.querySelector<HTMLElement>('[role="combobox"], input:not([type="hidden"]), textarea, button')?.focus();
1794
+ return;
1795
+ }
1796
+ }
1797
+ const firstCtl = panelInner.querySelector<HTMLElement>('[data-flow-field] [role="combobox"], [data-flow-field] input:not([type="hidden"]), [data-flow-field] textarea, [data-flow-field] button');
1798
+ (firstCtl ?? panelInner.querySelector<HTMLElement>('[data-flow-act="panel-close"]'))?.focus();
1644
1799
  };
1645
1800
 
1646
1801
  function paintPanel(): void {
@@ -1664,7 +1819,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1664
1819
  if (f.kind === 'mapping') {
1665
1820
  const by = f.targets_by !== undefined ? str(node.meta?.[f.targets_by]) : '';
1666
1821
  const base = f.targets_by !== undefined ? (f.targets_map?.[by] ?? []) : (f.targets ?? []);
1667
- return [f.key, f.prefix ?? '', by, base.map((x) => [x.key, x.label])];
1822
+ return [f.key, f.prefix ?? '', f.placeholder ?? '', f.empty_text ?? '', by, base.map((x) => [x.key, x.label, x.hint ?? ''])];
1668
1823
  }
1669
1824
  return null;
1670
1825
  }));
@@ -1711,7 +1866,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1711
1866
  }
1712
1867
 
1713
1868
  const requestConfig = (id: string): void => {
1714
- if (!nodeById(id)) return;
1869
+ if (isGraphView || !nodeById(id)) return;
1715
1870
  const key = keyOfNode(id);
1716
1871
  if (!(selected.size === 1 && selected.has(key))) { setSelection([key], key); paint(); }
1717
1872
  api.emit('node_config', { id });
@@ -1745,12 +1900,47 @@ export function createFlowEditor(): SomaComponentDefinition {
1745
1900
  gridDot.setAttribute('cy', String(step / 2));
1746
1901
  }
1747
1902
  };
1903
+ let userAdjustedView = false;
1904
+ let lastStageW = 0;
1905
+ let lastStageH = 0;
1906
+ const isFormField = (): boolean => typeof P().name === 'string' && P().name !== '';
1748
1907
  const stageSize = (): { w: number; h: number } => ({ w: stage.clientWidth || 0, h: stage.clientHeight || 0 });
1749
- const allRects = (): Rect[] => [...posCache.values(), ...ghostPosCache.values()].map(nodeRect);
1908
+ /** 计算全部 AI 建议条的画布落位:在锚点右侧可能超界时改按锚点右缘对齐,并纳入 fitView 包围盒 */
1909
+ const suggestionBarLayout = (gh: { nodes: Array<FlowNode & { sid?: string }>; edges: Array<FlowEdge & { sid?: string }> }): Array<{ suggestion: FlowSuggestion; at: Pt; width: number }> => {
1910
+ const list: Array<{ suggestion: FlowSuggestion; at: Pt; width: number }> = [];
1911
+ const allNodes = [...posCache.values(), ...ghostPosCache.values()];
1912
+ const maxRight = allNodes.length > 0 ? Math.max(...allNodes.map((p) => p.x + FLOW_GEOMETRY.nodeW)) : 0;
1913
+ const barW = FLOW_GEOMETRY.barW;
1914
+ for (const s of visibleSuggestions()) {
1915
+ const first = gh.nodes.find((n) => n.sid === s.id);
1916
+ const anchor = first ? ghostPosCache.get(first.id) : undefined;
1917
+ const firstEdge = gh.edges.find((e) => e.sid === s.id);
1918
+ const mid = firstEdge && posOf(firstEdge.from) && posOf(firstEdge.to) ? edgeGeometry(posOf(firstEdge.from)!, posOf(firstEdge.to)!, cfg.direction).mid : undefined;
1919
+ const rawAt = anchor ? { x: anchor.x, y: anchor.y + FLOW_GEOMETRY.nodeH + 4 } : mid;
1920
+ if (!rawAt) continue;
1921
+ const x = anchor && barW > FLOW_GEOMETRY.nodeW && rawAt.x + barW > maxRight
1922
+ ? Math.min(rawAt.x, maxRight - barW)
1923
+ : rawAt.x;
1924
+ list.push({ suggestion: s, at: { x, y: rawAt.y }, width: barW });
1925
+ }
1926
+ return list;
1927
+ };
1928
+ const allRects = (): Rect[] => {
1929
+ const rects = [...posCache.values(), ...ghostPosCache.values()].map(nodeRect);
1930
+ for (const item of suggestionBarLayout(ghostsOf())) {
1931
+ rects.push({ x: item.at.x, y: item.at.y, w: item.width, h: FLOW_GEOMETRY.barH });
1932
+ }
1933
+ return rects;
1934
+ };
1750
1935
  function fit(): void {
1751
1936
  const { w, h } = stageSize();
1752
1937
  view = w > 0 && h > 0 ? fitView(allRects(), w, h) : { zoom: 1, panX: 0, panY: 0 };
1753
- needFit = false;
1938
+ if (w > 0 && h > 0) {
1939
+ needFit = false;
1940
+ userAdjustedView = false;
1941
+ lastStageW = w;
1942
+ lastStageH = h;
1943
+ }
1754
1944
  applyView();
1755
1945
  updateZoomLabel();
1756
1946
  }
@@ -1758,6 +1948,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1758
1948
  const { w, h } = stageSize();
1759
1949
  view = zoomAt(view, factor, w / 2, h / 2);
1760
1950
  needFit = false;
1951
+ userAdjustedView = true;
1761
1952
  applyView();
1762
1953
  updateZoomLabel();
1763
1954
  };
@@ -1786,44 +1977,64 @@ export function createFlowEditor(): SomaComponentDefinition {
1786
1977
  };
1787
1978
 
1788
1979
  // ---- 绘制
1789
- const mkButton = (act: string, text: string, opts: { disabled?: boolean; primary?: boolean; icon?: KitIconName } = {}): HTMLButtonElement => {
1980
+ const mkButton = (act: string, text: string, opts: { disabled?: boolean; primary?: boolean; icon?: KitIconName; iconSize?: KitIconSize } = {}): HTMLButtonElement => {
1790
1981
  const b = el('button', opts.primary ? FLOW_CLASS.btnPrimary : FLOW_CLASS.btn, { type: 'button', 'data-flow-act': act });
1791
1982
  if (opts.icon !== undefined) {
1792
- const ic = kitIcon(opts.icon, 'sm');
1983
+ const ic = kitIcon(opts.icon, opts.iconSize ?? 'sm');
1793
1984
  ic.setAttribute('aria-hidden', 'true');
1794
1985
  b.appendChild(ic);
1795
- b.appendChild(document.createTextNode(` ${text}`));
1986
+ if (text !== '') b.appendChild(document.createTextNode(` ${text}`));
1796
1987
  } else b.textContent = text;
1797
1988
  if (opts.disabled) b.disabled = true;
1798
1989
  // 工具栏按钮(btn / btnPrimary 都带边框与底色)单点标 raised
1799
1990
  setKitFace(b, 'raised');
1991
+ // 画布工具条与出错行的按钮都经这里:元素部件「动作」单点自报
1992
+ kitMarkPart(b, 'action');
1800
1993
  return b;
1801
1994
  };
1802
1995
 
1803
1996
  const paintToolbar = (): void => {
1804
1997
  toolbar.textContent = '';
1998
+ const cleanAdd = (raw: string): string => raw.replace(/^[++]\s*/, '');
1999
+ const group = (...btns: HTMLButtonElement[]): HTMLElement => {
2000
+ const g = el('div', FLOW_CLASS.btnGroup);
2001
+ g.append(...btns);
2002
+ return g;
2003
+ };
1805
2004
  if (editable()) {
1806
2005
  const types = Object.values(cfg.nodeTypes);
1807
- if (types.length === 0) toolbar.appendChild(mkButton('add:', t('add', { type: t('nodeDefault') })));
1808
- for (const ty of types) toolbar.appendChild(mkButton(`add:${ty.type}`, t('add', { type: ty.label })));
1809
- toolbar.appendChild(mkButton('undo', t('undo'), { disabled: !canUndo(history) }));
1810
- toolbar.appendChild(mkButton('redo', t('redo'), { disabled: !canRedo(history) }));
2006
+ if (types.length === 0) toolbar.appendChild(mkButton('add:', cleanAdd(t('add', { type: t('nodeDefault') })), { icon: 'plus', iconSize: 'xs' }));
2007
+ for (const ty of types) toolbar.appendChild(mkButton(`add:${ty.type}`, cleanAdd(t('add', { type: ty.label })), { icon: 'plus', iconSize: 'xs' }));
2008
+ toolbar.appendChild(group(
2009
+ mkButton('undo', t('undo'), { disabled: !canUndo(history) }),
2010
+ mkButton('redo', t('redo'), { disabled: !canRedo(history) }),
2011
+ ));
1811
2012
  toolbar.appendChild(mkButton('del', t('del'), { disabled: selected.size === 0 }));
1812
2013
  toolbar.appendChild(mkButton('connect', t('connect'), { disabled: selectedNodeIds().length !== 1 }));
1813
2014
  const one = selectedNodeIds().length === 1 && selectedEdgeIds().length === 0;
1814
2015
  toolbar.appendChild(mkButton('insert-above', t('insertAbove'), { disabled: !one, icon: 'plus' }));
1815
- toolbar.appendChild(mkButton('move-up', t('moveUp'), { disabled: !one, icon: 'arrow-up' }));
1816
- toolbar.appendChild(mkButton('move-down', t('moveDown'), { disabled: !one, icon: 'arrow-down' }));
2016
+ // 成对动作(↑ 上移 / ↓ 下移)保持同组不拆行
2017
+ toolbar.appendChild(group(
2018
+ mkButton('move-up', t('moveUp'), { disabled: !one, icon: 'arrow-up' }),
2019
+ mkButton('move-down', t('moveDown'), { disabled: !one, icon: 'arrow-down' }),
2020
+ ));
1817
2021
  if (cfg.layout === 'manual') toolbar.appendChild(mkButton('layout', t('layout'), { disabled: graph.nodes.length === 0 }));
1818
2022
  }
1819
- toolbar.appendChild(mkButton('zoom-out', t('zoomOut')));
1820
- toolbar.appendChild(mkButton('zoom-in', t('zoomIn')));
1821
- toolbar.appendChild(mkButton('fit', t('fit')));
1822
- const z = el('span', FLOW_CLASS.zoomLabel, { 'data-flow-zoom': '' });
1823
- z.textContent = t('zoomLabel', { n: Math.round(view.zoom * 100) });
1824
- toolbar.appendChild(z);
1825
- toolbar.appendChild(el('span', FLOW_CLASS.zoomLabel, { 'data-flow-hint': '' })).textContent = t('zoomHint');
1826
- if (editable()) toolbar.appendChild(mkButton('save', t('save'), { primary: true }));
2023
+ const zoomBtns: HTMLButtonElement[] = [];
2024
+ if (canZoom()) {
2025
+ zoomBtns.push(mkButton('zoom-out', t('zoomOut')), mkButton('zoom-in', t('zoomIn')));
2026
+ }
2027
+ if (canZoom() || canPan()) zoomBtns.push(mkButton('fit', t('fit')));
2028
+ if (zoomBtns.length > 0) toolbar.appendChild(group(...zoomBtns));
2029
+ if (canZoom()) {
2030
+ const z = el('span', FLOW_CLASS.zoomLabel, { 'data-flow-zoom': '' });
2031
+ z.textContent = t('zoomLabel', { n: Math.round(view.zoom * 100) });
2032
+ toolbar.appendChild(z);
2033
+ toolbar.appendChild(el('span', FLOW_CLASS.zoomLabel, { 'data-flow-hint': '' })).textContent = t('zoomHint');
2034
+ }
2035
+ // 作为表单字段嵌入时不画独立主色蓝底「保存」,避免与弹窗底栏主按钮冲突
2036
+ if (editable() && !isFormField()) toolbar.appendChild(mkButton('save', t('save'), { primary: true }));
2037
+ toolbar.className = toolbar.childElementCount === 0 ? FLOW_CLASS.hidden : FLOW_CLASS.toolbar;
1827
2038
  };
1828
2039
 
1829
2040
  const nodeClass = (sel: boolean, level: Level, ghost: boolean, canMove: boolean): string => {
@@ -1842,11 +2053,24 @@ export function createFlowEditor(): SomaComponentDefinition {
1842
2053
  const buildNode = (n: FlowNode, at: Pt, opts: { ghost: boolean; issues?: FlowIssue[]; ghostOf?: string }): SVGForeignObjectElement => {
1843
2054
  const key = keyOfNode(n.id);
1844
2055
  const def = typeOf(n);
2056
+ const typeKeys = Object.keys(cfg.nodeTypes);
2057
+ const typeIdx = Math.max(0, typeKeys.indexOf(n.type));
2058
+ const explicitNodeTone = str(n.meta?.tone) || (def && def.tone !== 'neutral' ? def.tone : '');
2059
+ const resolvedTypeTone = kitResolveStatusOrCategoryTone(
2060
+ str(n.meta?.kind) || n.type || def?.label || n.label,
2061
+ typeIdx,
2062
+ {
2063
+ ...(explicitNodeTone !== '' ? { explicitTone: explicitNodeTone } : {}),
2064
+ preferHash: true,
2065
+ host: api.host,
2066
+ },
2067
+ );
1845
2068
  const sel = !opts.ghost && selected.has(key);
1846
2069
  const level = levelOf(opts.issues);
1847
2070
  const fo = svg('foreignObject', FLOW_CLASS.fo);
1848
2071
  place(fo, at, FLOW_GEOMETRY.nodeW, FLOW_GEOMETRY.nodeH);
1849
- const node = el('div', nodeClass(sel, level, opts.ghost, movable() && !opts.ghost));
2072
+ const baseNodeCls = nodeClass(sel, level, opts.ghost, movable() && !opts.ghost);
2073
+ const node = el('div', !opts.ghost && level === '' ? mergeClass(baseNodeCls, kitToneAccentBorderClass(resolvedTypeTone)) : baseNodeCls);
1850
2074
  fo.appendChild(node);
1851
2075
  const worstIssue = worst(opts.issues);
1852
2076
  if (opts.ghost) {
@@ -1858,11 +2082,19 @@ export function createFlowEditor(): SomaComponentDefinition {
1858
2082
  node.setAttribute('role', 'article');
1859
2083
  node.tabIndex = 0;
1860
2084
  if (sel) node.setAttribute('data-flow-selected', '');
2085
+ // 选中节点自报(节点角色 article 不支持 aria-selected,只写自报)
2086
+ kitMarkPicked(node, 'selected', sel, null);
1861
2087
  const lv = worstIssue ? `,${worstIssue.level === 'error' ? t('levelError') : t('levelWarning')}:${worstIssue.message}` : '';
1862
2088
  node.setAttribute('aria-label', `${t('nodeAria', { type: def?.label ?? n.type, label: n.label })}${lv}`);
1863
2089
  }
1864
2090
  const head = el('div', FLOW_CLASS.head);
1865
- if (def?.icon) { const i = el('span', FLOW_CLASS.icon, { 'aria-hidden': 'true' }); i.textContent = def.icon; head.appendChild(i); }
2091
+ if (def?.icon) {
2092
+ const i = el('span', mergeClass(mergeClass(FLOW_TONE_BADGE.neutral, 'inline-flex size-5 shrink-0 items-center justify-center overflow-hidden p-0'), kitToneSoftBadgeClass(resolvedTypeTone)), { 'aria-hidden': 'true' });
2093
+ const iconName = resolveKitIconName(def.icon);
2094
+ if (iconName !== null) i.appendChild(kitIcon(iconName, 'xs'));
2095
+ else i.textContent = def.icon;
2096
+ head.appendChild(i);
2097
+ }
1866
2098
  const ord = opts.ghost ? undefined : ordinals.get(n.id);
1867
2099
  if (ord !== undefined) { const o = el('span', FLOW_CLASS.line, { 'data-flow-ordinal': '' }); o.textContent = ord; head.appendChild(o); }
1868
2100
  const label = el('span', FLOW_CLASS.label);
@@ -1870,9 +2102,9 @@ export function createFlowEditor(): SomaComponentDefinition {
1870
2102
  head.appendChild(label);
1871
2103
  const tone = n.status !== undefined ? statusTone(n.status) : null;
1872
2104
  if (tone) head.appendChild(el('span', FLOW_TONE_DOT[tone], { 'aria-hidden': 'true' }));
1873
- if (!opts.ghost) {
2105
+ if (!opts.ghost && editable()) {
1874
2106
  const cb = el('button', FLOW_CLASS.cfgBtn, { type: 'button', tabindex: '-1', 'data-flow-act': `cfg:${n.id}`, 'aria-label': `${t('config')} ${n.label}` });
1875
- cb.textContent = '⚙';
2107
+ cb.appendChild(kitGlyph('settings', 'xs'));
1876
2108
  head.appendChild(cb);
1877
2109
  }
1878
2110
  node.appendChild(head);
@@ -1880,7 +2112,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1880
2112
  const body = el('div', FLOW_CLASS.body);
1881
2113
  const meta = el('div', FLOW_CLASS.head);
1882
2114
  if (def) {
1883
- const badge = el('span', FLOW_TONE_BADGE[def.tone]);
2115
+ const badge = el('span', mergeClass(FLOW_TONE_BADGE[def.tone], kitToneSoftBadgeClass(resolvedTypeTone)));
1884
2116
  badge.textContent = def.label;
1885
2117
  meta.appendChild(badge);
1886
2118
  }
@@ -1904,17 +2136,89 @@ export function createFlowEditor(): SomaComponentDefinition {
1904
2136
  }
1905
2137
  node.appendChild(body);
1906
2138
 
1907
- if (!opts.ghost) {
1908
- node.appendChild(el('span', FLOW_CLASS.inPort, { 'aria-hidden': 'true' }));
1909
- if (editable()) {
1910
- const port = el('button', FLOW_CLASS.outPort, { type: 'button', tabindex: '-1', 'data-flow-port': n.id, 'aria-label': t('port', { label: n.label }) });
1911
- node.appendChild(port);
1912
- }
2139
+ if (!opts.ghost && editable()) {
2140
+ node.appendChild(el('span', FLOW_CLASS.inPort, { 'aria-hidden': 'true', 'data-flow-in-port': n.id }));
2141
+ const port = el('button', FLOW_CLASS.outPort, { type: 'button', tabindex: '-1', 'data-flow-port': n.id, 'aria-label': t('port', { label: n.label }) });
2142
+ node.appendChild(port);
1913
2143
  }
1914
2144
  return fo;
1915
2145
  };
1916
2146
 
1917
2147
  const markerId = (kind: string): string => `${uid}-arrow-${kind}`;
2148
+ const portOutOf = (at: Pt): Pt => (
2149
+ cfg.direction === 'TB'
2150
+ ? { x: at.x + FLOW_GEOMETRY.nodeW / 2, y: at.y + FLOW_GEOMETRY.nodeH }
2151
+ : outPort(at)
2152
+ );
2153
+ const portInOf = (at: Pt): Pt => (
2154
+ cfg.direction === 'TB'
2155
+ ? { x: at.x + FLOW_GEOMETRY.nodeW / 2, y: at.y }
2156
+ : inPort(at)
2157
+ );
2158
+
2159
+ /** 同步端口拖拽橡皮筋预览线与目标入端口吸附高亮(全程纯 SVG 属性与类令牌,零 .style 写入) */
2160
+ const syncDraftEdgeDom = (): void => {
2161
+ if (nodesLayer) {
2162
+ for (const pEl of nodesLayer.querySelectorAll<HTMLElement>('[data-flow-in-port]')) {
2163
+ const pid = pEl.getAttribute('data-flow-in-port') ?? '';
2164
+ const isSnap = draftState !== null && editable() && draftState.snapTo !== null && pid === draftState.snapTo;
2165
+ if (isSnap) {
2166
+ pEl.className = FLOW_CLASS.inPortSnap;
2167
+ pEl.setAttribute(KIT_ATTR_PORT_ACTIVE, '');
2168
+ } else if (pEl.hasAttribute(KIT_ATTR_PORT_ACTIVE)) {
2169
+ pEl.className = FLOW_CLASS.inPort;
2170
+ pEl.removeAttribute(KIT_ATTR_PORT_ACTIVE);
2171
+ }
2172
+ }
2173
+ }
2174
+ if (!draftState || !editable() || !svgLayer) {
2175
+ draftEdgeEl?.remove();
2176
+ draftEdgeEl = null;
2177
+ return;
2178
+ }
2179
+ const fromPos = posOf(draftState.fromId);
2180
+ if (!fromPos) {
2181
+ draftEdgeEl?.remove();
2182
+ draftEdgeEl = null;
2183
+ return;
2184
+ }
2185
+ const d = draftEdgePath(portOutOf(fromPos), draftState.endPt, cfg.direction);
2186
+ if (!draftEdgeEl || draftEdgeEl.parentNode !== svgLayer) {
2187
+ draftEdgeEl?.remove();
2188
+ draftEdgeEl = svg('path', FLOW_CLASS.draftEdge, {
2189
+ [KIT_ATTR_FLOW_DRAFT_EDGE]: '',
2190
+ 'stroke-dasharray': '5 4',
2191
+ 'aria-hidden': 'true',
2192
+ 'marker-end': `url(#${markerId('selected')})`,
2193
+ d,
2194
+ });
2195
+ svgLayer.appendChild(draftEdgeEl);
2196
+ } else {
2197
+ draftEdgeEl.setAttribute('d', d);
2198
+ }
2199
+ };
2200
+
2201
+ const clearDraftEdge = (): void => {
2202
+ draftState = null;
2203
+ syncDraftEdgeDom();
2204
+ };
2205
+
2206
+ /** 指针靠近合法目标 inPort 时吸附至目标入端口中心并返回目标节点 id */
2207
+ const resolvePortSnap = (fromId: string, worldPt: Pt): { endPt: Pt; snapTo: string | null } => {
2208
+ const snapRadius = 28 / Math.min(1, view.zoom);
2209
+ let best: { id: string; pt: Pt; dist: number } | null = null;
2210
+ for (const n of graph.nodes) {
2211
+ if (n.id === fromId || !canConnect(graph, cfg.nodeTypes, fromId, n.id, cfg.allowCycles).ok) continue;
2212
+ const at = posOf(n.id);
2213
+ if (!at) continue;
2214
+ const pt = portInOf(at);
2215
+ const dist = Math.hypot(worldPt.x - pt.x, worldPt.y - pt.y);
2216
+ if (dist <= snapRadius && (best === null || dist < best.dist)) {
2217
+ best = { id: n.id, pt, dist };
2218
+ }
2219
+ }
2220
+ return best ? { endPt: best.pt, snapTo: best.id } : { endPt: worldPt, snapTo: null };
2221
+ };
1918
2222
 
1919
2223
  const paintEdges = (): void => {
1920
2224
  svgLayer.textContent = '';
@@ -1932,7 +2236,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1932
2236
  const b = posOf(e.to);
1933
2237
  if (!a || !b) return;
1934
2238
  const key = keyOfEdge(e.id);
1935
- const geo = edgeGeometry(a, b);
2239
+ const geo = edgeGeometry(a, b, cfg.direction);
1936
2240
  const sel = !ghost && selected.has(key);
1937
2241
  const level = levelOf(issues.get(key));
1938
2242
  const kind = ghost ? 'ghost' : sel ? 'selected' : level === 'error' ? 'error' : level === 'warning' ? 'warning' : 'normal';
@@ -1946,6 +2250,8 @@ export function createFlowEditor(): SomaComponentDefinition {
1946
2250
  g.setAttribute('role', 'button');
1947
2251
  g.setAttribute('tabindex', '0');
1948
2252
  g.setAttribute('aria-pressed', sel ? 'true' : 'false');
2253
+ // 连线是 role=button,无障碍属性用上一行的 aria-pressed,这里只补自报
2254
+ kitMarkPicked(g, 'selected', sel, null);
1949
2255
  g.setAttribute('aria-label', `${base}${e.label ? `(${e.label})` : ''}${w ? `,${w.level === 'error' ? t('levelError') : t('levelWarning')}:${w.message}` : ''}`);
1950
2256
  if (w) {
1951
2257
  const tip = svg('title');
@@ -1969,15 +2275,33 @@ export function createFlowEditor(): SomaComponentDefinition {
1969
2275
  lg.appendChild(text);
1970
2276
  labelLayer.appendChild(lg);
1971
2277
  labelText = text;
1972
- // 标签白底衬垫:量出外框后垫一块带内边距的圆角底;量不出(未布局、宽高为 0)按字数估算
2278
+ // 标签白底衬垫:按文本签名缓存 getBBox 测量尺寸与中心偏移,避免拖动或键入时每帧重复触发同步回流
1973
2279
  let bx = geo.mid.x - (e.label.length * FLOW_LABEL_FONT) / 2;
1974
2280
  let by = geo.mid.y - FLOW_LABEL_FONT / 2;
1975
2281
  let bw = e.label.length * FLOW_LABEL_FONT;
1976
2282
  let bh = FLOW_LABEL_FONT;
1977
- try {
1978
- const bb = labelText.getBBox();
1979
- if (bb.width > 0 && bb.height > 0) { bx = bb.x; by = bb.y; bw = bb.width; bh = bb.height; }
1980
- } catch { /* 无布局环境:用估算 */ }
2283
+ const cachedBox = labelBoxCache.get(e.label);
2284
+ if (cachedBox !== undefined) {
2285
+ bw = cachedBox.w;
2286
+ bh = cachedBox.h;
2287
+ bx = geo.mid.x + cachedBox.dx;
2288
+ by = geo.mid.y + cachedBox.dy;
2289
+ } else {
2290
+ try {
2291
+ const bb = labelText.getBBox();
2292
+ if (bb.width > 0 && bb.height > 0) {
2293
+ bx = bb.x;
2294
+ by = bb.y;
2295
+ bw = bb.width;
2296
+ bh = bb.height;
2297
+ if (labelBoxCache.size >= 256) {
2298
+ const oldest = labelBoxCache.keys().next().value;
2299
+ if (oldest !== undefined) labelBoxCache.delete(oldest);
2300
+ }
2301
+ labelBoxCache.set(e.label, { w: bw, h: bh, dx: bx - geo.mid.x, dy: by - geo.mid.y });
2302
+ }
2303
+ } catch { /* 无布局环境:用估算 */ }
2304
+ }
1981
2305
  lg.insertBefore(svg('rect', FLOW_CLASS.edgeLabelBg, {
1982
2306
  x: String(bx - FLOW_LABEL_PAD_X), y: String(by - FLOW_LABEL_PAD_Y), width: String(bw + FLOW_LABEL_PAD_X * 2), height: String(bh + FLOW_LABEL_PAD_Y * 2), rx: '4',
1983
2307
  }), text);
@@ -1989,6 +2313,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1989
2313
  svgLayer.appendChild(labelLayer);
1990
2314
  for (const e of graph.edges) draw(e, false);
1991
2315
  for (const e of ghostsOf().edges) draw(e, true);
2316
+ if (draftState !== null) syncDraftEdgeDom();
1992
2317
  };
1993
2318
 
1994
2319
  const paintNodes = (issues: Map<string, FlowIssue[]>): void => {
@@ -1996,7 +2321,7 @@ export function createFlowEditor(): SomaComponentDefinition {
1996
2321
  dndCleanups = [];
1997
2322
  dragFrom = null; // 注销后源的 onDragEnd 可能不再触发
1998
2323
  nodesLayer.textContent = '';
1999
- ordinals = ordinalsOf(graph, cfg.nodeTypes);
2324
+ ordinals = ordinalsOf(graph, cfg.nodeTypes, bool(pickOf(P(), 'numbered')));
2000
2325
  const port = dndPort();
2001
2326
  const valid = (from: string, to: string): boolean => canConnect(graph, cfg.nodeTypes, from, to, cfg.allowCycles).ok;
2002
2327
  for (const n of graph.nodes) {
@@ -2013,7 +2338,7 @@ export function createFlowEditor(): SomaComponentDefinition {
2013
2338
  data: () => ({ flowFrom: n.id }),
2014
2339
  canDrag: () => editable(),
2015
2340
  onDragStart: () => { dragFrom = n.id; markTargets(n.id); },
2016
- onDragEnd: () => { dragFrom = null; markTargets(null); },
2341
+ onDragEnd: () => { dragFrom = null; clearDraftEdge(); markTargets(connectFrom); },
2017
2342
  }));
2018
2343
  dndCleanups.push(port.dropTarget(node, {
2019
2344
  id: `${uid}|in|${n.id}`,
@@ -2029,15 +2354,10 @@ export function createFlowEditor(): SomaComponentDefinition {
2029
2354
  const gh = ghostsOf();
2030
2355
  const sugLabels = new Map(visibleSuggestions().map((s) => [s.id, s.label] as const));
2031
2356
  for (const n of gh.nodes) nodesLayer.appendChild(buildNode(n, ghostPosCache.get(n.id) ?? { x: 0, y: 0 }, { ghost: true, ghostOf: n.sid === undefined ? undefined : sugLabels.get(n.sid) }));
2032
- for (const s of visibleSuggestions()) {
2033
- const first = gh.nodes.find((n) => n.sid === s.id);
2034
- const anchor = first ? ghostPosCache.get(first.id) : undefined;
2035
- const firstEdge = gh.edges.find((e) => e.sid === s.id);
2036
- const mid = firstEdge && posOf(firstEdge.from) && posOf(firstEdge.to) ? edgeGeometry(posOf(firstEdge.from)!, posOf(firstEdge.to)!).mid : undefined;
2037
- const at = anchor ? { x: anchor.x, y: anchor.y + FLOW_GEOMETRY.nodeH + 4 } : mid;
2038
- if (!at) continue;
2357
+ for (const item of suggestionBarLayout(gh)) {
2358
+ const { suggestion: s, at, width } = item;
2039
2359
  const barFo = svg('foreignObject', FLOW_CLASS.fo);
2040
- place(barFo, at, FLOW_GEOMETRY.barW, FLOW_GEOMETRY.barH);
2360
+ place(barFo, at, width, FLOW_GEOMETRY.barH);
2041
2361
  const bar = el('div', FLOW_CLASS.bar, { role: 'group', 'data-flow-bar': s.id, 'aria-label': t('suggestion', { label: s.label }) });
2042
2362
  barFo.appendChild(bar);
2043
2363
  const cap = el('span', FLOW_CLASS.barCap);
@@ -2078,14 +2398,61 @@ export function createFlowEditor(): SomaComponentDefinition {
2078
2398
  paintEdges();
2079
2399
  paintPanel();
2080
2400
 
2081
- const errText = str(p.error);
2082
- errorOuter.className = errText === '' ? FLOW_CLASS.hidden : '';
2401
+ const errText = str(p.error_text) || str(p.error);
2402
+ errorOuter.className = errText === '' ? FLOW_CLASS.hidden : FLOW_CLASS.errorRow;
2083
2403
  errorInner.textContent = errText;
2404
+ if (retryBtn) {
2405
+ retryBtn.textContent = str(p.retry_text, kitText('soma.kit.retry', undefined, root));
2406
+ retryBtn.className = errText === '' ? FLOW_CLASS.hidden : FLOW_CLASS.btn;
2407
+ }
2408
+ const loading = bool(p.loading);
2409
+ if (loading) {
2410
+ root.setAttribute('aria-busy', 'true');
2411
+ emptyInner.setAttribute('aria-busy', 'true');
2412
+ emptyInner.setAttribute(KIT_ATTR_STATE, 'loading');
2413
+ } else {
2414
+ root.removeAttribute('aria-busy');
2415
+ emptyInner.removeAttribute('aria-busy');
2416
+ emptyInner.removeAttribute(KIT_ATTR_STATE);
2417
+ }
2084
2418
  const empty = graph.nodes.length === 0 && gh.nodes.length === 0;
2419
+ // 数据状态自报到组件根:出错 > 加载 > 空 > 只读(GraphView 恒只读,只读对它不是状态,不报)
2420
+ kitMarkDataFacts(root, { error: errText !== '', loading, empty, readonly: !isGraphView && cfg.readonly });
2085
2421
  emptyOuter.className = empty ? '' : FLOW_CLASS.hidden;
2086
- emptyInner.textContent = bool(p.loading) ? t('loading') : cfg.readonly ? t('emptyReadonly') : t('empty');
2422
+ const customEmpty = str(p.empty_text);
2423
+ emptyInner.textContent = loading ? t('loading') : customEmpty !== '' ? customEmpty : cfg.readonly ? t('emptyReadonly') : t('empty');
2424
+
2425
+ if (summaryTable) {
2426
+ summaryTable.textContent = '';
2427
+ if (graph.nodes.length > 0) {
2428
+ const cap = el('caption', '');
2429
+ cap.textContent = t('summary', { nodes: graph.nodes.length, edges: graph.edges.length });
2430
+ const thead = el('thead', '');
2431
+ const hr = el('tr', '');
2432
+ for (const col of [t('nodeDefault'), 'Type', '->']) {
2433
+ const th = el('th', '', { scope: 'col' });
2434
+ th.textContent = col;
2435
+ hr.appendChild(th);
2436
+ }
2437
+ thead.appendChild(hr);
2438
+ const tbody = el('tbody', '');
2439
+ for (const n of graph.nodes) {
2440
+ const tr = el('tr', '');
2441
+ const nh = el('th', '', { scope: 'row' });
2442
+ nh.textContent = n.label;
2443
+ const tdType = el('td', '');
2444
+ tdType.textContent = [typeOf(n)?.label ?? n.type, n.status ?? ''].filter((s) => s !== '').join(' · ');
2445
+ const tdEdges = el('td', '');
2446
+ const outs = graph.edges.filter((e) => e.from === n.id);
2447
+ tdEdges.textContent = outs.map((e) => `${labelOf(e.to)}${e.label ? ` (${e.label})` : ''}`).join(', ') || '—';
2448
+ tr.append(nh, tdType, tdEdges);
2449
+ tbody.appendChild(tr);
2450
+ }
2451
+ summaryTable.append(cap, thead, tbody);
2452
+ }
2453
+ }
2087
2454
 
2088
- if (needFit && graph.nodes.length > 0 && stage.clientWidth > 0) fit();
2455
+ if (needFit && (graph.nodes.length > 0 || gh.nodes.length > 0) && stage.clientWidth > 0 && stage.clientHeight > 0) fit();
2089
2456
  applyView();
2090
2457
 
2091
2458
  const errors = [...issues.values()].flat().filter((i) => i.level === 'error').length;
@@ -2093,20 +2460,26 @@ export function createFlowEditor(): SomaComponentDefinition {
2093
2460
  const parts = [t('summary', { nodes: graph.nodes.length, edges: graph.edges.length })];
2094
2461
  if (errors > 0) parts.push(t('errors', { n: errors }));
2095
2462
  if (warns > 0) parts.push(t('warnings', { n: warns }));
2096
- statusEl.textContent = flash !== '' ? flash : bool(p.loading) ? t('loading') : parts.join(' · ');
2463
+ statusEl.textContent = flash !== '' ? flash : loading ? t('loading') : parts.join(' · ');
2097
2464
 
2098
2465
  if (token) {
2099
2466
  const target = findByAttr(token.name, token.value);
2100
- if (target) (target as unknown as { focus?: () => void }).focus?.();
2467
+ if (target && !(target as HTMLButtonElement).disabled) {
2468
+ (target as unknown as { focus?: () => void }).focus?.();
2469
+ } else if (token.name === 'data-flow-act' && (token.value === 'undo' || token.value === 'redo')) {
2470
+ const alt = findByAttr('data-flow-act', token.value === 'undo' ? 'redo' : 'undo');
2471
+ if (alt && !(alt as HTMLButtonElement).disabled) alt.focus();
2472
+ else stage.focus();
2473
+ }
2101
2474
  }
2102
2475
  }
2103
2476
 
2104
2477
  // ---- 数据同步
2105
2478
  const sync = (first: boolean): void => {
2106
2479
  const p = P();
2107
- cfg = configOf(p, root);
2480
+ cfg = configOf(p, root, cfgDefaults);
2108
2481
  // GB4 作表单字段控件(表单给了字段名 name):图来自 value(草稿里的值),否则来自 data
2109
- const data = graphOf(typeof p.name === 'string' && p.name !== '' ? p.value : p.data);
2482
+ const data = graphOf(!isGraphView && typeof p.name === 'string' && p.name !== '' ? p.value : p.data);
2110
2483
  if (root && typeof p.id === 'string' && p.id !== '') root.id = p.id;
2111
2484
  // 画布(可聚焦的 group)承载表单传入的标签关联 / 必填 / 无效 / 说明:与自带的说明节点合并,重绘不丢
2112
2485
  if (stage) {
@@ -2114,26 +2487,29 @@ export function createFlowEditor(): SomaComponentDefinition {
2114
2487
  id: stage.id,
2115
2488
  aria_label: t('canvas'),
2116
2489
  labelledby: p.labelledby,
2117
- required: p.required,
2118
- invalid: p.invalid,
2490
+ ...(isGraphView ? {} : {
2491
+ required: p.required,
2492
+ invalid: p.invalid,
2493
+ errormessage: p.errormessage,
2494
+ aria_errormessage: p.aria_errormessage,
2495
+ }),
2119
2496
  describedby: p.describedby,
2120
2497
  aria_describedby: p.aria_describedby,
2121
- errormessage: p.errormessage,
2122
- aria_errormessage: p.aria_errormessage,
2123
2498
  });
2124
2499
  }
2125
2500
  const dsig = graphSig(data);
2126
2501
  if (first || (dsig !== lastDataSig && dsig !== graphSig(graph))) {
2127
- // 节点集合不变(宿主只回灌了规整后的 meta)时保持视口,不重新适应画布
2502
+ // 节点集合不变(宿主只回灌了规整后的 meta)时保持视口,不重新适应画布;拓扑相同时仅更新 present,不清空撤销栈
2128
2503
  const sameIds = !first && graph.nodes.length === data.nodes.length && graph.nodes.every((n, i) => n.id === data.nodes[i]?.id);
2504
+ const sameTopoOrEcho = !first && (topologySig(graph) === topologySig(data) || emittedSigs.has(dsig));
2129
2505
  graph = data;
2130
- history = emptyHistory();
2131
- if (!sameIds) needFit = true;
2506
+ if (first || !sameTopoOrEcho) history = emptyHistory();
2507
+ if (first || !sameIds) needFit = autoFit();
2132
2508
  pruneSelection();
2133
2509
  }
2134
2510
  lastDataSig = dsig;
2135
- external = (pickOf(p, 'validation') !== undefined ? issuesOf(pickOf(p, 'validation')) : []);
2136
- deriveSuggestions(p);
2511
+ external = (!isGraphView && pickOf(p, 'validation') !== undefined ? issuesOf(pickOf(p, 'validation')) : []);
2512
+ if (!isGraphView) deriveSuggestions(p);
2137
2513
  };
2138
2514
 
2139
2515
  // 建议 = 显式 suggestions;集合变了「忽略」重置
@@ -2157,6 +2533,7 @@ export function createFlowEditor(): SomaComponentDefinition {
2157
2533
  };
2158
2534
 
2159
2535
  const openMenu = (key: string, at: Pt): void => {
2536
+ if (isGraphView) return;
2160
2537
  menuInner.textContent = '';
2161
2538
  menuInner.setAttribute('aria-label', t('menu'));
2162
2539
  const id = key.slice(2);
@@ -2177,7 +2554,14 @@ export function createFlowEditor(): SomaComponentDefinition {
2177
2554
  b.textContent = text;
2178
2555
  menuInner.appendChild(b);
2179
2556
  }
2180
- place(menuFo, at, FLOW_GEOMETRY.menuW, items.length * FLOW_GEOMETRY.menuItemH + 12);
2557
+ const menuW = FLOW_GEOMETRY.menuW;
2558
+ const menuH = items.length * FLOW_GEOMETRY.menuItemH + 12;
2559
+ const { w: sw, h: sh } = stageSize();
2560
+ const clamped: Pt = {
2561
+ x: sw > 0 ? clamp(at.x, 4, Math.max(4, sw - menuW - 4)) : Math.max(0, at.x),
2562
+ y: sh > 0 ? clamp(at.y, 4, Math.max(4, sh - menuH - 4)) : Math.max(0, at.y),
2563
+ };
2564
+ place(menuFo, clamped, menuW, menuH);
2181
2565
  setCls(menuOuter, '');
2182
2566
  menuOpen = true;
2183
2567
  menuInner.querySelector<HTMLElement>('button')?.focus();
@@ -2194,28 +2578,65 @@ export function createFlowEditor(): SomaComponentDefinition {
2194
2578
  const target = e.target as Element | null;
2195
2579
  if (!target) return;
2196
2580
  if (menuOpen && !target.closest('[data-flow-act^="menu-"]')) closeMenu();
2197
- if (target.closest('[data-flow-act],[data-flow-port]')) return;
2581
+ const portEl = target.closest<HTMLElement>('[data-flow-port]');
2582
+ if (portEl) {
2583
+ const fromId = portEl.getAttribute('data-flow-port') ?? '';
2584
+ const fromPos = fromId !== '' ? posOf(fromId) : undefined;
2585
+ if (editable() && fromId !== '' && nodeById(fromId) && fromPos) {
2586
+ const p = stagePoint(e);
2587
+ const startPt = portOutOf(fromPos);
2588
+ const rawWorld = e.clientX === 0 && e.clientY === 0 ? startPt : screenToWorld(view, p.x, p.y);
2589
+ const snapped = resolvePortSnap(fromId, rawWorld);
2590
+ press = { kind: 'port', fromId, sx: e.clientX, sy: e.clientY, moved: false, hadButtons: e.buttons > 0, snapTo: snapped.snapTo };
2591
+ draftState = { fromId, endPt: snapped.endPt, snapTo: snapped.snapTo };
2592
+ markTargets(fromId);
2593
+ syncDraftEdgeDom();
2594
+ }
2595
+ return;
2596
+ }
2597
+ if (target.closest('[data-flow-act]')) return;
2198
2598
  const additive = e.shiftKey || e.ctrlKey || e.metaKey;
2199
2599
  const nodeEl = target.closest('[data-flow-key^="n:"]');
2200
2600
  const p = stagePoint(e);
2601
+ const hadButtons = e.buttons > 0;
2201
2602
  if (nodeEl) {
2202
2603
  const key = nodeEl.getAttribute('data-flow-key') ?? '';
2203
- press = { kind: 'node', key, sx: e.clientX, sy: e.clientY, moved: false, additive, origin: null };
2604
+ press = { kind: 'node', key, sx: e.clientX, sy: e.clientY, moved: false, hadButtons, additive, origin: null };
2204
2605
  } else if (target.closest('[data-flow-key^="e:"],[data-flow-bar],[data-flow-ghost]')) {
2205
2606
  return;
2206
2607
  } else if (e.shiftKey) {
2207
- press = { kind: 'marquee', sx: e.clientX, sy: e.clientY, moved: false, ax: p.x, ay: p.y };
2608
+ press = { kind: 'marquee', sx: e.clientX, sy: e.clientY, moved: false, hadButtons, ax: p.x, ay: p.y };
2208
2609
  } else {
2209
- press = { kind: 'pan', sx: e.clientX, sy: e.clientY, moved: false, start: { ...view }, additive };
2610
+ press = { kind: 'pan', sx: e.clientX, sy: e.clientY, moved: false, hadButtons, start: { ...view }, additive };
2210
2611
  }
2211
2612
  };
2212
2613
 
2213
2614
  const onPointerMove = (e: PointerEvent): void => {
2214
2615
  if (!press) return;
2215
2616
  // 按键已在画布外松开(未捕获指针时收不到 up):当作取消,避免无按键的“拖动”
2216
- if (e.buttons === 0) { press = null; dragPos = null; setCls(marqueeOuter, FLOW_CLASS.hidden); return; }
2617
+ if (press.hadButtons && e.buttons === 0) {
2618
+ const wasPort = press.kind === 'port';
2619
+ press = null;
2620
+ dragPos = null;
2621
+ setCls(marqueeOuter, FLOW_CLASS.hidden);
2622
+ if (wasPort) { clearDraftEdge(); markTargets(connectFrom); }
2623
+ return;
2624
+ }
2217
2625
  const dx = e.clientX - press.sx;
2218
2626
  const dy = e.clientY - press.sy;
2627
+ if (press.kind === 'port') {
2628
+ if (!press.moved && Math.hypot(dx, dy) >= FLOW_GEOMETRY.dragThreshold) {
2629
+ press.moved = true;
2630
+ try { stage.setPointerCapture?.(e.pointerId); } catch { /* 不支持捕获的环境 */ }
2631
+ }
2632
+ const p = stagePoint(e);
2633
+ const worldPt = screenToWorld(view, p.x, p.y);
2634
+ const snapped = resolvePortSnap(press.fromId, worldPt);
2635
+ press.snapTo = snapped.snapTo;
2636
+ draftState = { fromId: press.fromId, endPt: snapped.endPt, snapTo: snapped.snapTo };
2637
+ syncDraftEdgeDom();
2638
+ return;
2639
+ }
2219
2640
  if (!press.moved && Math.hypot(dx, dy) < FLOW_GEOMETRY.dragThreshold) return;
2220
2641
  if (!press.moved) {
2221
2642
  // 越过拖动阈值才捕获指针:单击 / 双击的目标保持为节点本身(捕获会把 click、dblclick 改投给画布)
@@ -2223,6 +2644,7 @@ export function createFlowEditor(): SomaComponentDefinition {
2223
2644
  }
2224
2645
  press.moved = true;
2225
2646
  if (press.kind === 'pan') {
2647
+ if (!canPan()) return;
2226
2648
  view = { ...press.start, panX: press.start.panX + dx, panY: press.start.panY + dy };
2227
2649
  needFit = false;
2228
2650
  applyView();
@@ -2248,11 +2670,36 @@ export function createFlowEditor(): SomaComponentDefinition {
2248
2670
  }
2249
2671
  };
2250
2672
 
2673
+ const pointInRect = (pt: Pt, r: Rect): boolean => pt.x >= r.x && pt.x <= r.x + r.w && pt.y >= r.y && pt.y <= r.y + r.h;
2674
+
2251
2675
  const onPointerUp = (e: PointerEvent): void => {
2252
2676
  const pr = press;
2253
2677
  press = null;
2254
2678
  try { stage.releasePointerCapture?.(e.pointerId); } catch { /* 同上 */ }
2255
2679
  if (!pr) return;
2680
+ if (pr.kind === 'port') {
2681
+ clearDraftEdge();
2682
+ markTargets(connectFrom);
2683
+ if (!pr.moved) return;
2684
+ suppressNextPortClick = true;
2685
+ queueMicrotask(() => { suppressNextPortClick = false; });
2686
+ const p = stagePoint(e);
2687
+ const worldPt = screenToWorld(view, p.x, p.y);
2688
+ const domNodeKey = (e.target as Element | null)?.closest('[data-flow-key^="n:"]')?.getAttribute('data-flow-key');
2689
+ const domNodeId = domNodeKey ? domNodeKey.slice(2) : null;
2690
+ const hitNodeId = graph.nodes.find((n) => n.id !== pr.fromId && posOf(n.id) !== undefined && pointInRect(worldPt, nodeRect(posOf(n.id)!)))?.id ?? null;
2691
+ const toId = pr.snapTo ?? (domNodeId !== pr.fromId ? domNodeId : null) ?? hitNodeId;
2692
+ if (toId !== null && toId !== pr.fromId) {
2693
+ const pairKey = `${pr.fromId}\u0000${toId}`;
2694
+ if (recentPortDrop !== pairKey) {
2695
+ recentPortDrop = pairKey;
2696
+ queueMicrotask(() => { if (recentPortDrop === pairKey) recentPortDrop = ''; });
2697
+ flash = '';
2698
+ tryConnect(pr.fromId, toId);
2699
+ }
2700
+ }
2701
+ return;
2702
+ }
2256
2703
  flash = '';
2257
2704
  if (pr.kind === 'pan') {
2258
2705
  if (!pr.moved && !pr.additive && selected.size > 0) { setSelection([]); paint(); }
@@ -2281,17 +2728,28 @@ export function createFlowEditor(): SomaComponentDefinition {
2281
2728
  };
2282
2729
 
2283
2730
  const onPointerCancel = (): void => {
2284
- if (!press) return;
2731
+ if (!press && draftState === null) return;
2285
2732
  press = null;
2286
2733
  dragPos = null;
2287
- dragFrom = null;
2288
2734
  setCls(marqueeOuter, FLOW_CLASS.hidden);
2289
- paint();
2735
+ if (dragFrom === null) {
2736
+ clearDraftEdge();
2737
+ paint();
2738
+ }
2739
+ };
2740
+
2741
+ const onDragOver = (e: DragEvent): void => {
2742
+ if (dragFrom === null || !editable()) return;
2743
+ const p = stagePoint(e);
2744
+ const worldPt = screenToWorld(view, p.x, p.y);
2745
+ const snapped = resolvePortSnap(dragFrom, worldPt);
2746
+ draftState = { fromId: dragFrom, endPt: snapped.endPt, snapTo: snapped.snapTo };
2747
+ syncDraftEdgeDom();
2290
2748
  };
2291
2749
 
2292
2750
  const onWheel = (e: WheelEvent): void => {
2293
2751
  // 只有 Ctrl / ⌘ + 滚轮(触控板双指捏合浏览器也会带 ctrlKey)才缩放并拦截;普通滚轮放行,页面照常滚动
2294
- if (!(e.ctrlKey || e.metaKey)) return;
2752
+ if (!(e.ctrlKey || e.metaKey) || !canZoom()) return;
2295
2753
  e.preventDefault();
2296
2754
  needFit = false;
2297
2755
  const p = stagePoint(e);
@@ -2315,10 +2773,12 @@ export function createFlowEditor(): SomaComponentDefinition {
2315
2773
  case 'move-up': case 'move-down': { const ids = selectedNodeIds(); if (ids.length === 1) moveNode(ids[0]!, name === 'move-up' ? 'up' : 'down'); break; }
2316
2774
  case 'menu-insert': { closeMenu(); insertAbove(arg, nodeById(arg)?.type ?? ''); break; }
2317
2775
  case 'menu-up': case 'menu-down': { closeMenu(); moveNode(arg, name === 'menu-up' ? 'up' : 'down'); break; }
2318
- case 'zoom-in': zoomBy(FLOW_GEOMETRY.zoomFactor); break;
2319
- case 'zoom-out': zoomBy(1 / FLOW_GEOMETRY.zoomFactor); break;
2776
+ case 'zoom-in': if (canZoom()) zoomBy(FLOW_GEOMETRY.zoomFactor); break;
2777
+ case 'zoom-out': if (canZoom()) zoomBy(1 / FLOW_GEOMETRY.zoomFactor); break;
2320
2778
  case 'fit': fit(); break;
2321
- case 'save': api.emit('save', payload(graph)); break;
2779
+ case 'save': if (editable()) api.emit('save', payload(graph)); break;
2780
+ case 'retry': api.emit('retry', {}); break;
2781
+ case 'panel-close': setSelection([]); active = ''; paint(); stage.focus(); break;
2322
2782
  case 'cfg': requestConfig(arg); break;
2323
2783
  case 'accept': accept(arg); break;
2324
2784
  case 'reject': reject(arg); break;
@@ -2347,6 +2807,7 @@ export function createFlowEditor(): SomaComponentDefinition {
2347
2807
  }
2348
2808
  active = nodeKey;
2349
2809
  paint();
2810
+ emitNodePick(id);
2350
2811
  };
2351
2812
 
2352
2813
  const onClick = (e: MouseEvent): void => {
@@ -2357,7 +2818,12 @@ export function createFlowEditor(): SomaComponentDefinition {
2357
2818
  const act = target.closest('[data-flow-act]')?.getAttribute('data-flow-act');
2358
2819
  if (act) { runAct(act); return; }
2359
2820
  const port = target.closest('[data-flow-port]')?.getAttribute('data-flow-port');
2360
- if (port) { flash = ''; startConnect(port); return; }
2821
+ if (port) {
2822
+ if (suppressNextPortClick) { suppressNextPortClick = false; return; }
2823
+ flash = '';
2824
+ startConnect(port);
2825
+ return;
2826
+ }
2361
2827
  const nodeKey = target.closest('[data-flow-key^="n:"]')?.getAttribute('data-flow-key');
2362
2828
  if (nodeKey) {
2363
2829
  if (consumedPointerKey === nodeKey) return;
@@ -2374,6 +2840,7 @@ export function createFlowEditor(): SomaComponentDefinition {
2374
2840
  active = edgeKey;
2375
2841
  setSelection(next, edgeKey);
2376
2842
  paint();
2843
+ emitEdgePick(edgeKey.slice(2));
2377
2844
  }
2378
2845
  };
2379
2846
 
@@ -2415,29 +2882,42 @@ export function createFlowEditor(): SomaComponentDefinition {
2415
2882
  e.preventDefault();
2416
2883
  return;
2417
2884
  }
2418
- if (target.closest('[data-flow-act],[data-flow-port]') && !target.closest('[data-flow-key]')) return;
2419
- const itemKey = target.closest('[data-flow-key]')?.getAttribute('data-flow-key') ?? null;
2420
- if (target !== stage && itemKey === null) return;
2421
2885
  const mod = e.ctrlKey || e.metaKey;
2422
2886
  const key = e.key;
2423
2887
  const handled = (): void => { e.preventDefault(); };
2888
+ const inTextEntry = target instanceof HTMLInputElement
2889
+ || target instanceof HTMLTextAreaElement
2890
+ || (target instanceof HTMLElement && target.isContentEditable);
2891
+ if (mod && !inTextEntry && editable()) {
2892
+ if (key === 'z' || key === 'Z') { handled(); flash = ''; if (e.shiftKey) doRedo(); else doUndo(); return; }
2893
+ if (key === 'y' || key === 'Y') { handled(); flash = ''; doRedo(); return; }
2894
+ if (key === 's' || key === 'S') { handled(); api.emit('save', payload(graph)); return; }
2895
+ }
2896
+ if (target.closest('[data-flow-act],[data-flow-port]') && !target.closest('[data-flow-key]')) return;
2897
+ const itemKey = target.closest('[data-flow-key]')?.getAttribute('data-flow-key') ?? null;
2898
+ if (target !== stage && itemKey === null) return;
2424
2899
 
2425
- if (mod && (key === 'z' || key === 'Z')) { handled(); flash = ''; if (e.shiftKey) doRedo(); else doUndo(); return; }
2426
- if (mod && (key === 'y' || key === 'Y')) { handled(); flash = ''; doRedo(); return; }
2427
2900
  if (mod && (key === 'a' || key === 'A')) { handled(); setSelection(graph.nodes.map((n) => keyOfNode(n.id))); paint(); return; }
2428
- if (mod && (key === 's' || key === 'S') && editable()) { handled(); api.emit('save', payload(graph)); return; }
2429
2901
  if (mod) return;
2430
- if (key === '+' || key === '=') { handled(); zoomBy(FLOW_GEOMETRY.zoomFactor); return; }
2431
- if (key === '-' || key === '_') { handled(); zoomBy(1 / FLOW_GEOMETRY.zoomFactor); return; }
2432
- if (key === '0') { handled(); fit(); return; }
2902
+ if ((key === '+' || key === '=') && canZoom()) { handled(); zoomBy(FLOW_GEOMETRY.zoomFactor); return; }
2903
+ if ((key === '-' || key === '_') && canZoom()) { handled(); zoomBy(1 / FLOW_GEOMETRY.zoomFactor); return; }
2904
+ if (key === '0' && (canZoom() || canPan())) { handled(); fit(); return; }
2433
2905
  if (key === 'Escape') {
2434
2906
  // 没有可取消的东西时不拦截,让外层浮层的 Esc 照常关闭
2907
+ if (press?.kind === 'port' || draftState !== null) {
2908
+ handled();
2909
+ press = null;
2910
+ dragFrom = null;
2911
+ clearDraftEdge();
2912
+ markTargets(connectFrom);
2913
+ return;
2914
+ }
2435
2915
  if (connectFrom !== null) { handled(); connectFrom = null; flash = ''; paint(); return; }
2436
2916
  if (selected.size > 0) { handled(); setSelection([]); paint(); }
2437
2917
  return;
2438
2918
  }
2439
2919
  if (key === 'ContextMenu' || (key === 'F10' && e.shiftKey)) {
2440
- if (itemKey === null) return;
2920
+ if (itemKey === null || isGraphView) return;
2441
2921
  handled();
2442
2922
  const r = (target.closest('[data-flow-key]') as Element).getBoundingClientRect();
2443
2923
  const s = stage.getBoundingClientRect();
@@ -2459,6 +2939,7 @@ export function createFlowEditor(): SomaComponentDefinition {
2459
2939
  const dx = dir === 'left' ? -step : dir === 'right' ? step : 0;
2460
2940
  const dy = dir === 'up' ? -step : dir === 'down' ? step : 0;
2461
2941
  if (itemKey === null) {
2942
+ if (!canPan()) return;
2462
2943
  // 画布本体:方向键平移
2463
2944
  view = { ...view, panX: view.panX - dx * 5, panY: view.panY - dy * 5 };
2464
2945
  needFit = false;
@@ -2480,10 +2961,12 @@ export function createFlowEditor(): SomaComponentDefinition {
2480
2961
  if (connectFrom !== null) { tryConnect(connectFrom, itemKey.slice(2)); return; }
2481
2962
  setSelection([itemKey], itemKey);
2482
2963
  paint();
2483
- requestConfig(itemKey.slice(2));
2964
+ if (isGraphView) emitNodePick(itemKey.slice(2));
2965
+ else requestConfig(itemKey.slice(2));
2484
2966
  } else {
2485
2967
  setSelection([itemKey], itemKey);
2486
2968
  paint();
2969
+ emitEdgePick(itemKey.slice(2));
2487
2970
  }
2488
2971
  return;
2489
2972
  }
@@ -2493,6 +2976,10 @@ export function createFlowEditor(): SomaComponentDefinition {
2493
2976
  if (next.has(itemKey)) next.delete(itemKey); else next.add(itemKey);
2494
2977
  setSelection(next, itemKey);
2495
2978
  paint();
2979
+ if (isGraphView) {
2980
+ if (itemKey.startsWith('n:')) emitNodePick(itemKey.slice(2));
2981
+ else emitEdgePick(itemKey.slice(2));
2982
+ }
2496
2983
  return;
2497
2984
  }
2498
2985
  if ((key === 'c' || key === 'C') && itemKey.startsWith('n:')) { handled(); flash = ''; startConnect(itemKey.slice(2)); return; }
@@ -2512,6 +2999,8 @@ export function createFlowEditor(): SomaComponentDefinition {
2512
2999
  const build = (host: HTMLElement): void => {
2513
3000
  host.textContent = '';
2514
3001
  toolbar = el('div', FLOW_CLASS.toolbar, { role: 'toolbar', 'aria-label': t('canvas') });
3002
+ // 自管布局的编辑器只报一级结构:工具条 = 面头,右键菜单 = 浮起,空态 / 出错行 / 配置面板 = 子块(不深入画布内部)
3003
+ kitMarkLevel(toolbar, 'head'); kitApplyLevelClass(toolbar);
2515
3004
  const help = el('p', FLOW_CLASS.srOnly, { id: `${uid}-help` });
2516
3005
  help.textContent = t('help');
2517
3006
  stage = el('div', FLOW_CLASS.stage, { tabindex: '0', role: 'group', 'aria-roledescription': t('canvas'), 'aria-label': t('canvas'), 'aria-describedby': `${uid}-help` });
@@ -2538,26 +3027,38 @@ export function createFlowEditor(): SomaComponentDefinition {
2538
3027
  menuOuter = svg('g', FLOW_CLASS.hidden);
2539
3028
  menuFo = svg('foreignObject', FLOW_CLASS.menuFo);
2540
3029
  menuInner = el('div', FLOW_CLASS.menuInner, { role: 'menu' });
3030
+ kitMarkLevel(menuInner, 'float'); kitApplyLevelClass(menuInner);
2541
3031
  menuFo.appendChild(menuInner);
2542
3032
  menuOuter.appendChild(menuFo);
2543
3033
  overlay.append(marqueeOuter, menuOuter);
2544
3034
  emptyOuter = el('div', '');
2545
3035
  emptyInner = el('div', FLOW_CLASS.emptyInner, { role: 'status' });
3036
+ kitMarkLevel(emptyInner, 'sub'); kitApplyLevelClass(emptyInner);
2546
3037
  emptyOuter.appendChild(emptyInner);
2547
3038
  stage.append(canvas, overlay, emptyOuter);
2548
3039
  errorOuter = el('div', FLOW_CLASS.hidden);
2549
3040
  errorInner = el('div', FLOW_CLASS.errorInner, { role: 'alert' });
3041
+ kitMarkLevel(errorOuter, 'sub'); kitApplyLevelClass(errorOuter);
2550
3042
  errorOuter.appendChild(errorInner);
3043
+ if (isGraphView) {
3044
+ retryBtn = mkButton('retry', kitText('soma.kit.retry', undefined, host));
3045
+ retryBtn.setAttribute(KIT_ATTR_RETRY, '');
3046
+ errorOuter.appendChild(retryBtn);
3047
+ } else {
3048
+ retryBtn = null;
3049
+ }
2551
3050
  statusEl = el('p', FLOW_CLASS.status, { role: 'status', 'aria-live': 'polite' });
2552
3051
  // 画布 + 右侧配置面板同一行;面板外层只管显隐,内层管样式
2553
3052
  panelOuter = el('div', FLOW_CLASS.hidden);
2554
- panelInner = el('div', FLOW_CLASS.panel, { role: 'region' });
3053
+ panelInner = el('div', FLOW_CLASS.panel, { role: 'region', [KIT_ATTR_CONTAINER]: 'card' });
3054
+ kitMarkLevel(panelInner, 'sub'); kitApplyLevelClass(panelInner);
2555
3055
  panelOuter.appendChild(panelInner);
2556
3056
  panelId = '';
2557
3057
  panelVals = '';
2558
3058
  const row = el('div', FLOW_CLASS.row);
2559
3059
  row.append(stage, panelOuter);
2560
- host.append(errorOuter, toolbar, help, row, statusEl);
3060
+ summaryTable = isGraphView ? el('table', FLOW_CLASS.srOnly, { [KIT_ATTR_GRAPH_SUMMARY]: '' }) : null;
3061
+ host.append(errorOuter, toolbar, help, row, ...(summaryTable ? [summaryTable] : []), statusEl);
2561
3062
  };
2562
3063
 
2563
3064
  return {
@@ -2584,6 +3085,7 @@ export function createFlowEditor(): SomaComponentDefinition {
2584
3085
  on(stage, 'pointermove', onPointerMove as (e: Event) => void);
2585
3086
  on(stage, 'pointerup', onPointerUp as (e: Event) => void);
2586
3087
  on(stage, 'pointercancel', onPointerCancel);
3088
+ on(stage, 'dragover', onDragOver as (e: Event) => void);
2587
3089
  on(stage, 'wheel', onWheel as (e: Event) => void, { passive: false });
2588
3090
  on(root, 'pointerdown', ((e: PointerEvent) => {
2589
3091
  if (menuOpen && !(e.target as Element | null)?.closest('[data-flow-act^="menu-"]')) closeMenu();
@@ -2593,19 +3095,54 @@ export function createFlowEditor(): SomaComponentDefinition {
2593
3095
  on(root, 'contextmenu', onContextMenu as (e: Event) => void);
2594
3096
  on(root, 'keydown', onKeydown as (e: Event) => void);
2595
3097
  on(root, 'focusin', onFocusIn as (e: Event) => void);
3098
+ // 弹窗打开或容器尺寸变化后重新居中适配画布节点(避免挂载时 0×0 或弹窗显隐切换后节点沉底 / 出屏)
3099
+ const refitIfNeeded = (): void => {
3100
+ const { w, h } = stageSize();
3101
+ if (w <= 0 || h <= 0) return;
3102
+ if (graph.nodes.length === 0 && ghostsOf().nodes.length === 0) return;
3103
+ if (needFit || (!userAdjustedView && (w !== lastStageW || h !== lastStageH))) fit();
3104
+ };
3105
+ if (typeof IntersectionObserver === 'function') {
3106
+ const io = new IntersectionObserver((entries) => {
3107
+ if (entries.some((entry) => entry.isIntersecting)) refitIfNeeded();
3108
+ });
3109
+ io.observe(stage);
3110
+ removers.push(() => io.disconnect());
3111
+ }
3112
+ const win = root.ownerDocument.defaultView;
3113
+ if (win) {
3114
+ const onWinResize = (): void => refitIfNeeded();
3115
+ win.addEventListener('resize', onWinResize);
3116
+ removers.push(() => win.removeEventListener('resize', onWinResize));
3117
+ if (typeof win.requestAnimationFrame === 'function') {
3118
+ const rafId = win.requestAnimationFrame(() => refitIfNeeded());
3119
+ removers.push(() => win.cancelAnimationFrame(rafId));
3120
+ }
3121
+ }
2596
3122
  const port = dndPort();
2597
3123
  if (port) {
2598
3124
  offMove = port.onMove((intent) => {
2599
3125
  const from = fromOf(intent.sourceId);
2600
3126
  const prefix = `${uid}|in|`;
2601
3127
  if (from === null || !intent.targetId.startsWith(prefix)) return;
3128
+ const to = intent.targetId.slice(prefix.length);
3129
+ const pairKey = `${from}\u0000${to}`;
2602
3130
  flash = '';
2603
3131
  dragFrom = null;
2604
- tryConnect(from, intent.targetId.slice(prefix.length));
3132
+ clearDraftEdge();
3133
+ if (recentPortDrop === pairKey) return;
3134
+ recentPortDrop = pairKey;
3135
+ queueMicrotask(() => { if (recentPortDrop === pairKey) recentPortDrop = ''; });
3136
+ tryConnect(from, to);
2605
3137
  });
2606
3138
  }
2607
3139
  return () => {
2608
3140
  mounted = false;
3141
+ panelGen += 1;
3142
+ press = null;
3143
+ dragFrom = null;
3144
+ clearDraftEdge();
3145
+ labelBoxCache.clear();
2609
3146
  for (const fn of removers) fn();
2610
3147
  removers = [];
2611
3148
  for (const fn of dndCleanups) fn();