soma-kit 0.0.0-stage → 0.1.0

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 (353) hide show
  1. package/README.md +539 -2
  2. package/bin/soma-kit.mjs +27 -0
  3. package/package.json +66 -4
  4. package/packs/ai/agent-run-card.ts +64 -0
  5. package/packs/ai/evaluation-card.ts +51 -0
  6. package/packs/ai/guardrail-policy-card.ts +48 -0
  7. package/packs/ai/index.ts +31 -0
  8. package/packs/ai/model-card.ts +55 -0
  9. package/packs/ai/model-routing-card.ts +49 -0
  10. package/packs/ai/prompt-template-card.ts +49 -0
  11. package/packs/ai/texts.ts +19 -0
  12. package/packs/commerce/address-card.ts +58 -0
  13. package/packs/commerce/coupon-card.ts +64 -0
  14. package/packs/commerce/index.ts +25 -0
  15. package/packs/commerce/order-card.ts +60 -0
  16. package/packs/commerce/purchase-order-card.ts +74 -0
  17. package/packs/commerce/texts.ts +14 -0
  18. package/packs/finance/index.ts +30 -0
  19. package/packs/finance/invoice-summary-card.ts +48 -0
  20. package/packs/finance/reconcile-board.ts +450 -0
  21. package/packs/finance/reconcile-case-card.ts +70 -0
  22. package/packs/finance/reconcile-desk/compile.ts +208 -0
  23. package/packs/finance/reconcile-desk/index.ts +20 -0
  24. package/packs/finance/reconcile-desk/shell.ts +27 -0
  25. package/packs/finance/texts.ts +21 -0
  26. package/packs/ops/change-window-card.ts +54 -0
  27. package/packs/ops/dependency-status-card.ts +50 -0
  28. package/packs/ops/error-budget-card.ts +60 -0
  29. package/packs/ops/execution-task-runner.ts +61 -0
  30. package/packs/ops/index.ts +36 -0
  31. package/packs/ops/integration-status-card.ts +45 -0
  32. package/packs/ops/release-readiness-card.ts +63 -0
  33. package/packs/ops/runbook-execution-card.ts +81 -0
  34. package/packs/ops/texts.ts +21 -0
  35. package/packs/security/control-evidence-card.ts +54 -0
  36. package/packs/security/finding-card.ts +96 -0
  37. package/packs/security/index.ts +29 -0
  38. package/packs/security/texts.ts +31 -0
  39. package/packs/shared/card-util.ts +60 -0
  40. package/packs/shared/wrap.ts +13 -0
  41. package/spec/generated/kit-app.schema.json +84 -0
  42. package/spec/generated/kit-page.schema.json +2766 -0
  43. package/spec/kit-grammar.json +1358 -0
  44. package/spec/kit-grammar.schema.json +716 -0
  45. package/src/app/app-config.ts +108 -0
  46. package/src/app/compose-apps.ts +139 -0
  47. package/src/app/define-kit-actions.ts +89 -0
  48. package/src/app/define-kit-app.ts +362 -0
  49. package/src/app/define-kit-pack.ts +114 -0
  50. package/src/app/envelope.ts +117 -0
  51. package/src/app/index.ts +50 -0
  52. package/src/app/notify-renderer.ts +114 -0
  53. package/src/app/paged-list-adapter.ts +246 -0
  54. package/src/app/server-pages.ts +303 -0
  55. package/src/app/server.ts +244 -0
  56. package/src/app/submit.types.ts +87 -0
  57. package/src/base/action-busy.ts +159 -0
  58. package/src/base/action-gate.ts +267 -0
  59. package/src/base/action-status.ts +31 -0
  60. package/src/base/alert.ts +136 -0
  61. package/src/base/avatar.ts +271 -0
  62. package/src/base/button.ts +139 -0
  63. package/src/base/cascader.ts +523 -0
  64. package/src/base/check-core.ts +214 -0
  65. package/src/base/checkbox.ts +35 -0
  66. package/src/base/choice.ts +183 -0
  67. package/src/base/color-picker.ts +316 -0
  68. package/src/base/combobox.ts +61 -0
  69. package/src/base/command-palette.ts +371 -0
  70. package/src/base/context-menu.ts +103 -0
  71. package/src/base/countdown.ts +168 -0
  72. package/src/base/date-range.ts +444 -0
  73. package/src/base/date.ts +899 -0
  74. package/src/base/divider.ts +156 -0
  75. package/src/base/fab.ts +192 -0
  76. package/src/base/icons.ts +106 -0
  77. package/src/base/image.ts +177 -0
  78. package/src/base/index.ts +214 -0
  79. package/src/base/input.ts +316 -0
  80. package/src/base/kbd.ts +99 -0
  81. package/src/base/link.ts +167 -0
  82. package/src/base/listbox-core.ts +965 -0
  83. package/src/base/mentions.ts +323 -0
  84. package/src/base/menu-button.ts +240 -0
  85. package/src/base/menu-core.ts +341 -0
  86. package/src/base/month-grid.ts +171 -0
  87. package/src/base/motion/aura.ts +94 -0
  88. package/src/base/motion/hover-3d.ts +154 -0
  89. package/src/base/motion/hover-gallery.ts +185 -0
  90. package/src/base/motion/index.ts +27 -0
  91. package/src/base/motion/limits.ts +75 -0
  92. package/src/base/motion/marquee.ts +157 -0
  93. package/src/base/motion/text-rotate.ts +195 -0
  94. package/src/base/number.ts +121 -0
  95. package/src/base/otp.ts +259 -0
  96. package/src/base/permission-gate.ts +99 -0
  97. package/src/base/popover.ts +352 -0
  98. package/src/base/popup.ts +542 -0
  99. package/src/base/portal-core.ts +297 -0
  100. package/src/base/price-text.ts +126 -0
  101. package/src/base/progress.ts +216 -0
  102. package/src/base/qr-code.ts +446 -0
  103. package/src/base/qty-stepper.ts +241 -0
  104. package/src/base/radio.ts +33 -0
  105. package/src/base/range.ts +444 -0
  106. package/src/base/rating.ts +249 -0
  107. package/src/base/segmented.ts +286 -0
  108. package/src/base/select.ts +57 -0
  109. package/src/base/shared.ts +708 -0
  110. package/src/base/swap.ts +86 -0
  111. package/src/base/switch.ts +111 -0
  112. package/src/base/tag-input.ts +464 -0
  113. package/src/base/tag.ts +250 -0
  114. package/src/base/text.ts +126 -0
  115. package/src/base/textarea.ts +129 -0
  116. package/src/base/time-picker.ts +606 -0
  117. package/src/base/tree-select.ts +629 -0
  118. package/src/base/upload.ts +548 -0
  119. package/src/base/virtual-list.ts +286 -0
  120. package/src/biz/approval-desk/compile.ts +179 -0
  121. package/src/biz/approval-desk/index.ts +21 -0
  122. package/src/biz/approval-desk/shell.ts +50 -0
  123. package/src/biz/auth-panel/compile.ts +196 -0
  124. package/src/biz/auth-panel/index.ts +24 -0
  125. package/src/biz/auth-panel/shell.ts +46 -0
  126. package/src/biz/category-crud/compile.ts +173 -0
  127. package/src/biz/category-crud/index.ts +19 -0
  128. package/src/biz/category-crud/shell.ts +29 -0
  129. package/src/biz/checkout-page/compile.ts +111 -0
  130. package/src/biz/checkout-page/index.ts +20 -0
  131. package/src/biz/checkout-page/shell.ts +50 -0
  132. package/src/biz/compose.ts +313 -0
  133. package/src/biz/data-components.ts +26 -0
  134. package/src/biz/define.ts +23 -0
  135. package/src/biz/import-wizard/compile.ts +204 -0
  136. package/src/biz/import-wizard/hub.ts +540 -0
  137. package/src/biz/import-wizard/index.ts +24 -0
  138. package/src/biz/import-wizard/shell.ts +161 -0
  139. package/src/biz/index.ts +80 -0
  140. package/src/biz/landing-page/compile.ts +67 -0
  141. package/src/biz/landing-page/index.ts +20 -0
  142. package/src/biz/landing-page/shell.ts +48 -0
  143. package/src/biz/link/hub.ts +255 -0
  144. package/src/biz/link/shared.ts +493 -0
  145. package/src/biz/master-sub/compile.ts +232 -0
  146. package/src/biz/master-sub/index.ts +20 -0
  147. package/src/biz/master-sub/shell.ts +56 -0
  148. package/src/biz/multi-board/compile.ts +234 -0
  149. package/src/biz/multi-board/index.ts +19 -0
  150. package/src/biz/multi-board/shell.ts +70 -0
  151. package/src/biz/names.ts +30 -0
  152. package/src/biz/notification-center/compile.ts +138 -0
  153. package/src/biz/notification-center/index.ts +29 -0
  154. package/src/biz/notification-center/shell.ts +42 -0
  155. package/src/biz/page-templates/result-page/compile.ts +46 -0
  156. package/src/biz/page-templates/result-page/index.ts +19 -0
  157. package/src/biz/page-templates/result-page/shell.ts +31 -0
  158. package/src/biz/page-templates/shared.ts +121 -0
  159. package/src/biz/page-templates/sign-in-page/compile.ts +176 -0
  160. package/src/biz/page-templates/sign-in-page/index.ts +18 -0
  161. package/src/biz/page-templates/sign-in-page/shell.ts +116 -0
  162. package/src/biz/record-detail/compile.ts +290 -0
  163. package/src/biz/record-detail/index.ts +22 -0
  164. package/src/biz/record-detail/shell.ts +64 -0
  165. package/src/biz/settings-center/compile.ts +100 -0
  166. package/src/biz/settings-center/index.ts +18 -0
  167. package/src/biz/settings-center/shell.ts +51 -0
  168. package/src/biz/shared/action-host.ts +469 -0
  169. package/src/biz/shared/coordinator.ts +516 -0
  170. package/src/biz/shared/index.ts +9 -0
  171. package/src/biz/shared/pipes.ts +58 -0
  172. package/src/biz/shared/runtime-hub.ts +112 -0
  173. package/src/biz/shared/step-values.ts +25 -0
  174. package/src/biz/single-form/compile.ts +146 -0
  175. package/src/biz/single-form/index.ts +18 -0
  176. package/src/biz/single-form/shell.ts +38 -0
  177. package/src/biz/standard-crud/bridge.ts +11 -0
  178. package/src/biz/standard-crud/compile.ts +546 -0
  179. package/src/biz/standard-crud/index.ts +18 -0
  180. package/src/biz/standard-crud/shell.ts +157 -0
  181. package/src/biz/step-form/compile.ts +400 -0
  182. package/src/biz/step-form/hub.ts +412 -0
  183. package/src/biz/step-form/index.ts +23 -0
  184. package/src/biz/step-form/shell.ts +96 -0
  185. package/src/biz/step-form/steps-ref.ts +112 -0
  186. package/src/biz/types.ts +96 -0
  187. package/src/cli/kit-cli.ts +102 -0
  188. package/src/compile/action-host-attach.ts +76 -0
  189. package/src/compile/compile-page.ts +472 -0
  190. package/src/compile/component-candidates.ts +147 -0
  191. package/src/compile/fragment.ts +104 -0
  192. package/src/compile/hints.ts +255 -0
  193. package/src/compile/index.ts +16 -0
  194. package/src/compile/locate.ts +166 -0
  195. package/src/compile/page-params.ts +80 -0
  196. package/src/compile/parse.ts +355 -0
  197. package/src/compile/redirect.ts +90 -0
  198. package/src/compile/registry.ts +30 -0
  199. package/src/compile/remove-guard.ts +99 -0
  200. package/src/compile/styles.ts +244 -0
  201. package/src/compile/types.ts +106 -0
  202. package/src/data/amount-breakdown.ts +132 -0
  203. package/src/data/anchor-nav.ts +225 -0
  204. package/src/data/approval-flow.ts +269 -0
  205. package/src/data/assignment-picker.ts +652 -0
  206. package/src/data/async-result-panel.ts +308 -0
  207. package/src/data/breadcrumbs.ts +197 -0
  208. package/src/data/calendar.ts +363 -0
  209. package/src/data/carousel.ts +408 -0
  210. package/src/data/chart.ts +726 -0
  211. package/src/data/checklist.ts +215 -0
  212. package/src/data/code-view.ts +415 -0
  213. package/src/data/comment-thread.ts +342 -0
  214. package/src/data/confirm-dialog.ts +144 -0
  215. package/src/data/context-menu.ts +216 -0
  216. package/src/data/d9-limits.ts +42 -0
  217. package/src/data/d9-util.ts +81 -0
  218. package/src/data/diff.ts +239 -0
  219. package/src/data/display-util.ts +135 -0
  220. package/src/data/dock.ts +152 -0
  221. package/src/data/embed.ts +200 -0
  222. package/src/data/field-mapper.ts +544 -0
  223. package/src/data/flow-editor-contract.ts +41 -0
  224. package/src/data/flow-editor.ts +2622 -0
  225. package/src/data/flow-remote-options.ts +257 -0
  226. package/src/data/footer.ts +157 -0
  227. package/src/data/form-draft-registry.ts +76 -0
  228. package/src/data/gantt.ts +430 -0
  229. package/src/data/hero.ts +149 -0
  230. package/src/data/image-viewer.ts +333 -0
  231. package/src/data/index.ts +268 -0
  232. package/src/data/item-list.ts +335 -0
  233. package/src/data/kanban.ts +667 -0
  234. package/src/data/media-grid.ts +246 -0
  235. package/src/data/mega-menu.ts +257 -0
  236. package/src/data/menu-dom.ts +169 -0
  237. package/src/data/menu.ts +464 -0
  238. package/src/data/mockup.ts +176 -0
  239. package/src/data/modal-dialog.ts +182 -0
  240. package/src/data/navbar.ts +292 -0
  241. package/src/data/object-form.ts +1981 -0
  242. package/src/data/options-bus.ts +24 -0
  243. package/src/data/outcome-watch.ts +40 -0
  244. package/src/data/overlay-portal.ts +6 -0
  245. package/src/data/pager.ts +473 -0
  246. package/src/data/permission-matrix.ts +432 -0
  247. package/src/data/permission-tree.ts +916 -0
  248. package/src/data/pricing-table.ts +269 -0
  249. package/src/data/prompt-dialog.ts +235 -0
  250. package/src/data/reaction-bar.ts +236 -0
  251. package/src/data/record-card.ts +413 -0
  252. package/src/data/record-picker.ts +489 -0
  253. package/src/data/redirect.ts +109 -0
  254. package/src/data/remote-options.ts +54 -0
  255. package/src/data/request-console.ts +399 -0
  256. package/src/data/resident.ts +58 -0
  257. package/src/data/result-panel.ts +160 -0
  258. package/src/data/rich-text.ts +626 -0
  259. package/src/data/row-editor.ts +1066 -0
  260. package/src/data/rule-builder.ts +1137 -0
  261. package/src/data/shape-util.ts +221 -0
  262. package/src/data/staged-rows.ts +69 -0
  263. package/src/data/stat-group.ts +231 -0
  264. package/src/data/static-lazy.ts +63 -0
  265. package/src/data/static-registry.ts +227 -0
  266. package/src/data/steps.ts +195 -0
  267. package/src/data/survey.ts +455 -0
  268. package/src/data/system-switcher.ts +243 -0
  269. package/src/data/timeline.ts +204 -0
  270. package/src/data/tour-guide.ts +392 -0
  271. package/src/data/transfer.ts +597 -0
  272. package/src/data/tree-check.ts +30 -0
  273. package/src/data/tree-table.ts +674 -0
  274. package/src/data/tree.ts +656 -0
  275. package/src/data/trend-line.ts +147 -0
  276. package/src/data/virtual-rows.ts +556 -0
  277. package/src/data/watermark.ts +140 -0
  278. package/src/data/wrap.ts +267 -0
  279. package/src/data/wrapped-candidates.ts +96 -0
  280. package/src/frames/blank-frame.ts +19 -0
  281. package/src/frames/index.ts +44 -0
  282. package/src/frames/page-bar.ts +185 -0
  283. package/src/frames/page-header.ts +185 -0
  284. package/src/frames/page-status.ts +54 -0
  285. package/src/frames/resize-handle.ts +147 -0
  286. package/src/frames/shared.ts +242 -0
  287. package/src/frames/single-frame.ts +16 -0
  288. package/src/frames/split-frame/index.ts +4 -0
  289. package/src/frames/split-frame/shell.ts +219 -0
  290. package/src/frames/split-frame/span.ts +64 -0
  291. package/src/frames/split-frame/wiring.ts +164 -0
  292. package/src/frames/tabs-frame/index.ts +3 -0
  293. package/src/frames/tabs-frame/shell.ts +112 -0
  294. package/src/frames/tabs-frame/wiring.ts +69 -0
  295. package/src/frames/top-main-frame.ts +20 -0
  296. package/src/frames/types.ts +72 -0
  297. package/src/frames/workspace-frame/extras.ts +197 -0
  298. package/src/frames/workspace-frame/index.ts +13 -0
  299. package/src/frames/workspace-frame/shell.ts +282 -0
  300. package/src/frames/workspace-frame/state.ts +152 -0
  301. package/src/frames/workspace-frame/view.ts +1013 -0
  302. package/src/generated/kit-grammar-runtime.ts +2822 -0
  303. package/src/generated/page-origin.ts +57 -0
  304. package/src/i18n/index.ts +22 -0
  305. package/src/i18n/kit-text.ts +692 -0
  306. package/src/i18n/resolve-text-refs.ts +128 -0
  307. package/src/index.ts +6 -0
  308. package/src/object-renderer/action-gate.ts +216 -0
  309. package/src/object-renderer/adopt-gate.ts +333 -0
  310. package/src/object-renderer/arrange.ts +411 -0
  311. package/src/object-renderer/candidates.ts +68 -0
  312. package/src/object-renderer/collapse-wiring.ts +99 -0
  313. package/src/object-renderer/collection-expand.ts +185 -0
  314. package/src/object-renderer/collection-parts.ts +653 -0
  315. package/src/object-renderer/collection-table.ts +503 -0
  316. package/src/object-renderer/collection.ts +628 -0
  317. package/src/object-renderer/compile-data.ts +549 -0
  318. package/src/object-renderer/defaults.ts +252 -0
  319. package/src/object-renderer/display-checks.ts +153 -0
  320. package/src/object-renderer/emit-events.ts +498 -0
  321. package/src/object-renderer/emit-object.ts +98 -0
  322. package/src/object-renderer/emit-static.ts +1036 -0
  323. package/src/object-renderer/field-policy.ts +89 -0
  324. package/src/object-renderer/field-value.ts +581 -0
  325. package/src/object-renderer/form-detail.ts +116 -0
  326. package/src/object-renderer/index.ts +13 -0
  327. package/src/object-renderer/linkage.ts +371 -0
  328. package/src/object-renderer/merge-class.ts +126 -0
  329. package/src/object-renderer/mode.ts +25 -0
  330. package/src/object-renderer/outcome-draft.ts +61 -0
  331. package/src/object-renderer/parts.ts +136 -0
  332. package/src/object-renderer/pick-component.ts +36 -0
  333. package/src/object-renderer/render-object.ts +724 -0
  334. package/src/object-renderer/request-actions.ts +581 -0
  335. package/src/object-renderer/skeleton.ts +101 -0
  336. package/src/object-renderer/table-actions.ts +438 -0
  337. package/src/object-renderer/table-summary.ts +105 -0
  338. package/src/object-renderer/table-tools.ts +1072 -0
  339. package/src/object-renderer/types.ts +936 -0
  340. package/src/page-target/ai-surface.ts +154 -0
  341. package/src/page-target/compile.ts +354 -0
  342. package/src/page-target/drift.ts +186 -0
  343. package/src/page-target/index.ts +25 -0
  344. package/src/page-target/intent-map.ts +137 -0
  345. package/src/page-target/intent-schema.ts +711 -0
  346. package/src/page-target/origin.ts +17 -0
  347. package/src/page-target/target.ts +450 -0
  348. package/src/page-target/writer-policy.ts +315 -0
  349. package/src/theme/block-theme.ts +202 -0
  350. package/src/theme/kit-theme-text.ts +2 -0
  351. package/src/theme/kit-theme.css +275 -0
  352. package/src/theme/kit-theme.tpl +275 -0
  353. package/src/theme/theme-tokens.ts +135 -0
@@ -0,0 +1,1066 @@
1
+ // RowEditor:行表编辑器(layer: data,写死形状,accept: single)。
2
+ //
3
+ // 数据:`data` 是 { title?, hint?, rows[], error? };`columns` 声明列:
4
+ // (number / money / date 三种列:number、money 校验为数字并可设 min / max / decimals,money 展示按币种格式化,数值列右对齐;
5
+ // date 用原生日期框,值为 YYYY-MM-DD。`footer: sum` 在行表下出合计行,只对 number / money 列求和展示;`min_rows` / `max_rows` 限行数。)
6
+ // [{ key, label, kind?: text | select | bool | json | number | money | date, options?, placeholder?, required?, pattern?, pattern_message?, mono?, span?, default?, true_label?, false_label? }]
7
+ // 已有行按列显示(bool 显示 true_label / false_label,select 显示选项文字,json 非字符串按 JSON 文本),行尾「删除」钮;
8
+ // 下方是同列的录入区(readonly 时没有录入区与删除钮),点「添加」先做声明式校验(required / pattern),
9
+ // 通过抛 `add { row, replaced }`;失败抛 `invalid { message }` 并显示在错误行,不抛 add。
10
+ // 主键列 = `row_key`(默认第一列),同主键的新行视为替换(replaced 为真)。删除抛 `remove { key, row, index }`。
11
+ // `auto_apply`(默认真):add / remove 之后组件先改自己的行副本并抛 `change { value }`;
12
+ // 假则组件不改行,由页面改 data.rows(受控,页面可在 add 里再做业务校验并写 data.error)。
13
+ // 录入草稿在组件内,重画与 columns 选项变化都不丢;数据只经 textContent / value 写入。
14
+
15
+ import type { SomaComponentDefinition } from 'soma-core';
16
+ import { bool, createKitController, FIELD_CLASS, formatValue, joinClass, num, str, type KitApi } from '../base/shared';
17
+ import { kitText, type KitTextKey } from '../i18n/kit-text';
18
+ import { KIT_BUSY_PROP_DEFS, kitBusyOf } from '../base/action-busy';
19
+ import { KIT_DATE_CLASS_CANDIDATES, mountKitDateField } from '../base/date';
20
+ import { KIT_LISTBOX_CLASS_CANDIDATES } from '../base/listbox-core';
21
+ import { createKitEmbedBag, mountKitSelectField, type KitEmbedBag } from './embed';
22
+ import { fetchRemoteOptionRows } from './remote-options';
23
+ import { actionButton, BUTTON_CLASS_TOKENS, classTokens, emptyNode, mk, recOf, rowsOf, textOf, TONE_SOFT } from './shape-util';
24
+ import type { SomaDataPort } from 'soma-core';
25
+ import { askKitConfirm } from './confirm-dialog';
26
+ import { watchKitOutcome } from './outcome-watch';
27
+ import { stagedDiff, stagedHeadKeys, stagedMarks, stagedModel } from './staged-rows';
28
+
29
+ // 集合本地草稿(staged):未同步条与行小标的类串(条与小标的语气取 warning-soft,与「已采纳」标签同一口径)
30
+ const STAGE_BAR_CLASS = `flex flex-wrap items-center justify-between gap-2 rounded-md px-3 py-2 text-sm ${TONE_SOFT.warning}`;
31
+ const STAGE_BTNS_CLASS = 'flex items-center gap-2';
32
+ const STAGE_MARK_CLASS = `ms-2 rounded-full px-2 py-0.5 text-xs font-medium ${TONE_SOFT.warning}`;
33
+ const STAGE_NOTE_CLASS = 'w-full text-xs';
34
+
35
+ // ── 类串常量与 Tailwind 候选清单 ──
36
+
37
+ const SPAN_CLASS: Readonly<Record<number, string>> = Object.freeze({
38
+ 1: 'col-span-1', 2: 'col-span-2', 3: 'col-span-3', 4: 'col-span-4', 5: 'col-span-5', 6: 'col-span-6',
39
+ 7: 'col-span-7', 8: 'col-span-8', 9: 'col-span-9', 10: 'col-span-10',
40
+ });
41
+ const FORM_COLS: Readonly<Record<number, string>> = Object.freeze({
42
+ 1: 'grid-cols-1', 2: 'grid-cols-1 @md:grid-cols-2', 3: 'grid-cols-1 @md:grid-cols-3', 4: 'grid-cols-1 @md:grid-cols-2 @2xl:grid-cols-4',
43
+ 5: 'grid-cols-1 @md:grid-cols-3 @2xl:grid-cols-5', 6: 'grid-cols-1 @md:grid-cols-3 @2xl:grid-cols-6',
44
+ });
45
+
46
+ const ROOT_CLASS = 'flex flex-col gap-3';
47
+ const TITLE_CLASS = 'text-sm font-semibold text-fg';
48
+ const HINT_CLASS = 'text-xs text-fg-subtle';
49
+ const HEAD_CLASS = 'grid grid-cols-12 items-center gap-2 border-b border-border px-2 py-2 text-xs font-medium text-fg-muted';
50
+ const ROW_CLASS = 'grid grid-cols-12 items-center gap-2 border-b border-border-subtle px-2 py-2';
51
+ const CELL_CLASS = 'min-w-0 break-all text-sm text-fg';
52
+ const CELL_MONO = 'min-w-0 break-all font-mono text-xs text-fg-muted';
53
+ const CELL_MUTED = 'min-w-0 break-all text-sm text-fg-muted';
54
+ const END_CLASS = 'col-span-2 justify-self-end';
55
+ const FORM_CLASS = 'grid gap-3';
56
+ const FIELD_WRAP = 'flex flex-col gap-1';
57
+ const LABEL_CLASS = 'text-xs font-medium text-fg-muted';
58
+ const REQUIRED_MARK = 'text-danger-on-soft';
59
+ const TEXTAREA_LIKE = 'font-mono';
60
+ const ERROR_CLASS = 'text-sm text-danger-on-soft';
61
+ const LIST_WRAP = 'flex flex-col';
62
+ const NUM_ALIGN = 'text-end tabular-nums';
63
+ const FOOTER_ROW_CLASS = 'grid grid-cols-12 items-center gap-2 border-t border-border px-2 py-2 text-sm font-semibold text-fg';
64
+ const COUNT_CLASS = 'text-xs text-fg-subtle';
65
+ const DATE_FIELD_CLASS = 'block h-9 w-full rounded-md border border-border bg-surface ps-3 pe-8 text-sm text-fg transition-colors placeholder:text-fg-subtle enabled:hover:border-fg-subtle focus-visible:outline-none focus-visible:border-primary focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:bg-surface-sunken disabled:text-fg-subtle disabled:opacity-60 read-only:bg-surface-sunken';
66
+
67
+ export const KIT_ROW_EDITOR_CLASS_CANDIDATES: readonly string[] = classTokens(
68
+ ROOT_CLASS, TITLE_CLASS, HINT_CLASS, HEAD_CLASS, ROW_CLASS, CELL_CLASS, CELL_MONO, CELL_MUTED, END_CLASS, FORM_CLASS, FIELD_WRAP,
69
+ LABEL_CLASS, REQUIRED_MARK, TEXTAREA_LIKE, ERROR_CLASS, LIST_WRAP, Object.values(SPAN_CLASS), Object.values(FORM_COLS),
70
+ FIELD_CLASS.md, BUTTON_CLASS_TOKENS, 'self-end', '@container', NUM_ALIGN, FOOTER_ROW_CLASS, COUNT_CLASS, DATE_FIELD_CLASS, KIT_DATE_CLASS_CANDIDATES, KIT_LISTBOX_CLASS_CANDIDATES,
71
+ STAGE_BAR_CLASS, STAGE_BTNS_CLASS, STAGE_MARK_CLASS, STAGE_NOTE_CLASS,
72
+ );
73
+
74
+ // ── 数据规整纯函数:列声明、单元格文字、录入校验、草稿转行 ──
75
+
76
+ export type KitRowColumnKind = 'text' | 'select' | 'bool' | 'json' | 'number' | 'money' | 'date';
77
+
78
+ /** 数值列(右对齐、可合计) */
79
+ export function isNumericRowKind(kind: KitRowColumnKind): boolean {
80
+ return kind === 'number' || kind === 'money';
81
+ }
82
+
83
+ export interface KitRowColumn {
84
+ /** number / money:数值下限与上限(缺省不限) */
85
+ min: number | null;
86
+ max: number | null;
87
+ /** number / money:小数位上限;money 缺省 2,number 缺省 -1(不限) */
88
+ decimals: number;
89
+ /** money 的币种代码(展示用,缺省 CNY) */
90
+ currency: string;
91
+ /** 参与 footer: sum 合计(number / money 缺省真) */
92
+ sum: boolean;
93
+ key: string;
94
+ label: string;
95
+ kind: KitRowColumnKind;
96
+ options: Array<{ value: string; label: string }>;
97
+ placeholder: string;
98
+ required: boolean;
99
+ pattern: string;
100
+ patternMessage: string;
101
+ mono: boolean;
102
+ span: number;
103
+ dflt: string;
104
+ trueLabel: string;
105
+ falseLabel: string;
106
+ requiredMessage: string;
107
+ /** 进录入区(假 = 只读展示列) */
108
+ editable: boolean;
109
+ /** 进行表(假 = 只在录入区出现) */
110
+ list: boolean;
111
+ /** GB5:select 列的远程选项(options 写成对象 { from, valueKey?, labelKey?, rowsPath?, params? });静态选项为 null */
112
+ optionsFrom: KitRowOptionsFrom | null;
113
+ }
114
+
115
+ /** select 列的远程选项声明(规整后;键同 schema.<字段>.options 的对象写法,params 只许字面量) */
116
+ export interface KitRowOptionsFrom {
117
+ from: string;
118
+ valueKey: string;
119
+ labelKey: string;
120
+ rowsPath: string;
121
+ params: Record<string, string>;
122
+ }
123
+
124
+ function rowOptionsFromOf(raw: unknown, kind: KitRowColumnKind): KitRowOptionsFrom | null {
125
+ if (kind !== 'select' || raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null;
126
+ const r = raw as Record<string, unknown>;
127
+ if (typeof r.from !== 'string' || !r.from.startsWith('/')) return null;
128
+ const params: Record<string, string> = {};
129
+ if (r.params !== null && typeof r.params === 'object' && !Array.isArray(r.params)) {
130
+ for (const [k, v] of Object.entries(r.params as Record<string, unknown>)) {
131
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') params[k] = String(v);
132
+ }
133
+ }
134
+ return {
135
+ from: r.from,
136
+ valueKey: textOf(r.valueKey) || 'value',
137
+ labelKey: textOf(r.labelKey) || 'label',
138
+ rowsPath: textOf(r.rowsPath),
139
+ params,
140
+ };
141
+ }
142
+
143
+ /** 列声明(纯函数):缺 key 的丢弃;span 缺省按「(10 - 已指定) / 未指定列数」均分 */
144
+ export function rowColumnsOf(raw: unknown, at?: Element | string | null): KitRowColumn[] {
145
+ const list = rowsOf(raw).filter((c) => textOf(c.key) !== '');
146
+ const fixed = list.reduce((n, c) => n + (Number.isFinite(Number(c.span)) && Number(c.span) > 0 ? Math.min(10, Math.floor(Number(c.span))) : 0), 0);
147
+ const free = list.filter((c) => !(Number.isFinite(Number(c.span)) && Number(c.span) > 0)).length;
148
+ const share = free === 0 ? 1 : Math.max(1, Math.min(10, Math.floor(Math.max(1, 10 - fixed) / free)));
149
+ return list.map((c) => {
150
+ const k = textOf(c.kind);
151
+ const kind: KitRowColumnKind = k === 'select' || k === 'bool' || k === 'json' || k === 'number' || k === 'money' || k === 'date' ? k : 'text';
152
+ const spanNum = Number(c.span);
153
+ const minNum = c.min === undefined || c.min === null || c.min === '' ? NaN : Number(c.min);
154
+ const maxNum = c.max === undefined || c.max === null || c.max === '' ? NaN : Number(c.max);
155
+ const decNum = c.decimals === undefined || c.decimals === null || c.decimals === '' ? NaN : Number(c.decimals);
156
+ return {
157
+ min: Number.isFinite(minNum) ? minNum : null,
158
+ max: Number.isFinite(maxNum) ? maxNum : null,
159
+ decimals: Number.isFinite(decNum) && decNum >= 0 ? Math.min(6, Math.floor(decNum)) : kind === 'money' ? 2 : -1,
160
+ currency: textOf(c.currency) || 'CNY',
161
+ sum: c.sum === undefined ? isNumericRowKind(kind) : c.sum === true,
162
+ key: textOf(c.key),
163
+ label: textOf(c.label) || textOf(c.key),
164
+ kind,
165
+ options: Array.isArray(c.options) ? rowsOf(c.options).map((o) => ({ value: textOf(o.value), label: textOf(o.label) || textOf(o.value) })) : [],
166
+ optionsFrom: rowOptionsFromOf(c.options, kind),
167
+ placeholder: textOf(c.placeholder),
168
+ required: c.required === true,
169
+ pattern: textOf(c.pattern),
170
+ patternMessage: textOf(c.pattern_message),
171
+ mono: c.mono === true,
172
+ span: Number.isFinite(spanNum) && spanNum > 0 ? Math.min(10, Math.floor(spanNum)) : share,
173
+ dflt: textOf(c.default),
174
+ requiredMessage: textOf(c.required_message),
175
+ editable: c.editable !== false,
176
+ list: c.list !== false,
177
+ trueLabel: textOf(c.true_label) || kitText('soma.kit.yes', undefined, at),
178
+ falseLabel: textOf(c.false_label) || kitText('soma.kit.no', undefined, at),
179
+ };
180
+ });
181
+ }
182
+
183
+ /** 一格的展示文字(纯函数) */
184
+ export function rowCellText(col: KitRowColumn, value: unknown, locale = ''): string {
185
+ if (value === undefined || value === null) return '';
186
+ if (value === '' && (col.kind === 'number' || col.kind === 'money')) return '';
187
+ if (col.kind === 'number') return formatValue(value, 'number', locale);
188
+ if (col.kind === 'money') return formatValue(value, `currency:${col.currency}`, locale);
189
+ if (col.kind === 'bool') return value === true || value === 'true' ? col.trueLabel : col.falseLabel;
190
+ if (col.kind === 'select') return col.options.find((o) => o.value === String(value))?.label ?? String(value);
191
+ if (typeof value === 'object') {
192
+ try { return JSON.stringify(value); } catch { return ''; }
193
+ }
194
+ return String(value);
195
+ }
196
+
197
+ /** YYYY-MM-DD 且是真实存在的日期 */
198
+ function isIsoDate(v: string): boolean {
199
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) return false;
200
+ const d = new Date(`${v}T00:00:00Z`);
201
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === v;
202
+ }
203
+
204
+ /** 合计行(纯函数):每个 sum 为真的数值列求和,按列小数位(缺省 6 位)舍入消浮点误差;非数值格忽略 */
205
+ export function rowTotals(columns: readonly KitRowColumn[], rows: ReadonlyArray<Record<string, unknown>>): Record<string, number> {
206
+ const out: Record<string, number> = {};
207
+ for (const c of columns) {
208
+ if (!c.sum || !isNumericRowKind(c.kind)) continue;
209
+ const scale = 10 ** (c.decimals >= 0 ? c.decimals : 6);
210
+ let total = 0;
211
+ for (const r of rows) {
212
+ const n = Number(r[c.key]);
213
+ if (r[c.key] !== '' && r[c.key] !== null && r[c.key] !== undefined && Number.isFinite(n)) total += n;
214
+ }
215
+ out[c.key] = Math.round(total * scale) / scale;
216
+ }
217
+ return out;
218
+ }
219
+
220
+ /** 录入校验(纯函数):通过返回 null,否则返回提示文字 */
221
+ export function validateRowDraft(columns: readonly KitRowColumn[], draft: Readonly<Record<string, string>>, requiredText: string, at?: Element | string | null): string | null {
222
+ const T = (key: KitTextKey, params: Record<string, string | number>): string => kitText(key, params, at);
223
+ for (const c of columns) {
224
+ const v = (draft[c.key] ?? '').trim();
225
+ if (!c.editable) continue;
226
+ if (c.required && v === '') return c.requiredMessage !== '' ? c.requiredMessage : `${requiredText}${c.label}`;
227
+ if (isNumericRowKind(c.kind) && v !== '') {
228
+ const n = Number(v);
229
+ if (!Number.isFinite(n)) return T('soma.kit.field_number', { label: c.label });
230
+ if (c.min !== null && n < c.min) return T('soma.kit.field_min', { label: c.label, n: c.min });
231
+ if (c.max !== null && n > c.max) return T('soma.kit.field_max', { label: c.label, n: c.max });
232
+ const frac = v.includes('.') ? v.split('.')[1]!.length : 0;
233
+ if (c.decimals >= 0 && frac > c.decimals) return T('soma.kit.field_decimals', { label: c.label, n: c.decimals });
234
+ }
235
+ if (c.kind === 'date' && v !== '' && !isIsoDate(v)) return T('soma.kit.field_date', { label: c.label });
236
+ if (c.pattern !== '' && v !== '') {
237
+ let re: RegExp | null = null;
238
+ try { re = new RegExp(c.pattern); } catch { re = null; }
239
+ if (re && !re.test(v)) return c.patternMessage !== '' ? c.patternMessage : T('soma.kit.field_format', { label: c.label });
240
+ }
241
+ }
242
+ return null;
243
+ }
244
+
245
+ /** 草稿 -> 行:bool 转布尔,json 能解析就解析,其余原样字符串(text 去首尾空白) */
246
+ export function draftToRow(columns: readonly KitRowColumn[], draft: Readonly<Record<string, string>>): Record<string, unknown> {
247
+ const row: Record<string, unknown> = {};
248
+ for (const c of columns) {
249
+ if (!c.editable) continue;
250
+ const v = draft[c.key] ?? '';
251
+ if (c.kind === 'bool') row[c.key] = v === 'true';
252
+ else if (isNumericRowKind(c.kind)) row[c.key] = v.trim() === '' ? null : Number(v);
253
+ else if (c.kind === 'date') row[c.key] = v.trim();
254
+ else if (c.kind === 'json') {
255
+ const t = v.trim();
256
+ if (t === '') { row[c.key] = ''; continue; }
257
+ try { row[c.key] = JSON.parse(t); } catch { row[c.key] = t; }
258
+ } else row[c.key] = c.kind === 'text' ? v.trim() : v;
259
+ }
260
+ return row;
261
+ }
262
+
263
+ /** 外部行的签名:作表单字段控件时取 value,否则取 data.rows(paint 用它判断「外部有没有换新的行」) */
264
+ function incomingSig(p: Record<string, unknown>): string {
265
+ const given = fieldRows(p);
266
+ return given !== null ? JSON.stringify(given) : JSON.stringify(recOf(p.data).rows ?? null);
267
+ }
268
+
269
+ /** 作表单字段控件时的行数组(value 给了数组,或带了字段名);否则 null(行来自 data.rows) */
270
+ function fieldRows(p: Record<string, unknown>): Array<Record<string, unknown>> | null {
271
+ // value 契约缺省为 []:空数组且没带字段名时视为「没给」,行仍取 data.rows
272
+ if (Array.isArray(p.value) && (p.value.length > 0 || str(p.name) !== '')) return rowsOf(p.value);
273
+ return str(p.name) !== '' ? [] : null;
274
+ }
275
+
276
+ // ── 行内多行编辑(edit_mode: inline):行 <-> 草稿字符串、单格取值、整表校验 ──
277
+
278
+ /** 行 -> 录入草稿字符串(校验复用 validateRowDraft):bool 取 true / false,对象值转 JSON 文本,空值回空串 */
279
+ export function rowToDraft(columns: readonly KitRowColumn[], row: Readonly<Record<string, unknown>>): Record<string, string> {
280
+ const out: Record<string, string> = {};
281
+ for (const c of columns) {
282
+ const v = row[c.key];
283
+ if (c.kind === 'bool') out[c.key] = v === true || v === 'true' ? 'true' : 'false';
284
+ else if (v === undefined || v === null) out[c.key] = '';
285
+ else if (typeof v === 'object') { try { out[c.key] = JSON.stringify(v); } catch { out[c.key] = ''; } }
286
+ else out[c.key] = String(v);
287
+ }
288
+ return out;
289
+ }
290
+
291
+ /** 单格控件的文本 -> 行里的值:bool 转布尔;数值列空为 null、能转数字就转(转不了保留原文让校验报错);json 能解析就解析 */
292
+ export function inlineCellValue(col: KitRowColumn, text: string): unknown {
293
+ if (col.kind === 'bool') return text === 'true';
294
+ if (isNumericRowKind(col.kind)) {
295
+ if (text.trim() === '') return null;
296
+ const n = Number(text);
297
+ return Number.isFinite(n) ? n : text;
298
+ }
299
+ if (col.kind === 'json') {
300
+ const t = text.trim();
301
+ if (t === '') return '';
302
+ try { return JSON.parse(t); } catch { return t; }
303
+ }
304
+ return text;
305
+ }
306
+
307
+ /**
308
+ * 整张子表的提交前校验(纯函数):行数上下限,再逐行逐列沿用录入校验(required / pattern / 数值范围),
309
+ * 错误带「第 N 行:」前缀。通过返回 null。
310
+ */
311
+ export function validateInlineRows(
312
+ columns: readonly KitRowColumn[],
313
+ rows: ReadonlyArray<Record<string, unknown>>,
314
+ opts: { minRows?: number; maxRows?: number; requiredText?: string; lockedKey?: string } = {},
315
+ at?: Element | string | null,
316
+ ): string | null {
317
+ const minRows = Math.max(0, Math.floor(opts.minRows ?? 0));
318
+ const maxRows = Math.max(0, Math.floor(opts.maxRows ?? 0));
319
+ if (minRows > 0 && rows.length < minRows) return kitText('soma.kit.rows_min', { n: minRows }, at);
320
+ if (maxRows > 0 && rows.length > maxRows) return kitText('soma.kit.rows_max', { n: maxRows }, at);
321
+ const requiredText = opts.requiredText ?? kitText('soma.kit.row_required', undefined, at);
322
+ for (let i = 0; i < rows.length; i += 1) {
323
+ if (opts.lockedKey !== undefined && opts.lockedKey !== '' && rows[i]![opts.lockedKey] === true) continue;
324
+ const message = validateRowDraft(columns, rowToDraft(columns, rows[i]!), requiredText, at);
325
+ if (message !== null) return kitText('soma.kit.rows_row_error', { n: i + 1, message }, at);
326
+ }
327
+ return null;
328
+ }
329
+
330
+ // ── 组件 ──
331
+
332
+ interface EditorState {
333
+ columnsSig: string;
334
+ draft: Record<string, string>;
335
+ rows: Array<Record<string, unknown>>;
336
+ rowsSig: string;
337
+ localError: string;
338
+ pendingClear: boolean;
339
+ /** 行内编辑模式的行表签名(结构不变就不重建,输入框焦点与光标不丢) */
340
+ listSig: string;
341
+ /** 行内编辑的单元格控件(自绘下拉 / 日期框):行表重建前统一释放 */
342
+ cellEmbeds: KitEmbedBag;
343
+ nodes: { list: HTMLElement; form: HTMLElement; err: HTMLElement; title: HTMLElement; hint: HTMLElement; count: HTMLElement } | null;
344
+ /** 录入区命令式嵌入的自绘下拉 / 日期框:录入区重建与卸载前统一释放(含已展开的浮层) */
345
+ embeds: KitEmbedBag;
346
+ }
347
+
348
+ export function createRowEditor(): SomaComponentDefinition {
349
+ const states = new WeakMap<HTMLElement, EditorState>();
350
+ const stateOf = (root: HTMLElement): EditorState => {
351
+ let s = states.get(root);
352
+ if (!s) { s = { columnsSig: '', draft: {}, rows: [], rowsSig: '', localError: '', pendingClear: false, listSig: '', cellEmbeds: createKitEmbedBag(), nodes: null, embeds: createKitEmbedBag() }; states.set(root, s); }
353
+ return s;
354
+ };
355
+ const resetDraft = (st: EditorState, cols: readonly KitRowColumn[]): void => {
356
+ for (const c of cols) st.draft[c.key] = c.kind === 'bool' ? (c.dflt === 'true' ? 'true' : 'false') : c.dflt;
357
+ st.columnsSig = '';
358
+ };
359
+
360
+ // ── staged(集合本地草稿)──
361
+ // 状态按根登记在这里,不进 EditorState:基线(服务端最近下发的行)、同步中 / 失败 / 过期提示、对同步结果的订阅。
362
+ interface StageState {
363
+ base: Array<Record<string, unknown>> | null;
364
+ sent: Array<Record<string, unknown>> | null;
365
+ stale: boolean;
366
+ awaiting: boolean;
367
+ syncing: boolean;
368
+ failMsg: string;
369
+ scope: string;
370
+ off: (() => void) | null;
371
+ bar: HTMLElement | null;
372
+ barSig: string;
373
+ lastCount: number;
374
+ }
375
+ const stages = new WeakMap<HTMLElement, StageState>();
376
+ const apis = new WeakMap<HTMLElement, KitApi>();
377
+
378
+ // ── GB5:select 列的远程选项(options.from)──
379
+ // 按根登记已取回的候选;key = from + params + rowsPath。取数中显示『选项加载中…』、失败显示『选项加载失败』,都不假装有选项。
380
+ interface RemoteSlot { state: 'loading' | 'ok' | 'failed'; options: Array<{ value: string; label: string }> }
381
+ const remotes = new WeakMap<HTMLElement, Map<string, RemoteSlot>>();
382
+ /** 把远程选项叠到列声明上(纯叠加;取数在这里发起,回来后整体重绘) */
383
+ const overlayRemote = (root: HTMLElement, cols: KitRowColumn[]): KitRowColumn[] => {
384
+ if (!cols.some((c) => c.optionsFrom !== null)) return cols;
385
+ let slots = remotes.get(root);
386
+ if (slots === undefined) { slots = new Map(); remotes.set(root, slots); }
387
+ const mine = slots;
388
+ return cols.map((c) => {
389
+ const of = c.optionsFrom;
390
+ if (of === null) return c;
391
+ const key = JSON.stringify([of.from, of.params, of.rowsPath, of.valueKey, of.labelKey]);
392
+ let slot = mine.get(key);
393
+ if (slot === undefined) {
394
+ const fresh: RemoteSlot = { state: 'loading', options: [] };
395
+ slot = fresh;
396
+ mine.set(key, fresh);
397
+ const done = (state: 'ok' | 'failed', options: Array<{ value: string; label: string }>): void => {
398
+ if (remotes.get(root) !== mine || mine.get(key) !== fresh) return; // 已卸载或被换掉
399
+ fresh.state = state;
400
+ fresh.options = options;
401
+ const api = apis.get(root);
402
+ if (api) paint(root, api.props());
403
+ };
404
+ fetchRemoteOptionRows(apis.get(root)?.services, of.from, of.params, of.rowsPath)
405
+ .then((rows) => done('ok', rows.map((r) => ({ value: textOf(r[of.valueKey]), label: textOf(r[of.labelKey]) || textOf(r[of.valueKey]) })).filter((o) => o.value !== '')))
406
+ .catch(() => done('failed', []));
407
+ }
408
+ return {
409
+ ...c,
410
+ options: slot.options,
411
+ placeholder: slot.state === 'loading' ? kitText('soma.kit.rows_options_loading', undefined, root)
412
+ : slot.state === 'failed' ? kitText('soma.kit.rows_options_failed', undefined, root) : c.placeholder,
413
+ };
414
+ });
415
+ };
416
+ const stageOf = (root: HTMLElement): StageState => {
417
+ let s = stages.get(root);
418
+ if (!s) { s = { base: null, sent: null, stale: false, awaiting: false, syncing: false, failMsg: '', scope: '', off: null, bar: null, barSig: '', lastCount: 0 }; stages.set(root, s); }
419
+ return s;
420
+ };
421
+ const cloneRows = (rows: ReadonlyArray<Record<string, unknown>>): Array<Record<string, unknown>> => rows.map((r) => ({ ...r }));
422
+ const stageKeyOf = (root: HTMLElement, p: Record<string, unknown>): string => (str(p.row_key) !== '' ? str(p.row_key) : (rowColumnsOf(p.columns, root)[0]?.key ?? ''));
423
+
424
+ /** 订阅同步结果(范围名变了才重订):只响应本组件发出的那一次同步(awaiting),不被别处旧结果误清 */
425
+ function bindStageOutcome(root: HTMLElement, p: Record<string, unknown>): void {
426
+ const stg = stageOf(root);
427
+ const scope = str(p.scope);
428
+ if (scope === stg.scope && (stg.off !== null || scope === '')) return;
429
+ stg.off?.();
430
+ stg.off = null;
431
+ stg.scope = scope;
432
+ if (scope === '') return;
433
+ const data = apis.get(root)?.services as { data?: SomaDataPort } | undefined;
434
+ stg.off = watchKitOutcome(data?.data, scope, (o) => {
435
+ if (!stg.awaiting) return;
436
+ const st = stateOf(root);
437
+ if (o.status === 'pending') stg.syncing = true;
438
+ else if (o.status === 'saved') {
439
+ stg.awaiting = false; stg.syncing = false; stg.failMsg = ''; stg.stale = false;
440
+ stg.base = cloneRows(stg.sent ?? st.rows);
441
+ stg.sent = null;
442
+ } else if (o.status === 'failed' || o.status === 'conflict' || o.status === 'held') {
443
+ stg.awaiting = false; stg.syncing = false;
444
+ stg.failMsg = o.status === 'conflict' ? kitText('soma.kit.form_conflict', undefined, root) : o.message;
445
+ stg.sent = null;
446
+ } else return;
447
+ const api = apis.get(root);
448
+ if (api) refreshStage(root, api.props());
449
+ });
450
+ }
451
+
452
+ /** 未同步条与行小标:差异为 0 且无失败提示时整条隐藏;有差异就常驻,写清「改动只在本页,尚未保存」 */
453
+ function refreshStage(root: HTMLElement, p: Record<string, unknown>): void {
454
+ const st = stateOf(root);
455
+ const stg = stageOf(root);
456
+ const nodes = st.nodes;
457
+ if (!bool(p.staged) || !nodes) {
458
+ if (stg.bar) stg.bar.hidden = true;
459
+ return;
460
+ }
461
+ const key = stageKeyOf(root, p);
462
+ const diff = stagedDiff(stg.base ?? st.rows, st.rows, key);
463
+ if (!stg.bar) {
464
+ stg.bar = mk('div', '');
465
+ stg.bar.setAttribute('role', 'status');
466
+ stg.bar.setAttribute('aria-live', 'polite');
467
+ stg.bar.setAttribute('data-kit-stage', '');
468
+ root.insertBefore(stg.bar, nodes.list);
469
+ }
470
+ const keys = stagedHeadKeys(diff);
471
+ const sig = JSON.stringify([diff.count, diff.added.length, diff.changed.length, diff.removed.length, keys, stg.syncing, stg.failMsg, stg.stale]);
472
+ stg.bar.hidden = diff.count === 0;
473
+ if (sig !== stg.barSig) {
474
+ stg.barSig = sig;
475
+ stg.bar.textContent = '';
476
+ if (diff.count > 0) {
477
+ const inner = mk('div', STAGE_BAR_CLASS);
478
+ const more = diff.count > keys.length ? '…' : '';
479
+ inner.appendChild(mk('span', '', `${kitText('soma.kit.stage_unsynced', { n: diff.count, added: diff.added.length, changed: diff.changed.length, removed: diff.removed.length }, root)}${keys.length > 0 ? `(${keys.join(kitText('soma.kit.list_sep', undefined, root))}${more})` : ''}`));
480
+ const btns = mk('div', STAGE_BTNS_CLASS);
481
+ btns.appendChild(actionButton({ key: 'stage_discard', label: kitText('soma.kit.stage_discard', undefined, root), tone: 'neutral', disabled: stg.syncing, reason: '' }));
482
+ btns.appendChild(actionButton({ key: 'stage_sync', label: kitText(stg.syncing ? 'soma.kit.stage_syncing' : 'soma.kit.stage_sync', undefined, root), tone: 'primary', disabled: stg.syncing, reason: '' }));
483
+ inner.appendChild(btns);
484
+ if (stg.failMsg !== '') inner.appendChild(mk('p', STAGE_NOTE_CLASS, kitText('soma.kit.stage_failed', { message: stg.failMsg }, root)));
485
+ if (stg.stale) inner.appendChild(mk('p', STAGE_NOTE_CLASS, kitText('soma.kit.stage_stale', undefined, root)));
486
+ stg.bar.appendChild(inner);
487
+ }
488
+ }
489
+ // 行小标:工作副本第 i 行 <-> 行表第 i 个 [data-kit-row](表头与合计行没有该属性)
490
+ const marks = stagedMarks(stg.base ?? st.rows, st.rows, key);
491
+ nodes.list.querySelectorAll<HTMLElement>('[data-kit-row]').forEach((tr, i) => {
492
+ tr.querySelector('[data-kit-stage-mark]')?.remove();
493
+ const m = marks[i];
494
+ const host = tr.firstElementChild;
495
+ if (!m || !host) return;
496
+ const tag = mk('span', STAGE_MARK_CLASS, kitText(m === 'new' ? 'soma.kit.stage_new' : 'soma.kit.stage_edited', undefined, root));
497
+ tag.setAttribute('data-kit-stage-mark', m);
498
+ host.appendChild(tag);
499
+ });
500
+ if (diff.count !== stg.lastCount) {
501
+ stg.lastCount = diff.count;
502
+ apis.get(root)?.emit('stage_change', { count: diff.count, added: diff.added.length, changed: diff.changed.length, removed: diff.removed.length });
503
+ }
504
+ }
505
+
506
+ /** 点「同步」:先做行表校验,通过才抛 submit(走 core 写通道);结果由 bindStageOutcome 接回,成功前一直标「未同步」 */
507
+ function stageSync(root: HTMLElement, p: Record<string, unknown>): void {
508
+ const st = stateOf(root);
509
+ const stg = stageOf(root);
510
+ if (stg.awaiting || stg.syncing) return;
511
+ const cols = rowColumnsOf(p.columns, root);
512
+ const message = validateInlineRows(cols, st.rows, { minRows: num(p.min_rows) ?? 0, maxRows: num(p.max_rows) ?? 0, lockedKey: str(p.locked_key) }, root);
513
+ if (message !== null) {
514
+ st.localError = message;
515
+ showError(root, st, textOf(recOf(p.data).error));
516
+ apis.get(root)?.emit('invalid', { message });
517
+ return;
518
+ }
519
+ st.localError = '';
520
+ showError(root, st, textOf(recOf(p.data).error));
521
+ stg.awaiting = true;
522
+ stg.failMsg = '';
523
+ stg.sent = cloneRows(st.rows);
524
+ const model = stagedModel(st.rows, str(p.value_key, 'rows'));
525
+ apis.get(root)?.emit('submit', { values: model, object: str(p.object), model, mode: 'update', scope: str(p.scope) });
526
+ refreshStage(root, p);
527
+ }
528
+
529
+ /** 点「放弃变更」:自绘确认后恢复基线(服务端数据),不弹原生对话框 */
530
+ async function stageDiscard(root: HTMLElement, p: Record<string, unknown>): Promise<void> {
531
+ const st = stateOf(root);
532
+ const stg = stageOf(root);
533
+ if (stg.syncing || stg.base === null) return;
534
+ const n = stagedDiff(stg.base, st.rows, stageKeyOf(root, p)).count;
535
+ if (n === 0) return;
536
+ const ok = await askKitConfirm({ message: kitText('soma.kit.stage_discard_confirm', { n }, root), tone: 'danger', at: root });
537
+ if (!ok || !stages.has(root)) return;
538
+ st.rows = cloneRows(stg.base);
539
+ st.listSig = '';
540
+ st.localError = '';
541
+ stg.failMsg = '';
542
+ stg.stale = false;
543
+ const api = apis.get(root);
544
+ paint(root, api ? api.props() : p);
545
+ api?.emit('discard', { count: n });
546
+ }
547
+
548
+ return {
549
+ contract: {
550
+ name: 'RowEditor',
551
+ layer: 'data',
552
+ props: {
553
+ data: { type: 'object', default: {}, desc: '{ title?, hint?, rows[], error? }' },
554
+ value: { type: 'array', default: [], desc: '行数组(作表单字段控件时由表单给出,优先于 data.rows);change { value } 抛出完整行数组' },
555
+ id: { type: 'string', default: '', desc: '根节点 id(表单用它定位出错字段)' },
556
+ name: { type: 'string', default: '', desc: '字段名(表单字段控件用)' },
557
+ disabled: { type: 'boolean', default: false, desc: '禁用:同只读(无录入区、删除钮与单格编辑)' },
558
+ edit_mode: { type: 'enum', values: ['append', 'inline'], default: 'append', desc: 'append(缺省)= 下方录入区逐条添加;inline = 行内多行编辑,每行每格就地可改,每次改动抛 change(作表单字段时值随表单提交)' },
559
+ locked_key: { type: 'string', default: '', desc: '行级只读:该字段为真的行,所有列显示为纯文字、不可改(如敏感字段不允许勾选);提交校验也跳过这些行。只在 edit_mode: inline 生效' },
560
+ fixed_rows: { type: 'boolean', default: false, desc: '行由数据给定,不可增删(无添加钮与删除钮),只改 editable 的列;常用于「字段策略」这类逐行勾选' },
561
+ columns: { type: 'array', default: [], desc: '列 [{ key, label, kind?: text|select|bool|json|number|money|date, min?, max?, decimals?, currency?, sum?(number/money 参与合计,缺省真), options?, placeholder?, required?, pattern?, pattern_message?, mono?, span?, default?, true_label?, false_label?, required_message?, editable?(假=只读展示列), list?(假=只在录入区) }]' },
562
+ row_key: { type: 'string', default: '', desc: '主键列(同主键视为替换),缺省第一列' },
563
+ readonly: { type: 'boolean', default: false, desc: '只读:无录入区与删除钮' },
564
+ ...KIT_BUSY_PROP_DEFS,
565
+ auto_apply: { type: 'boolean', default: true, desc: '添加 / 删除后组件先改自己的行副本并抛 change;假则只抛 add / remove,由页面改 data.rows' },
566
+ staged: { type: 'boolean', default: false, desc: '本地草稿:增删改先在本页累积(隐含 auto_apply),顶部常驻「未同步 N 项」条,可「同步」(抛 submit,经 core 写通道 data.submit 提交整张行表)或「放弃变更」(确认后恢复服务端数据);同步成功才算保存,不是乐观更新' },
567
+ value_key: { type: 'string', default: 'rows', desc: 'staged 同步时 submit 的 model 里放行表的键(须是写对象 schema 里的字段)' },
568
+ object: { type: 'string', default: '', desc: 'staged 同步用的数据对象名(编译器按 view 所在对象补全)' },
569
+ scope: { type: 'string', default: '', desc: 'staged 同步的写入结果范围名(编译器补全);组件据此订阅同步结果' },
570
+ add_label: { type: 'string', default: '', desc: '添加钮文字;缺省取内置文案(按页面语言)' },
571
+ remove_label: { type: 'string', default: '', desc: '删除钮文字;缺省取内置文案(按页面语言)' },
572
+ action_label: { type: 'string', default: '', desc: '行尾操作列表头文字' },
573
+ locale: { type: 'string', default: '', desc: '数值 / 金额格式化语言;空则 zh-CN' },
574
+ required_text: { type: 'string', default: '', desc: '必填缺失时的提示前缀,后接列名;缺省取内置文案(按页面语言)' },
575
+ min_rows: { type: 'number', default: 0, desc: '最少保留行数:达到后删除钮禁用并提示;0 不限' },
576
+ max_rows: { type: 'number', default: 0, desc: '最多行数:达到后新增(非替换)抛 invalid 并提示;0 不限' },
577
+ min_rows_text: { type: 'string', default: '', desc: '到达行数下限的提示,{n} 换成下限;缺省取内置文案(按页面语言)' },
578
+ max_rows_text: { type: 'string', default: '', desc: '到达行数上限的提示,{n} 换成上限;缺省取内置文案(按页面语言)' },
579
+ footer: { type: 'enum', values: ['none', 'sum'], default: 'none', desc: '底部合计行:sum 对 number / money 列(sum 非假)求和,不计算业务字段,仅展示' },
580
+ total_label: { type: 'string', default: '', desc: '合计行的行名,放在第一个非合计列;缺省取内置文案(按页面语言)' },
581
+ empty_text: { type: 'string', default: '', desc: '没有行时的文案;缺省取内置文案(按页面语言)' },
582
+ class: { type: 'string', default: '', desc: '外部传入的类,追加在根节点类串末尾' },
583
+ },
584
+ emits: {
585
+ add: { payload: { row: { type: 'object' }, replaced: { type: 'boolean' } }, desc: '录入校验通过后添加' },
586
+ remove: { payload: { key: { type: 'string' }, row: { type: 'object' }, index: { type: 'number' } }, desc: '删除某行' },
587
+ change: { payload: { value: { type: 'array' }, totals: { type: 'object' } }, desc: 'auto_apply 下 add / remove 后的完整行数组;totals 是各合计列的和(无合计列为空对象)' },
588
+ invalid: { payload: { message: { type: 'string' } }, desc: '声明式校验没过(required / pattern)' },
589
+ submit: { payload: { values: { type: 'object' }, object: { type: 'string' }, model: { type: 'object' }, mode: { type: 'string' }, scope: { type: 'string' } }, desc: 'staged 点「同步」后抛:整张行表在 model[value_key],mode 恒 update;view.on 缺省接 ACTION | data.submit(对象声明了 write 时)' },
590
+ stage_change: { payload: { count: { type: 'number' }, added: { type: 'number' }, changed: { type: 'number' }, removed: { type: 'number' } }, desc: 'staged 未同步项数变化(含 0)' },
591
+ discard: { payload: { count: { type: 'number' } }, desc: 'staged 确认放弃变更后抛,行表已恢复服务端数据' },
592
+ },
593
+ },
594
+ services: ['data', 'http'],
595
+ templateHtml: `<section data-soma-id="root" class="@container ${ROOT_CLASS}"></section>`,
596
+ controllerFactory: createKitController({
597
+ busyAware: true,
598
+ attach(root, api) {
599
+ apis.set(root, api);
600
+ const keyOf = (): string => {
601
+ const p = api.props();
602
+ const cols = rowColumnsOf(p.columns, root);
603
+ return str(p.row_key) !== '' ? str(p.row_key) : (cols[0]?.key ?? '');
604
+ };
605
+ const onInput = (event: Event): void => {
606
+ const el = event.target as HTMLInputElement | null;
607
+ if (!el) return;
608
+ // 行内多行编辑:单格改动写回行副本并抛 change(值没变不抛:文本框的 input 与 change 都会来)
609
+ const cell = el.getAttribute('data-kit-cell');
610
+ if (cell !== null) {
611
+ const p = api.props();
612
+ if (bool(p.readonly) || bool(p.disabled)) return;
613
+ const st = stateOf(root);
614
+ const index = Number(el.getAttribute('data-kit-index'));
615
+ const col = rowColumnsOf(p.columns, root).find((c) => c.key === cell);
616
+ const row = st.rows[index];
617
+ if (!col || !row) return;
618
+ const next = inlineCellValue(col, el.value);
619
+ if (JSON.stringify(row[cell]) === JSON.stringify(next)) return;
620
+ st.rows = st.rows.map((r, i) => (i === index ? { ...r, [cell]: next } : r));
621
+ // st.rowsSig 不动:它记的是「上次收到的外部行」,表单回灌与本地副本一致的值时 paint 不重建
622
+ const allCols = rowColumnsOf(p.columns, root);
623
+ api.emit('change', { value: st.rows, totals: rowTotals(allCols, st.rows) });
624
+ refreshTotals(root, allCols.filter((c) => c.list), st.rows, str(p.locale));
625
+ if (bool(p.staged)) refreshStage(root, p);
626
+ return;
627
+ }
628
+ const k = el.getAttribute('data-kit-field');
629
+ if (k === null || k === undefined) return;
630
+ stateOf(root).draft[k] = el.value;
631
+ };
632
+ const onClick = (event: Event): void => {
633
+ const btn = (event.target as HTMLElement | null)?.closest<HTMLButtonElement>('[data-kit-action]');
634
+ if (!btn || btn.disabled) return;
635
+ const p = api.props();
636
+ const st = stateOf(root);
637
+ const cols = rowColumnsOf(p.columns, root);
638
+ const key = keyOf();
639
+ const act = btn.getAttribute('data-kit-action');
640
+ if (act === 'stage_sync') { stageSync(root, p); return; }
641
+ if (act === 'stage_discard') { void stageDiscard(root, p); return; }
642
+ if (act === 'add_row') {
643
+ // 行内多行编辑的「添加一行」:追加一条缺省行(不校验,必填等在表单提交时统一校验)
644
+ const maxRows = Math.max(0, Math.floor(num(p.max_rows) ?? 0));
645
+ if (maxRows > 0 && st.rows.length >= maxRows) {
646
+ const full = str(p.max_rows_text, kitText('soma.kit.rows_max', undefined, root)).replace('{n}', String(maxRows));
647
+ st.localError = full;
648
+ showError(root, st, str(recOf(p.data).error));
649
+ api.emit('invalid', { message: full });
650
+ return;
651
+ }
652
+ const blank: Record<string, string> = {};
653
+ for (const c of cols) blank[c.key] = c.kind === 'bool' ? (c.dflt === 'true' ? 'true' : 'false') : c.dflt;
654
+ st.rows = [...st.rows, draftToRow(cols, blank)];
655
+ st.localError = '';
656
+ api.emit('change', { value: st.rows, totals: rowTotals(cols, st.rows) });
657
+ paint(root, api.props());
658
+ const last = root.querySelectorAll<HTMLElement>(`[data-kit-index="${st.rows.length - 1}"][data-kit-cell]`);
659
+ (last[0] ?? root.querySelector<HTMLElement>('[data-kit-action="add_row"]'))?.focus();
660
+ return;
661
+ }
662
+ if (act === 'remove') {
663
+ const index = Number(btn.getAttribute('data-kit-index'));
664
+ const row = st.rows[index];
665
+ if (!row) return;
666
+ const minRows = Math.max(0, Math.floor(num(p.min_rows) ?? 0));
667
+ if (minRows > 0 && st.rows.length <= minRows) {
668
+ const msg = str(p.min_rows_text, kitText('soma.kit.rows_min', undefined, root)).replace('{n}', String(minRows));
669
+ st.localError = msg;
670
+ showError(root, st, str(recOf(p.data).error));
671
+ api.emit('invalid', { message: msg });
672
+ return;
673
+ }
674
+ api.emit('remove', { key: textOf(row[key]), row, index });
675
+ if (bool(p.auto_apply) || bool(p.staged) || str(p.edit_mode) === 'inline') {
676
+ st.rows = st.rows.filter((_, i) => i !== index);
677
+ st.rowsSig = incomingSig(p);
678
+ st.localError = '';
679
+ api.emit('change', { value: st.rows, totals: rowTotals(cols, st.rows) });
680
+ paint(root, api.props());
681
+ // 行表重绘后焦点会丢:落到同位置(或最后一行)的删除钮,没有行了就落到录入区第一格
682
+ const removes = root.querySelectorAll<HTMLElement>('[data-kit-action="remove"]');
683
+ (removes[Math.min(index, removes.length - 1)] ?? root.querySelector<HTMLElement>('[data-kit-field]'))?.focus();
684
+ }
685
+ return;
686
+ }
687
+ if (act === 'add') {
688
+ const msg = validateRowDraft(cols, st.draft, str(p.required_text, kitText('soma.kit.row_required', undefined, root)), root);
689
+ if (msg !== null) {
690
+ st.localError = msg;
691
+ showError(root, st, str(recOf(p.data).error));
692
+ api.emit('invalid', { message: msg });
693
+ return;
694
+ }
695
+ st.localError = '';
696
+ const row = draftToRow(cols, st.draft);
697
+ const replaced = key !== '' && st.rows.some((r) => textOf(r[key]) === textOf(row[key]));
698
+ const maxRows = Math.max(0, Math.floor(num(p.max_rows) ?? 0));
699
+ if (maxRows > 0 && !replaced && st.rows.length >= maxRows) {
700
+ const full = str(p.max_rows_text, kitText('soma.kit.rows_max', undefined, root)).replace('{n}', String(maxRows));
701
+ st.localError = full;
702
+ showError(root, st, str(recOf(p.data).error));
703
+ api.emit('invalid', { message: full });
704
+ return;
705
+ }
706
+ api.emit('add', { row, replaced });
707
+ if (bool(p.auto_apply) || bool(p.staged)) {
708
+ st.rows = key === '' ? [...st.rows, row] : [...st.rows.filter((r) => textOf(r[key]) !== textOf(row[key])), row];
709
+ st.rowsSig = incomingSig(p);
710
+ api.emit('change', { value: st.rows, totals: rowTotals(cols, st.rows) });
711
+ resetDraft(st, cols);
712
+ paint(root, api.props());
713
+ } else {
714
+ // 受控:页面接受(改了 data.rows)后才清草稿;页面拒绝(写 data.error)则草稿保留
715
+ st.pendingClear = true;
716
+ }
717
+ }
718
+ };
719
+ // 文本框里按 Enter 等于点「添加」(输入法组合中不算)
720
+ const onKeydown = (event: KeyboardEvent): void => {
721
+ const el = event.target as HTMLElement | null;
722
+ if (event.key !== 'Enter' || event.isComposing || !(el instanceof HTMLInputElement) || !el.hasAttribute('data-kit-field')) return;
723
+ const add = root.querySelector<HTMLButtonElement>('[data-kit-action="add"]');
724
+ if (!add) return;
725
+ event.preventDefault();
726
+ add.click();
727
+ };
728
+ root.addEventListener('input', onInput);
729
+ root.addEventListener('change', onInput);
730
+ root.addEventListener('click', onClick);
731
+ root.addEventListener('keydown', onKeydown);
732
+ return () => {
733
+ root.removeEventListener('input', onInput);
734
+ root.removeEventListener('change', onInput);
735
+ root.removeEventListener('click', onClick);
736
+ root.removeEventListener('keydown', onKeydown);
737
+ states.get(root)?.embeds.release(root);
738
+ states.get(root)?.cellEmbeds.release(root);
739
+ states.delete(root);
740
+ remotes.delete(root);
741
+ stages.get(root)?.off?.();
742
+ stages.delete(root);
743
+ apis.delete(root);
744
+ };
745
+ },
746
+ render(root, p) {
747
+ paint(root, p);
748
+ },
749
+ }),
750
+ };
751
+
752
+ function showError(root: HTMLElement, st: EditorState, external: string): void {
753
+ const text = st.localError !== '' ? st.localError : external;
754
+ const err = st.nodes?.err;
755
+ if (!err) return;
756
+ err.textContent = text;
757
+ err.hidden = text === '';
758
+ }
759
+
760
+ /** 行内编辑:单格控件里的文字(bool 取 true / false,对象值转 JSON,空值回空串) */
761
+ function inlineText(c: KitRowColumn, v: unknown): string {
762
+ if (c.kind === 'bool') return v === true || v === 'true' ? 'true' : 'false';
763
+ if (v === undefined || v === null) return '';
764
+ if (typeof v === 'object') { try { return JSON.stringify(v); } catch { return ''; } }
765
+ return String(v);
766
+ }
767
+
768
+ /** 行内编辑:一个单元格的控件(文本框 / 自绘下拉 / 自绘日期框),带 data-kit-cell 与行号,由根上的 input / change 监听收值 */
769
+ function inlineControl(st: EditorState, c: KitRowColumn, value: unknown, index: number): HTMLElement {
770
+ const text = inlineText(c, value);
771
+ let control: HTMLInputElement;
772
+ let holder: HTMLElement;
773
+ if (c.kind === 'select' || c.kind === 'bool') {
774
+ const opts = c.kind === 'bool' ? [{ value: 'false', label: c.falseLabel }, { value: 'true', label: c.trueLabel }] : c.options;
775
+ const field = st.cellEmbeds.add(mountKitSelectField({ options: opts, value: opts.some((o) => o.value === text) ? text : '', placeholder: c.placeholder, ariaLabel: c.label }));
776
+ field.el.setAttribute('data-kit-select-host', '');
777
+ control = field.input;
778
+ holder = field.el;
779
+ } else if (c.kind === 'date') {
780
+ const field = st.cellEmbeds.add(mountKitDateField({ value: text, placeholder: c.placeholder, fieldClass: DATE_FIELD_CLASS }));
781
+ control = field.input;
782
+ holder = field.el;
783
+ } else {
784
+ const input = mk('input', c.mono || c.kind === 'json' ? `${FIELD_CLASS.md} ${TEXTAREA_LIKE}` : isNumericRowKind(c.kind) ? `${FIELD_CLASS.md} ${NUM_ALIGN}` : FIELD_CLASS.md);
785
+ input.type = 'text';
786
+ if (isNumericRowKind(c.kind)) input.inputMode = 'decimal';
787
+ input.placeholder = c.placeholder;
788
+ input.autocomplete = 'off';
789
+ input.value = text;
790
+ input.setAttribute('aria-label', c.label);
791
+ control = input;
792
+ holder = input;
793
+ }
794
+ control.setAttribute('data-kit-cell', c.key);
795
+ control.setAttribute('data-kit-index', String(index));
796
+ return holder;
797
+ }
798
+
799
+ /** 行内编辑的合计行:随单格改动就地刷新数字(不重建行表,输入焦点不丢) */
800
+ function refreshTotals(root: HTMLElement, cols: readonly KitRowColumn[], rows: ReadonlyArray<Record<string, unknown>>, locale: string): void {
801
+ const totals = rowTotals(cols, rows);
802
+ root.querySelectorAll<HTMLElement>('[data-kit-total]').forEach((el) => {
803
+ const c = cols.find((x) => x.key === el.getAttribute('data-kit-total'));
804
+ const v = c ? totals[c.key] : undefined;
805
+ if (c && v !== undefined) el.textContent = rowCellText(c, v, locale);
806
+ });
807
+ }
808
+
809
+ /** 行内多行编辑的行表:每行每格就地可改;readonly / disabled 时退回纯文字;fixed_rows 时没有添加 / 删除 */
810
+ function paintInlineList(root: HTMLElement, st: EditorState, p: Record<string, unknown>, list: HTMLElement, cols: readonly KitRowColumn[], readonly: boolean, fixedRows: boolean): void {
811
+ st.cellEmbeds.release(list);
812
+ list.textContent = '';
813
+ const shown = cols.filter((c) => c.list);
814
+ const structural = !readonly && !fixedRows;
815
+ const spanOf = (c: KitRowColumn): string => `${SPAN_CLASS[c.span] ?? 'col-span-2'}${isNumericRowKind(c.kind) ? ` ${NUM_ALIGN}` : ''}`;
816
+ if (st.rows.length === 0) {
817
+ list.appendChild(emptyNode(str(p.empty_text, kitText('soma.kit.empty', undefined, root))));
818
+ } else {
819
+ const head = mk('div', HEAD_CLASS);
820
+ for (const c of shown) {
821
+ const cell = mk('span', spanOf(c), c.label);
822
+ if (c.required && c.editable && !readonly) cell.appendChild(mk('span', REQUIRED_MARK, ' *'));
823
+ head.appendChild(cell);
824
+ }
825
+ if (structural) head.appendChild(mk('span', END_CLASS, str(p.action_label)));
826
+ list.appendChild(head);
827
+ st.rows.forEach((row, index) => {
828
+ const tr = mk('div', ROW_CLASS);
829
+ tr.setAttribute('data-kit-row', String(index));
830
+ for (const c of shown) {
831
+ const wrap = mk('span', `${spanOf(c)} min-w-0`);
832
+ if (readonly || !c.editable || (str(p.locked_key) !== '' && row[str(p.locked_key)] === true)) {
833
+ const cls = c.mono || c.kind === 'json' ? CELL_MONO : c.key === shown[0]?.key ? CELL_CLASS : CELL_MUTED;
834
+ wrap.className = `${spanOf(c)} ${cls}`;
835
+ wrap.textContent = rowCellText(c, row[c.key], str(p.locale));
836
+ } else {
837
+ wrap.appendChild(inlineControl(st, c, row[c.key], index));
838
+ }
839
+ tr.appendChild(wrap);
840
+ }
841
+ if (structural) {
842
+ const cell = mk('span', END_CLASS);
843
+ const btn = actionButton({ key: 'remove', label: str(p.remove_label, kitText('soma.kit.delete', undefined, root)), tone: 'danger', disabled: false, reason: '' });
844
+ btn.setAttribute('data-kit-index', String(index));
845
+ cell.appendChild(btn);
846
+ tr.appendChild(cell);
847
+ }
848
+ list.appendChild(tr);
849
+ });
850
+ if (str(p.footer, 'none') === 'sum') {
851
+ const totals = rowTotals(shown, st.rows);
852
+ const labelCol = shown.find((c) => totals[c.key] === undefined);
853
+ const foot = mk('div', FOOTER_ROW_CLASS);
854
+ foot.setAttribute('data-kit-footer', 'sum');
855
+ for (const c of shown) {
856
+ const total = totals[c.key];
857
+ const text = total !== undefined ? rowCellText(c, total, str(p.locale)) : c === labelCol ? str(p.total_label, kitText('soma.kit.total_label', undefined, root)) : '';
858
+ const cell = mk('span', spanOf(c), text);
859
+ if (total !== undefined) cell.setAttribute('data-kit-total', c.key);
860
+ foot.appendChild(cell);
861
+ }
862
+ if (structural) foot.appendChild(mk('span', END_CLASS));
863
+ list.appendChild(foot);
864
+ }
865
+ }
866
+ if (structural) {
867
+ const bar = mk('div', 'flex px-2 py-2');
868
+ bar.appendChild(actionButton({ key: 'add_row', label: str(p.add_label, kitText('soma.kit.rows_add_row', undefined, root)), tone: 'neutral', disabled: false, reason: '' }));
869
+ list.appendChild(bar);
870
+ }
871
+ }
872
+
873
+ function paint(root: HTMLElement, p: Record<string, unknown>): void {
874
+ const st = stateOf(root);
875
+ const data = recOf(p.data);
876
+ const cols = overlayRemote(root, rowColumnsOf(p.columns, root));
877
+ const readonly = bool(p.readonly) || bool(p.disabled);
878
+ const inline = str(p.edit_mode) === 'inline';
879
+ const fixedRows = bool(p.fixed_rows);
880
+ // 作表单字段控件时行来自 value(受表单草稿控制),否则来自 data.rows
881
+ const given = fieldRows(p);
882
+ const rowsSig = incomingSig(p);
883
+ if (rowsSig !== st.rowsSig) {
884
+ st.rowsSig = rowsSig;
885
+ const next = (given ?? rowsOf(data.rows)).map((r) => ({ ...r }));
886
+ const stg = bool(p.staged) ? stageOf(root) : null;
887
+ if (stg !== null && stg.base !== null && !stg.awaiting && stagedDiff(stg.base, st.rows, stageKeyOf(root, p)).count > 0) {
888
+ // 本地有未同步变更:服务端数据换新时不覆盖工作副本(否则会悄悄丢掉用户的编辑),只换基线并提示「已在别处更新」
889
+ stg.base = cloneRows(next);
890
+ stg.stale = true;
891
+ } else if (!(given !== null && JSON.stringify(next) === JSON.stringify(st.rows))) {
892
+ // 表单回灌的正是本地副本刚抛出的行:内容一致就不重建,行内输入框的焦点与光标不丢
893
+ st.rows = next;
894
+ st.listSig = '';
895
+ if (st.pendingClear) { st.pendingClear = false; resetDraft(st, cols); }
896
+ if (stg !== null) { stg.base = cloneRows(next); stg.stale = false; }
897
+ }
898
+ }
899
+ if (bool(p.staged)) {
900
+ const stg0 = stageOf(root);
901
+ if (stg0.base === null) stg0.base = cloneRows(st.rows);
902
+ bindStageOutcome(root, p);
903
+ }
904
+ if (p.id !== undefined && str(p.id) !== '') root.id = str(p.id);
905
+ const shown = cols.filter((c) => c.list);
906
+ root.className = joinClass(`@container ${ROOT_CLASS}`, p.class);
907
+
908
+ if (!st.nodes) {
909
+ root.textContent = '';
910
+ const title = mk('h3', TITLE_CLASS);
911
+ const hint = mk('p', HINT_CLASS);
912
+ const list = mk('div', LIST_WRAP);
913
+ const err = mk('p', ERROR_CLASS);
914
+ err.setAttribute('role', 'alert');
915
+ err.hidden = true;
916
+ const count = mk('p', COUNT_CLASS);
917
+ count.setAttribute('aria-live', 'polite');
918
+ count.hidden = true;
919
+ const form = mk('div', '');
920
+ root.append(title, hint, list, count, err, form);
921
+ st.nodes = { list, form, err, title, hint, count };
922
+ }
923
+ const { list, form, title, hint, count } = st.nodes;
924
+ title.textContent = textOf(data.title);
925
+ title.hidden = textOf(data.title) === '';
926
+ hint.textContent = textOf(data.hint);
927
+ hint.hidden = textOf(data.hint) === '';
928
+
929
+ // 行表
930
+ const key = str(p.row_key) !== '' ? str(p.row_key) : (cols[0]?.key ?? '');
931
+ if (inline) {
932
+ // 行内多行编辑:结构不变(列、行数、锁定态)就不重建,输入框的焦点与光标不丢;合计行随单格改动单独刷新
933
+ const listSig = JSON.stringify([cols, readonly, fixedRows, st.rows.length, str(p.locked_key), str(p.remove_label), str(p.action_label), str(p.footer), str(p.empty_text), str(p.add_label), str(p.locale)]);
934
+ if (listSig !== st.listSig) {
935
+ st.listSig = listSig;
936
+ paintInlineList(root, st, p, list, cols, readonly, fixedRows);
937
+ }
938
+ } else if (st.rows.length === 0) {
939
+ list.textContent = '';
940
+ list.appendChild(emptyNode(str(p.empty_text, kitText('soma.kit.empty', undefined, root))));
941
+ } else {
942
+ list.textContent = '';
943
+ const head = mk('div', HEAD_CLASS);
944
+ const spanOf = (c: KitRowColumn): string => `${SPAN_CLASS[c.span] ?? 'col-span-2'}${isNumericRowKind(c.kind) ? ` ${NUM_ALIGN}` : ''}`;
945
+ for (const c of shown) head.appendChild(mk('span', spanOf(c), c.label));
946
+ if (!readonly && !fixedRows) head.appendChild(mk('span', END_CLASS, str(p.action_label)));
947
+ list.appendChild(head);
948
+ st.rows.forEach((row, index) => {
949
+ const tr = mk('div', ROW_CLASS);
950
+ tr.setAttribute('data-kit-row', textOf(row[key]));
951
+ for (const c of shown) {
952
+ const cls = c.mono || c.kind === 'json' ? CELL_MONO : c.key === shown[0]?.key ? CELL_CLASS : CELL_MUTED;
953
+ tr.appendChild(mk('span', `${spanOf(c)} ${cls}`, rowCellText(c, row[c.key], str(p.locale))));
954
+ }
955
+ if (!readonly && !fixedRows) {
956
+ const cell = mk('span', END_CLASS);
957
+ const btn = actionButton({ key: 'remove', label: str(p.remove_label, kitText('soma.kit.delete', undefined, root)), tone: 'danger', disabled: false, reason: '' });
958
+ btn.setAttribute('data-kit-index', String(index));
959
+ cell.appendChild(btn);
960
+ tr.appendChild(cell);
961
+ }
962
+ list.appendChild(tr);
963
+ });
964
+ if (str(p.footer, 'none') === 'sum') {
965
+ const totals = rowTotals(shown, st.rows);
966
+ const labelCol = shown.find((c) => totals[c.key] === undefined);
967
+ const foot = mk('div', FOOTER_ROW_CLASS);
968
+ foot.setAttribute('data-kit-footer', 'sum');
969
+ for (const c of shown) {
970
+ const total = totals[c.key];
971
+ const text = total !== undefined ? rowCellText(c, total, str(p.locale)) : c === labelCol ? str(p.total_label, kitText('soma.kit.total_label', undefined, root)) : '';
972
+ foot.appendChild(mk('span', spanOf(c), text));
973
+ }
974
+ if (!readonly && !fixedRows) foot.appendChild(mk('span', END_CLASS));
975
+ list.appendChild(foot);
976
+ }
977
+ }
978
+ // 行数提示:设了上下限才出;到限时追加原因
979
+ const minRows = Math.max(0, Math.floor(num(p.min_rows) ?? 0));
980
+ const maxRows = Math.max(0, Math.floor(num(p.max_rows) ?? 0));
981
+ count.hidden = minRows === 0 && maxRows === 0;
982
+ if (minRows > 0 || maxRows > 0) {
983
+ const n = st.rows.length;
984
+ const parts = [maxRows > 0 ? `${n} / ${maxRows}` : String(n)];
985
+ if (maxRows > 0 && n >= maxRows) parts.push(str(p.max_rows_text, kitText('soma.kit.rows_max', undefined, root)).replace('{n}', String(maxRows)));
986
+ else if (minRows > 0 && n <= minRows) parts.push(str(p.min_rows_text, kitText('soma.kit.rows_min', undefined, root)).replace('{n}', String(minRows)));
987
+ count.textContent = parts.join(' ');
988
+ }
989
+
990
+ // 录入区:列声明变化才重建(保住草稿与焦点)
991
+ const noEntry = readonly || inline || fixedRows;
992
+ const colsSig = JSON.stringify([cols, noEntry, str(p.add_label)]);
993
+ if (colsSig !== st.columnsSig) {
994
+ st.columnsSig = colsSig;
995
+ st.embeds.release(form);
996
+ form.textContent = '';
997
+ const editable = cols.filter((c) => c.editable);
998
+ form.hidden = noEntry || editable.length === 0;
999
+ if (!noEntry) {
1000
+ const grid = mk('div', `${FORM_CLASS} ${FORM_COLS[Math.min(editable.length + 1, 6)] ?? FORM_COLS[3]}`);
1001
+ form.appendChild(grid);
1002
+ for (const c of editable) {
1003
+ if (st.draft[c.key] === undefined) st.draft[c.key] = c.kind === 'bool' ? (c.dflt === 'true' ? 'true' : 'false') : c.dflt;
1004
+ const wrap = mk('label', FIELD_WRAP);
1005
+ const lab = mk('span', LABEL_CLASS, c.label);
1006
+ if (c.required) lab.appendChild(mk('span', REQUIRED_MARK, ' *'));
1007
+ wrap.appendChild(lab);
1008
+ let control: HTMLInputElement;
1009
+ let holder: HTMLElement | null = null;
1010
+ if (c.kind === 'select' || c.kind === 'bool') {
1011
+ // 自绘下拉(没有原生 <select>):control 是它的 hidden 载体(带 data-kit-field,value 即选中项),holder 是外壳
1012
+ const opts = c.kind === 'bool'
1013
+ ? [{ value: 'false', label: c.falseLabel }, { value: 'true', label: c.trueLabel }]
1014
+ : c.options;
1015
+ // 草稿值不在选项里时落到第一项(和原来原生下拉的表现一致)
1016
+ if (!opts.some((o) => o.value === (st.draft[c.key] ?? '')) && opts[0]) st.draft[c.key] = opts[0].value;
1017
+ const field = st.embeds.add(mountKitSelectField({ options: opts, value: st.draft[c.key] ?? '', placeholder: c.placeholder, ariaLabel: c.label }));
1018
+ field.el.setAttribute('data-kit-select-host', '');
1019
+ control = field.input;
1020
+ holder = field.el;
1021
+ } else if (c.kind === 'date') {
1022
+ // 日期列:自绘日历框,控件是它的文本框(value 即日期文本)
1023
+ const field = st.embeds.add(mountKitDateField({ value: st.draft[c.key] ?? '', placeholder: c.placeholder, fieldClass: DATE_FIELD_CLASS }));
1024
+ control = field.input;
1025
+ holder = field.el;
1026
+ } else {
1027
+ const input = mk('input', c.mono || c.kind === 'json' ? `${FIELD_CLASS.md} ${TEXTAREA_LIKE}` : isNumericRowKind(c.kind) ? `${FIELD_CLASS.md} ${NUM_ALIGN}` : FIELD_CLASS.md);
1028
+ input.type = 'text';
1029
+ if (isNumericRowKind(c.kind)) input.inputMode = 'decimal';
1030
+ input.placeholder = c.placeholder;
1031
+ input.autocomplete = 'off';
1032
+ input.value = st.draft[c.key] ?? '';
1033
+ control = input;
1034
+ }
1035
+ control.setAttribute('data-kit-field', c.key);
1036
+ wrap.appendChild(holder ?? control);
1037
+ grid.appendChild(wrap);
1038
+ }
1039
+ const last = mk('div', `${FIELD_WRAP} self-end`);
1040
+ last.appendChild(actionButton({ key: 'add', label: str(p.add_label, kitText('soma.kit.add', undefined, root)), tone: 'neutral', disabled: false, reason: '' }));
1041
+ grid.appendChild(last);
1042
+ }
1043
+ } else {
1044
+ form.hidden = noEntry || !cols.some((c) => c.editable);
1045
+ }
1046
+ showError(root, st, textOf(data.error));
1047
+ refreshStage(root, p);
1048
+ // 忙闲通道:所接动作(add / remove / change)在进行中时添加、删除钮禁用并挂 aria-busy,结束后恢复(只还原自己置的禁用)
1049
+ const busy = kitBusyOf(p);
1050
+ root.querySelectorAll<HTMLButtonElement>('[data-kit-action]').forEach((b) => {
1051
+ if (busy) {
1052
+ b.disabled = true;
1053
+ b.setAttribute('aria-busy', 'true');
1054
+ b.setAttribute('data-kit-busy', '');
1055
+ } else if (b.hasAttribute('data-kit-busy')) {
1056
+ b.disabled = false;
1057
+ b.removeAttribute('aria-busy');
1058
+ b.removeAttribute('data-kit-busy');
1059
+ }
1060
+ });
1061
+ // 行数到下限:删除钮禁用(忙闲还原之后再压一次,保证两个来源都不被对方冲掉)
1062
+ if (minRows > 0 && st.rows.length <= minRows) {
1063
+ root.querySelectorAll<HTMLButtonElement>('[data-kit-action="remove"]').forEach((b) => { b.disabled = true; });
1064
+ }
1065
+ }
1066
+ }