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,1072 @@
1
+ // KitTableTools:表格的工具与接线件(M 波 G2,写死小组件,紧挨在表格外壳之前,自己不画表格)。
2
+ //
3
+ // 它管六件事,都落在紧随其后的表格外壳(data-kit-table)上:
4
+ // 1) 工具栏:刷新 / 行高(紧凑·标准·宽松)/ 列设置(显隐,固定列锁定)/ 导出 CSV;
5
+ // 2) 批量条:勾选后工具栏位置换成「已选 N 项 · 清除 [批量动作…]」,带 {n} 的确认就地问,通过才抛 batch_action;
6
+ // 3) 列显隐:给 data-kit-col 的格整格换成 hidden 类(原类存 data-kit-cls),MutationObserver 跟随新渲染的行;
7
+ // 4) 滚动边缘:外壳标 data-kit-edge-l / -r,固定列的分隔线 + 阴影由类串里的 group-data-* 变体决定;
8
+ // 5) 省略列:补 title(全文);
9
+ // 6) 就地编辑:双击 / Enter / F2 把可编辑格换成输入控件,Enter 保存、Esc 取消;保存抛 cell_edit,页面接 ACTION | data.submit。
10
+ // 组件不改数据:写入只抛事件;勾选只抛 select_change(载荷 rows 批量,协调组件维护已选)。
11
+ // 记忆(列显隐、行高):localStorage,键含页面路径与对象名,读写全包 try/catch。
12
+
13
+ import type { SomaComponentDefinition, SomaDataPort } from 'soma-core';
14
+ import { CLASS_PROP, createKitController, num, str } from '../base/shared';
15
+ import { KIT_DROPDOWN_CLASS_CANDIDATES, onOutsidePress, overlayVerdict, releaseDropdownsIn, syncDropdown } from '../base/popup';
16
+ import { permissionCheckerOf } from '../base/permission-gate';
17
+ import { KIT_CHECK_CLASS_CANDIDATES, attachMarkEvents, createCheck, paintCheck } from '../base/check-core';
18
+ import { attachSpin } from '../base/qty-stepper';
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 KitEmbedHandle } from '../data/embed';
22
+ import { KIT_TABLE_ACTIONS_CLASS_CANDIDATES, ACTION_BUTTON_CLASS } from './table-actions';
23
+ import { KIT_TABLE_EXT } from './defaults';
24
+ import { attachResizeHandle, type ResizeHandle } from '../frames/resize-handle';
25
+ import { kitText, type KitTextKey } from '../i18n/kit-text';
26
+
27
+ // ---------------------------------------------------------------- 类(整串字面量)
28
+
29
+ const ROOT_CLASS = 'flex flex-wrap items-center justify-between gap-2 pb-2';
30
+ const GROUP_CLASS = 'flex flex-wrap items-center gap-2';
31
+ const TOOL_BTN_CLASS = 'inline-flex h-8 items-center justify-center rounded-md border border-border bg-surface px-3 text-sm font-medium text-fg transition-colors hover:bg-surface-sunken focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
32
+ const SEG_GROUP_CLASS = 'inline-flex items-center rounded-md border border-border bg-surface p-0.5';
33
+ const SEG_BTN_CLASS = 'inline-flex h-7 items-center justify-center rounded-md px-2 text-xs font-medium text-fg-muted transition-colors hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
34
+ const SEG_BTN_ON_CLASS = 'inline-flex h-7 items-center justify-center rounded-md bg-primary-soft px-2 text-xs font-medium text-primary-on-soft transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
35
+ const BATCH_BAR_CLASS = 'flex w-full flex-wrap items-center gap-2 rounded-lg bg-primary-soft px-3 py-1.5 text-sm text-primary-on-soft';
36
+ const BATCH_TEXT_CLASS = 'font-medium';
37
+ const LINK_BTN_CLASS = 'inline-flex h-8 items-center rounded-md px-2 text-sm font-medium text-primary-on-soft underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
38
+ const CHECK_TEXT_CLASS = 'text-sm text-fg';
39
+ const PANEL_CHECK_CLASS = 'w-full px-2 py-1 text-sm text-fg hover:bg-surface-sunken';
40
+ const PANEL_CHECK_LOCKED_CLASS = 'w-full px-2 py-1 text-sm';
41
+ const ANCHOR_CLASS = 'relative inline-flex';
42
+ const PANEL_BASE = 'absolute z-20 w-56 rounded-lg border border-border-subtle bg-surface-raised p-2 text-sm text-fg shadow-lg';
43
+ const PANEL_ITEM_CLASS = 'flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 hover:bg-surface-sunken';
44
+ const PANEL_ITEM_LOCKED_CLASS = 'flex cursor-not-allowed items-center gap-2 rounded-md px-2 py-1 text-fg-subtle';
45
+ const PANEL_FOOT_CLASS = 'mt-1 flex justify-end border-t border-border-subtle pt-1';
46
+ const NOTICE_CLASS = 'text-xs text-fg-muted';
47
+ const NOTICE_ERR_CLASS = 'text-xs text-danger-on-soft';
48
+ const EDIT_CELL_CLASS = 'cursor-text focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring';
49
+ const EDIT_INPUT_CLASS = 'block h-8 w-full min-w-0 appearance-none autofill-clear rounded-md border border-primary bg-surface px-2 text-sm text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
50
+ const EDIT_SELECT_CLASS = 'min-w-0';
51
+ const EDIT_DATE_CLASS ='block h-8 w-full min-w-0 rounded-md border border-primary bg-surface ps-2 pe-8 text-sm text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
52
+ const EDIT_ERR_CLASS = 'block text-xs text-danger-on-soft';
53
+ const HIDDEN_CLASS = 'hidden';
54
+ const SR_ONLY_CLASS = 'sr-only';
55
+
56
+ /** 列宽拖拽(Q 波 G4)运行期换上的类:10 档预置宽 `w-N`(N 取 scroll.minSteps)+ 叶子表头格 / 手柄类;拖到的档位类必须全在候选里,否则按页裁剪后缺类 */
57
+ export const KIT_TABLE_RESIZE_CLASS_CANDIDATES: readonly string[] = [
58
+ ...KIT_TABLE_EXT.scroll.minSteps.map((n) => `w-${n}`),
59
+ KIT_TABLE_EXT.resize.cell, KIT_TABLE_EXT.resize.handle,
60
+ ].flatMap((s) => s.split(/\s+/).filter((c) => c !== ''));
61
+
62
+ export const KIT_TABLE_TOOLS_CLASS_CANDIDATES: readonly string[] = [
63
+ ...KIT_TABLE_RESIZE_CLASS_CANDIDATES,
64
+ SR_ONLY_CLASS,
65
+ ROOT_CLASS, GROUP_CLASS, TOOL_BTN_CLASS, SEG_GROUP_CLASS, SEG_BTN_CLASS, SEG_BTN_ON_CLASS, BATCH_BAR_CLASS, BATCH_TEXT_CLASS, LINK_BTN_CLASS,
66
+ CHECK_TEXT_CLASS, PANEL_CHECK_CLASS, PANEL_CHECK_LOCKED_CLASS, ...KIT_CHECK_CLASS_CANDIDATES, ANCHOR_CLASS, PANEL_BASE, PANEL_ITEM_CLASS, PANEL_ITEM_LOCKED_CLASS, PANEL_FOOT_CLASS, NOTICE_CLASS, NOTICE_ERR_CLASS,
67
+ EDIT_CELL_CLASS, EDIT_INPUT_CLASS, EDIT_DATE_CLASS, EDIT_SELECT_CLASS, EDIT_ERR_CLASS, HIDDEN_CLASS,
68
+ ...KIT_DATE_CLASS_CANDIDATES, ...KIT_LISTBOX_CLASS_CANDIDATES,
69
+ ...Object.values(ACTION_BUTTON_CLASS), ...KIT_TABLE_ACTIONS_CLASS_CANDIDATES, ...KIT_DROPDOWN_CLASS_CANDIDATES,
70
+ ].flatMap((s) => s.split(/\s+/).filter((c) => c !== ''));
71
+
72
+ // ---------------------------------------------------------------- 纯函数
73
+
74
+ type Rec = Record<string, unknown>;
75
+ const isRec = (v: unknown): v is Rec => v !== null && typeof v === 'object' && !Array.isArray(v);
76
+
77
+ export interface ToolsColumn {
78
+ field: string;
79
+ label: string;
80
+ fixed: '' | 'left' | 'right';
81
+ editable: boolean;
82
+ kind: '' | 'text' | 'number' | 'select' | 'date';
83
+ options: Array<{ value: string | number | boolean; label: string }>;
84
+ format: string;
85
+ /** 所属列组标题(导出表头写「组标题 / 列名」);无组 = '' */
86
+ group: string;
87
+ /** 可拖宽 + 声明档(scroll.minSteps 里的值) */
88
+ resizable: boolean;
89
+ step: number;
90
+ }
91
+
92
+ /** 把类串里的列宽类(`w-N`,N 取 minSteps)换成 `w-<step>`(第一处原位替换,没有就追加);纯函数 */
93
+ export function withWidthStep(cls: string, steps: readonly number[], step: number): string {
94
+ const drop = new Set(steps.map((n) => `w-${n}`));
95
+ const target = `w-${step}`;
96
+ const out: string[] = [];
97
+ let placed = false;
98
+ for (const t of cls.split(/\s+/).filter((x) => x !== '')) {
99
+ if (drop.has(t)) {
100
+ if (!placed) out.push(target);
101
+ placed = true;
102
+ } else out.push(t);
103
+ }
104
+ if (!placed) out.push(target);
105
+ return out.join(' ');
106
+ }
107
+
108
+ /** 拖到的像素宽换算成最近的档位下标:unit = 每个间距刻度的像素(由拖前实测宽 / 当时的档位得出,不手抄像素);算不出返回 null */
109
+ export function nearestStepIndex(steps: readonly number[], wantUnits: number): number | null {
110
+ if (!Number.isFinite(wantUnits) || steps.length === 0) return null;
111
+ let best = 0;
112
+ steps.forEach((s, i) => {
113
+ if (Math.abs(s - wantUnits) < Math.abs(steps[best]! - wantUnits)) best = i;
114
+ });
115
+ return best;
116
+ }
117
+
118
+ export function columnsOf(raw: unknown): ToolsColumn[] {
119
+ if (!Array.isArray(raw)) return [];
120
+ const out: ToolsColumn[] = [];
121
+ for (const item of raw) {
122
+ if (!isRec(item) || str(item.field) === '') continue;
123
+ const kind = item.kind === 'text' || item.kind === 'number' || item.kind === 'select' || item.kind === 'date' ? item.kind : '';
124
+ const options = Array.isArray(item.options)
125
+ ? item.options.filter(isRec).map((o) => ({ value: o.value as string | number | boolean, label: str(o.label, str(o.value)) }))
126
+ : [];
127
+ out.push({
128
+ field: str(item.field), label: str(item.label, str(item.field)),
129
+ fixed: item.fixed === 'left' || item.fixed === 'right' ? item.fixed : '',
130
+ editable: item.editable === true, kind, options, format: str(item.format),
131
+ group: str(item.group), resizable: item.resizable === true, step: typeof item.step === 'number' ? item.step : 0,
132
+ });
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /** 行主键串(无主键字段时按整行内容) */
138
+ export function rowKeyOf(row: unknown, keyField: string): string {
139
+ if (!isRec(row)) return '';
140
+ const v = keyField !== '' ? row[keyField] : undefined;
141
+ return v !== undefined && v !== null ? String(v) : JSON.stringify(row);
142
+ }
143
+
144
+ /** CSV 单元格:引号转义;以 = + - @ 开头的字符串前补单引号(防公式注入);数字、布尔原样 */
145
+ export function csvCell(value: unknown): string {
146
+ let text: string;
147
+ if (value === null || value === undefined) text = '';
148
+ else if (typeof value === 'number' || typeof value === 'boolean') text = String(value);
149
+ else if (Array.isArray(value)) text = value.map((v) => String(v)).join(';');
150
+ else if (typeof value === 'object') text = JSON.stringify(value);
151
+ else {
152
+ text = String(value);
153
+ if (text !== '' && KIT_TABLE_EXT.export.formulaGuard.includes(text.charAt(0))) text = `'${text}`;
154
+ }
155
+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
156
+ }
157
+
158
+ /** 导出 CSV 文本:表头 + 行;枚举列导出选项文案;超过 maxRows 截断 */
159
+ export function buildCsv(columns: readonly ToolsColumn[], rows: readonly unknown[]): string {
160
+ const lines: string[] = [columns.map((c) => csvCell(c.group !== undefined && c.group !== '' ? `${c.group} / ${c.label}` : c.label)).join(',')];
161
+ for (const row of rows.slice(0, KIT_TABLE_EXT.export.maxRows)) {
162
+ const rec = isRec(row) ? row : {};
163
+ lines.push(columns.map((c) => {
164
+ const raw = rec[c.field];
165
+ const hit = c.options.find((o) => String(o.value) === String(raw));
166
+ return csvCell(hit !== undefined ? hit.label : raw);
167
+ }).join(','));
168
+ }
169
+ return `${KIT_TABLE_EXT.export.bom ? '' : ''}${lines.join('\r\n')}\r\n`;
170
+ }
171
+
172
+ /** 确认文案里的 {n} 换成个数 */
173
+ export function confirmText(template: string, n: number): string {
174
+ return template.split(KIT_TABLE_EXT.batchConfirmCount).join(String(n));
175
+ }
176
+
177
+ /** 记忆键:kit-table:页面路径:对象名:列设置|密度 */
178
+ export function rememberKey(pathname: string, object: string, what: 'cols' | 'density'): string {
179
+ return `${KIT_TABLE_EXT.remember.keyPrefix}:${pathname}:${object}:${what}`;
180
+ }
181
+
182
+ function readStore(key: string): string | null {
183
+ try {
184
+ return typeof localStorage === 'undefined' ? null : localStorage.getItem(key);
185
+ } catch {
186
+ return null;
187
+ }
188
+ }
189
+ function writeStore(key: string, value: string | null): void {
190
+ try {
191
+ if (typeof localStorage === 'undefined') return;
192
+ if (value === null) localStorage.removeItem(key);
193
+ else localStorage.setItem(key, value);
194
+ } catch {
195
+ // 隐私模式 / 禁用站点数据:当次有效,不落盘
196
+ }
197
+ }
198
+
199
+ export function parseHidden(raw: string | null, known: readonly string[]): Set<string> {
200
+ if (raw === null) return new Set();
201
+ try {
202
+ const v: unknown = JSON.parse(raw);
203
+ const list = isRec(v) && Array.isArray(v.hidden) ? v.hidden : [];
204
+ return new Set(list.filter((x): x is string => typeof x === 'string' && known.includes(x)));
205
+ } catch {
206
+ return new Set();
207
+ }
208
+ }
209
+
210
+ type Density = 'compact' | 'standard' | 'comfortable';
211
+ const DENSITIES: ReadonlyArray<{ id: Density; label: KitTextKey }> = [
212
+ { id: 'compact', label: 'soma.kit.density_compact' }, { id: 'standard', label: 'soma.kit.density_standard' }, { id: 'comfortable', label: 'soma.kit.density_comfortable' },
213
+ ];
214
+
215
+ interface BatchItem { id: string; name: string; tone: 'primary' | 'danger' | 'neutral'; confirm: string; permission: string }
216
+
217
+ function batchOf(raw: unknown): BatchItem[] {
218
+ if (!Array.isArray(raw)) return [];
219
+ return raw.filter(isRec).map((b): BatchItem => ({
220
+ id: str(b.id), name: str(b.name, str(b.id)),
221
+ tone: b.tone === 'primary' || b.tone === 'danger' ? b.tone : 'neutral',
222
+ confirm: str(b.confirm), permission: str(b.permission),
223
+ })).filter((b) => b.id !== '');
224
+ }
225
+
226
+ // ---------------------------------------------------------------- 组件
227
+
228
+ export function createKitTableTools(): SomaComponentDefinition {
229
+ return {
230
+ contract: {
231
+ name: 'KitTableTools',
232
+ layer: 'data',
233
+ props: {
234
+ object: { type: 'string', default: '', desc: '对象名(记忆键、就地编辑载荷用)' },
235
+ scope: { type: 'string', default: '', desc: '区域作用域 id' },
236
+ rows: { type: 'array', default: [], desc: '当前页行数组(page.data.<对象>.result.rows)' },
237
+ total: { type: 'number', default: 0, desc: '总行数(page.data.<对象>.result.total);跨页选择提示用' },
238
+ keyField: { type: 'string', default: '', desc: '行主键字段名' },
239
+ columns: { type: 'array', default: [], desc: '列元信息 [{ field, label, fixed?, editable?, kind?, options?, format? }]' },
240
+ items: { type: 'array', default: [], desc: '工具栏项:reload / density / columns / export' },
241
+ density: { type: 'string', default: 'standard', desc: '表格默认行高档(记忆的行高优先)' },
242
+ scroll: { type: 'boolean', default: false, desc: '表格处于滚动模式(影响滚动边缘标记)' },
243
+ editMode: { type: 'string', default: '', desc: '就地编辑方式:cell / row;空 = 不编辑' },
244
+ selectMode: { type: 'string', default: 'none', desc: '勾选列模式 none / single / multi' },
245
+ selectScope: { type: 'string', default: 'all', desc: '勾选范围:all 跨页保留 / page 翻页丢弃不在本页的勾选' },
246
+ selected: { type: 'array', default: [], desc: '已选行数组(协调组件 focus 切片 sel 的镜像);配 batch 才有' },
247
+ batch: { type: 'array', default: [], desc: '批量动作 [{ id, name, tone, confirm, permission? }];confirm 里 {n} 换成已选个数' },
248
+ class: CLASS_PROP,
249
+ },
250
+ emits: {
251
+ reload: { payload: {}, desc: '点工具栏「刷新」' },
252
+ select_change: {
253
+ payload: {
254
+ rows: { type: 'array', desc: '被改变勾选的行(批量)' },
255
+ checked: { type: 'boolean', desc: '勾选后的状态' },
256
+ mode: { type: 'string', desc: 'multi' },
257
+ keyField: { type: 'string', desc: '行主键字段名' },
258
+ },
259
+ desc: '批量条的「全选本页 / 清除」或翻页丢弃:与 row_select 同语义事件(载荷多了 rows)',
260
+ },
261
+ batch_action: {
262
+ payload: {
263
+ kit_action: { type: 'string', desc: '动作判别键' },
264
+ id: { type: 'string', desc: '动作 id' },
265
+ name: { type: 'string', desc: '动作显示名' },
266
+ rows: { type: 'array', desc: '已选行' },
267
+ count: { type: 'number', desc: '作用的行数(all 时为总数)' },
268
+ all: { type: 'boolean', desc: '用户选了「选择全部 N 项」:服务端按当前筛选条件处理' },
269
+ },
270
+ desc: '点批量动作(有 confirm 时已在批量条里确认过)',
271
+ },
272
+ cell_edit: {
273
+ payload: {
274
+ object: { type: 'string', desc: '对象名' },
275
+ scope: { type: 'string', desc: '写入结果范围(<对象>__cell,与表单互不串)' },
276
+ model: { type: 'object', desc: '主键 + 改动的字段' },
277
+ mode: { type: 'string', desc: 'update' },
278
+ field: { type: 'string', desc: '改动的字段(多个以逗号连接)' },
279
+ row: { type: 'object', desc: '改动前的整行' },
280
+ },
281
+ desc: '就地编辑保存:页面接 ACTION | data.submit',
282
+ },
283
+ },
284
+ },
285
+ services: ['data', 'permission'],
286
+ templateHtml: `<div data-soma-id="root" class="${HIDDEN_CLASS}"></div>`,
287
+ controllerFactory: (ctx) => {
288
+ const check = permissionCheckerOf(ctx);
289
+ const dataPort = (): SomaDataPort | undefined => {
290
+ const port = (ctx.services as { data?: SomaDataPort } | undefined)?.data;
291
+ return port && typeof port === 'object' ? port : undefined;
292
+ };
293
+ // ---- 状态
294
+ let hidden = new Set<string>();
295
+ // 列宽拖拽:字段 -> 档位下标(scroll.minSteps);touched = 有过改动、需要在新渲染的格上重放的列。宽度不持久化
296
+ const widthSteps = new Map<string, number>();
297
+ const touched = new Set<string>();
298
+ const resizeHandles = new Map<HTMLElement, ResizeHandle>();
299
+ let density: Density | null = null;
300
+ let panelOpen = false;
301
+ // 列设置面板挂到浮层端口后不再是工具栏的后代,root 上的委托收不到它的事件:面板挂出后由 attach 里登记的函数直接绑在面板上
302
+ let panelBind: ((panel: HTMLElement) => void) | null = null;
303
+ let confirming: string | null = null;
304
+ let allMode = false;
305
+ let notice: { text: string; error: boolean } | null = null;
306
+ let table: HTMLElement | null = null;
307
+ let rootEl: HTMLElement | null = null;
308
+ let apiRef: { props: () => Rec } | null = null;
309
+ let rebuild: () => void = () => undefined;
310
+ // 常驻播报区(sr-only,role=status):批量条每次重绘都会换新节点,节点内的 aria-live 播不出变化,所以播报走这一个不重建的节点
311
+ let liveEl: HTMLElement | null = null;
312
+ let liveLast = '';
313
+ // 内置文案:按宿主所在页面语言取词(运行期读法)
314
+ const T = (key: KitTextKey, params?: Record<string, string | number>): string => kitText(key, params, ctx.host);
315
+ let selAnnounced = false;
316
+ const announce =(text: string): void => {
317
+ if (!liveEl || text === liveLast) return;
318
+ liveLast = text;
319
+ liveEl.textContent = text;
320
+ };
321
+
322
+ const P =(): Rec => apiRef?.props() ?? {};
323
+ const cols = (): ToolsColumn[] => columnsOf(P().columns);
324
+ const object = (): string => str(P().object);
325
+ const rowsList = (): unknown[] => (Array.isArray(P().rows) ? (P().rows as unknown[]) : []);
326
+ const selectedList = (): unknown[] => (Array.isArray(P().selected) ? (P().selected as unknown[]) : []);
327
+ const keyField = (): string => str(P().keyField);
328
+ const cellScope = (): string => `${object()}__cell`;
329
+ const pathname = (): string => (typeof location === 'undefined' ? '' : location.pathname);
330
+
331
+ const effectiveDensity = (): Density => {
332
+ if (density !== null) return density;
333
+ const d = str(P().density, 'standard');
334
+ return d === 'compact' || d === 'comfortable' ? d : 'standard';
335
+ };
336
+
337
+ // ---- 对表格外壳的作用
338
+ const applyDensity = (): void => {
339
+ if (!table) return;
340
+ const d = effectiveDensity();
341
+ if (d === 'compact') table.setAttribute('data-kit-dense', '');
342
+ else table.removeAttribute('data-kit-dense');
343
+ if (d === 'comfortable') table.setAttribute('data-kit-roomy', '');
344
+ else table.removeAttribute('data-kit-roomy');
345
+ };
346
+
347
+ const applyHidden = (): void => {
348
+ if (!table) return;
349
+ table.querySelectorAll<HTMLElement>('[data-kit-col]').forEach((el) => {
350
+ const hide = hidden.has(el.getAttribute('data-kit-col') ?? '');
351
+ const stored = el.getAttribute('data-kit-cls');
352
+ if (hide && stored === null) {
353
+ el.setAttribute('data-kit-cls', el.className);
354
+ el.className = HIDDEN_CLASS;
355
+ } else if (!hide && stored !== null) {
356
+ el.className = stored;
357
+ el.removeAttribute('data-kit-cls');
358
+ }
359
+ });
360
+ // 多级表头:组内列全隐则整个组块隐,部分隐则自然收窄(固定列不可隐,所以固定组不会被隐)
361
+ table.querySelectorAll<HTMLElement>('[data-kit-group-cols]').forEach((el) => {
362
+ const members = (el.getAttribute('data-kit-group-cols') ?? '').split(',').filter((f) => f !== '');
363
+ const hide = members.length > 0 && members.every((f) => hidden.has(f));
364
+ const stored = el.getAttribute('data-kit-cls');
365
+ if (hide && stored === null) {
366
+ el.setAttribute('data-kit-cls', el.className);
367
+ el.className = HIDDEN_CLASS;
368
+ } else if (!hide && stored !== null) {
369
+ el.className = stored;
370
+ el.removeAttribute('data-kit-cls');
371
+ }
372
+ });
373
+ };
374
+
375
+ // ---- 列宽拖拽:只换预置类 w-N,不写 CSSOM
376
+ const stepList = KIT_TABLE_EXT.scroll.minSteps;
377
+ const declaredIndex = (col: ToolsColumn): number => Math.max(0, stepList.indexOf(col.step));
378
+ const currentIndex = (col: ToolsColumn): number => widthSteps.get(col.field) ?? declaredIndex(col);
379
+ /** 把触过的列的表头格 / 体格 / 合计格的宽度类对齐到当前档位(新渲染的行也靠它补上) */
380
+ const applyWidths = (): void => {
381
+ if (!table || touched.size === 0) return;
382
+ const byField = new Map(cols().map((c) => [c.field, c]));
383
+ table.querySelectorAll<HTMLElement>('[data-kit-col]').forEach((el) => {
384
+ const field = el.getAttribute('data-kit-col') ?? '';
385
+ if (!touched.has(field)) return;
386
+ const col = byField.get(field);
387
+ if (!col) return;
388
+ const step = stepList[currentIndex(col)]!;
389
+ const stored = el.getAttribute('data-kit-cls');
390
+ if (stored !== null) el.setAttribute('data-kit-cls', withWidthStep(stored, stepList, step));
391
+ else {
392
+ const next = withWidthStep(el.className, stepList, step);
393
+ if (next !== el.className) el.className = next;
394
+ }
395
+ });
396
+ for (const f of [...touched]) if (!widthSteps.has(f)) touched.delete(f);
397
+ };
398
+ const resetWidths = (): void => {
399
+ if (widthSteps.size === 0) return;
400
+ widthSteps.clear();
401
+ applyWidths();
402
+ };
403
+ /** 给 data-kit-resizable 的叶子表头格补右缘手柄(表头重画后手柄随之消失,这里再补);复用 attachResizeHandle:档位下标 0..9 */
404
+ const applyHandles = (): void => {
405
+ if (!table) return;
406
+ for (const [host, h] of resizeHandles) {
407
+ if (!host.isConnected) { h.destroy(); resizeHandles.delete(host); }
408
+ }
409
+ const doc = table.ownerDocument;
410
+ const list = cols();
411
+ table.querySelectorAll<HTMLElement>('[data-kit-resizable]').forEach((cell) => {
412
+ const field = cell.getAttribute('data-kit-col') ?? '';
413
+ const col = list.find((c) => c.field === field);
414
+ if (!col || !col.resizable || cell.querySelector(':scope > [data-kit-resize]')) return;
415
+ const handleEl = doc.createElement('span');
416
+ handleEl.className = KIT_TABLE_EXT.resize.handle;
417
+ handleEl.setAttribute('data-kit-resize', field);
418
+ cell.appendChild(handleEl);
419
+ let startX = 0;
420
+ let startWidth = 0;
421
+ let startUnits = 0;
422
+ handleEl.addEventListener('pointerdown', (e) => {
423
+ // 拖动开始:正在就地编辑的格先取消(等同 Esc)
424
+ cancelEdit(false);
425
+ startX = e.clientX;
426
+ startWidth = cell.getBoundingClientRect().width;
427
+ startUnits = stepList[currentIndex(col)]!;
428
+ });
429
+ const handle = attachResizeHandle(handleEl, {
430
+ axis: 'x',
431
+ min: 0,
432
+ max: stepList.length - 1,
433
+ total: stepList.length - 1,
434
+ reset: declaredIndex(col),
435
+ label: T('soma.kit.col_resize', { label: col.label }),
436
+ get: () => currentIndex(col),
437
+ fromPointer: (e) => {
438
+ if (startWidth <= 0 || startUnits <= 0) return null;
439
+ const rtl = (doc.defaultView?.getComputedStyle(handleEl).direction ?? 'ltr') === 'rtl';
440
+ const dx = (rtl ? -1 : 1) * (e.clientX - startX);
441
+ return nearestStepIndex(stepList, ((startWidth + dx) / startWidth) * startUnits);
442
+ },
443
+ onChange: (value) => {
444
+ widthSteps.set(field, value);
445
+ touched.add(field);
446
+ applyWidths();
447
+ },
448
+ });
449
+ resizeHandles.set(cell, handle);
450
+ });
451
+ };
452
+
453
+ const applyEdges = (): void => {
454
+ if (!table || P().scroll !== true) return;
455
+ const left = table.scrollLeft > 0;
456
+ const right = table.scrollLeft + table.clientWidth < table.scrollWidth - 1;
457
+ if (left) table.setAttribute('data-kit-edge-l', ''); else table.removeAttribute('data-kit-edge-l');
458
+ if (right) table.setAttribute('data-kit-edge-r', ''); else table.removeAttribute('data-kit-edge-r');
459
+ };
460
+
461
+ const applyCells = (): void => {
462
+ if (!table) return;
463
+ table.querySelectorAll<HTMLElement>('[data-kit-ellipsis]').forEach((el) => {
464
+ const text = (el.textContent ?? '').trim();
465
+ if (text !== '' && el.getAttribute('title') !== text) el.setAttribute('title', text);
466
+ });
467
+ if (str(P().editMode) !== '') {
468
+ table.querySelectorAll<HTMLElement>('[data-kit-editable]').forEach((el) => {
469
+ if (el.hasAttribute('data-kit-edit-ready')) return;
470
+ el.setAttribute('data-kit-edit-ready', '');
471
+ el.setAttribute('tabindex', '0');
472
+ el.className = `${el.className} ${EDIT_CELL_CLASS}`;
473
+ });
474
+ }
475
+ };
476
+
477
+ const applyAll = (): void => {
478
+ applyHidden();
479
+ applyWidths();
480
+ applyHandles();
481
+ applyDensity();
482
+ applyEdges();
483
+ applyCells();
484
+ };
485
+
486
+ const persistHidden = (): void => {
487
+ writeStore(rememberKey(pathname(), object(), 'cols'), hidden.size === 0 ? null : JSON.stringify({ hidden: [...hidden] }));
488
+ };
489
+
490
+ // ---- 勾选 / 批量
491
+ const selectRows = (rows: unknown[], checked: boolean): void => {
492
+ if (rows.length === 0) return;
493
+ ctx.emit('select_change', { rows, checked, mode: 'multi', keyField: keyField() });
494
+ };
495
+ /** 本页勾选状态:全未选 false / 部分选 'mixed' / 全选 true */
496
+ const pageState = (): boolean | 'mixed' => {
497
+ const rows = rowsList();
498
+ if (rows.length === 0) return false;
499
+ const picked = new Set(selectedList().map((r) => rowKeyOf(r, keyField())));
500
+ const n = rows.filter((r) => picked.has(rowKeyOf(r, keyField()))).length;
501
+ return n === 0 ? false : n === rows.length ? true : 'mixed';
502
+ };
503
+ const pageSelected = (): boolean => pageState() === true;
504
+
505
+ const exportCsv = (): void => {
506
+ const visible = cols().filter((c) => !hidden.has(c.field));
507
+ const picked = selectedList();
508
+ const rows = picked.length > 0 ? picked : rowsList();
509
+ const text = buildCsv(visible, rows);
510
+ const doc = rootEl?.ownerDocument;
511
+ if (!doc || typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') return;
512
+ const blob = new Blob([text], { type: 'text/csv;charset=utf-8' });
513
+ const url = URL.createObjectURL(blob);
514
+ const a = doc.createElement('a');
515
+ a.setAttribute('href', url);
516
+ a.setAttribute('download', KIT_TABLE_EXT.export.filename);
517
+ doc.body.appendChild(a);
518
+ a.click();
519
+ a.remove();
520
+ URL.revokeObjectURL(url);
521
+ notice = { text: T('soma.kit.exported_rows', { n: Math.min(rows.length, KIT_TABLE_EXT.export.maxRows) }), error: false };
522
+ rebuild();
523
+ };
524
+
525
+ // ---- 就地编辑
526
+ // control:可聚焦、承载 aria 的元素;valueEl:读值的 input(自绘 Select / 日期框的 hidden 或文本载体);shell:挂进单元格的外壳;handle:命令式嵌入件(卸载时释放)
527
+ interface EditCell { col: ToolsColumn; cell: HTMLElement; control: HTMLElement; valueEl: HTMLInputElement; shell: HTMLElement; handle: KitEmbedHandle | null; host: HTMLElement | null; err: HTMLElement }
528
+ // 就地编辑的命令式嵌入件(日期框、下拉):退出编辑 / 表体被整块重建 / 卸载时统一释放并收起浮层
529
+ const embeds = createKitEmbedBag();
530
+ let editing: { rowIndex: number; row: Rec; cells: EditCell[]; focusCell: HTMLElement } | null = null;
531
+
532
+ const rowOfCell = (cell: HTMLElement): { index: number; row: Rec } | null => {
533
+ const container = table?.querySelector<HTMLElement>('[data-kit-rows]');
534
+ if (!container) return null;
535
+ let el: HTMLElement | null = cell;
536
+ while (el && el.parentElement !== container) el = el.parentElement;
537
+ if (!el) return null;
538
+ // 虚拟滚动表体(KitVirtualRows)只画窗口内的行:行自带数据下标 data-kit-index,不能按 DOM 序号推
539
+ const stamped = el.getAttribute('data-kit-index');
540
+ const items = Array.from(container.children).filter((c) => c.tagName !== 'TEMPLATE');
541
+ const index = stamped !== null && Number.isInteger(Number(stamped)) ? Number(stamped) : items.indexOf(el);
542
+ const row = rowsList()[index];
543
+ return index >= 0 && isRec(row) ? { index, row } : null;
544
+ };
545
+
546
+ const cancelEdit = (refocus: boolean): void => {
547
+ if (!editing) return;
548
+ const e = editing;
549
+ editing = null;
550
+ for (const c of e.cells) {
551
+ // 日期框 / 下拉是自绘件:释放它(收掉浮层、解绑监听),再摘掉整个外壳
552
+ if (c.handle) embeds.drop(c.handle);
553
+ c.shell.remove();
554
+ c.err.remove();
555
+ c.host?.classList.remove(HIDDEN_CLASS);
556
+ }
557
+ // 退出编辑:焦点回到进入编辑的单元格(点外部取消时不抢焦点),并播报
558
+ if (refocus) e.focusCell.focus();
559
+ liveLast = '';
560
+ announce(T('soma.kit.edit_exited'));
561
+ };
562
+
563
+ const controlFor = (doc: Document, col: ToolsColumn, value: unknown): Pick<EditCell, 'control' | 'valueEl' | 'shell' | 'handle'> => {
564
+ if (col.kind === 'date') {
565
+ // 行内日期:自绘日历框,控件是它的文本框(value 即日期文本)
566
+ const field = embeds.add(mountKitDateField({ value: value === null || value === undefined ? '' : String(value), fieldClass: EDIT_DATE_CLASS }));
567
+ return { control: field.input, valueEl: field.input, shell: field.el, handle: field };
568
+ }
569
+ if (col.kind === 'select') {
570
+ // 行内下拉:自绘 Select(没有原生 <select>);单元格编辑模式下选中即提交,行编辑模式随 Enter(其它控件上)一起提交
571
+ const field = embeds.add(mountKitSelectField({
572
+ options: col.options.map((o) => ({ value: String(o.value), label: o.label })),
573
+ value: value === null || value === undefined ? '' : String(value),
574
+ size: 'sm',
575
+ className: EDIT_SELECT_CLASS,
576
+ onChange: () => { if (str(P().editMode) !== 'row') queueMicrotask(() => { if (editing) commitEdit(); }); },
577
+ }));
578
+ return { control: field.field, valueEl: field.input, shell: field.el, handle: field };
579
+ }
580
+ const input = doc.createElement('input');
581
+ input.setAttribute('type', 'text');
582
+ input.value = value === null || value === undefined ? '' : String(value);
583
+ input.className = EDIT_INPUT_CLASS;
584
+ // 数字列:自绘数字框(过滤非数字、↑↓ 调值),不用原生 type=number;随输入框一起卸载
585
+ if (col.kind === 'number') attachSpin(input, () => ({ step: 1 }));
586
+ return { control: input, valueEl: input, shell: input, handle: null };
587
+ };
588
+
589
+ const startEdit = (cell: HTMLElement): void => {
590
+ const mode = str(P().editMode);
591
+ if (mode === '' || cell.getAttribute('data-kit-editable') === null) return;
592
+ const hit = rowOfCell(cell);
593
+ if (!hit) return;
594
+ cancelEdit(false);
595
+ const doc = cell.ownerDocument;
596
+ const targets = mode === 'row'
597
+ ? Array.from(cell.parentElement?.querySelectorAll<HTMLElement>('[data-kit-editable]') ?? [cell])
598
+ : [cell];
599
+ const list: EditCell[] = [];
600
+ for (const t of targets) {
601
+ const col = cols().find((c) => c.field === t.getAttribute('data-kit-col'));
602
+ if (!col || !col.editable || hit.index !== rowOfCell(t)?.index) continue;
603
+ const host = t.firstElementChild instanceof HTMLElement ? t.firstElementChild : null;
604
+ const made = controlFor(doc, col, hit.row[col.field]);
605
+ const { control } = made;
606
+ control.setAttribute('aria-label', col.label);
607
+ control.setAttribute('data-kit-edit-control', col.field);
608
+ const err = doc.createElement('span');
609
+ err.className = HIDDEN_CLASS;
610
+ err.setAttribute('role', 'alert');
611
+ host?.classList.add(HIDDEN_CLASS);
612
+ t.appendChild(made.shell);
613
+ t.appendChild(err);
614
+ list.push({ col, cell: t, ...made, host, err });
615
+ }
616
+ if (list.length === 0) return;
617
+ editing = { rowIndex: hit.index, row: hit.row, cells: list, focusCell: cell };
618
+ const first = list.find((c) => c.cell === cell) ?? list[0]!;
619
+ first.control.focus();
620
+ liveLast = '';
621
+ announce(T('soma.kit.editing_hint', { label: first.col.label }));
622
+ };
623
+
624
+ const valueOf = (e: EditCell): unknown => {
625
+ const raw = e.valueEl.value;
626
+ if (e.col.kind === 'number') return raw.trim() === '' ? null : num(raw);
627
+ if (e.col.kind === 'select') {
628
+ const hit = e.col.options.find((o) => String(o.value) === raw);
629
+ return hit !== undefined ? hit.value : raw;
630
+ }
631
+ return raw;
632
+ };
633
+
634
+ const commitEdit = (): void => {
635
+ if (!editing) return;
636
+ const e = editing;
637
+ const changes: Rec = {};
638
+ for (const c of e.cells) {
639
+ const next = valueOf(c);
640
+ const prev = e.row[c.col.field];
641
+ const same = (next === null || next === '') && (prev === null || prev === undefined || prev === '') ? true : String(next) === String(prev);
642
+ if (!same) changes[c.col.field] = next;
643
+ }
644
+ if (Object.keys(changes).length === 0) {
645
+ cancelEdit(true);
646
+ return;
647
+ }
648
+ // 前端即时校验:沿用对象字典的 rules,只看被改的字段
649
+ const port = dataPort();
650
+ if (port?.validate) {
651
+ const bad = port.validate(object(), { ...e.row, ...changes });
652
+ let any = false;
653
+ for (const c of e.cells) {
654
+ const msg = c.col.field in changes ? bad[c.col.field] : undefined;
655
+ if (msg) {
656
+ any = true;
657
+ c.err.className = EDIT_ERR_CLASS;
658
+ c.err.textContent = msg;
659
+ c.control.setAttribute('aria-invalid', 'true');
660
+ } else {
661
+ c.err.className = HIDDEN_CLASS;
662
+ c.err.textContent = '';
663
+ c.control.removeAttribute('aria-invalid');
664
+ }
665
+ }
666
+ if (any) {
667
+ e.cells.find((c) => c.control.getAttribute('aria-invalid') === 'true')?.control.focus();
668
+ return;
669
+ }
670
+ }
671
+ const key = keyField();
672
+ if (key === '' || e.row[key] === undefined) {
673
+ notice = { text: T('soma.kit.save_no_key'), error: true };
674
+ cancelEdit(true);
675
+ rebuild();
676
+ return;
677
+ }
678
+ const model: Rec = { [key]: e.row[key], ...changes };
679
+ cancelEdit(true);
680
+ notice = { text: T('soma.kit.saving'), error: false };
681
+ rebuild();
682
+ ctx.emit('cell_edit', { object: object(), scope: cellScope(), model, mode: 'update', field: Object.keys(changes).join(','), row: e.row });
683
+ };
684
+
685
+ // ---- 工具栏 / 批量条 渲染
686
+ const btn = (doc: Document, cls: string, text: string, attrs: Record<string, string> = {}): HTMLButtonElement => {
687
+ const b = doc.createElement('button');
688
+ b.setAttribute('type', 'button');
689
+ b.className = cls;
690
+ b.textContent = text;
691
+ for (const [k, v] of Object.entries(attrs)) b.setAttribute(k, v);
692
+ return b;
693
+ };
694
+
695
+ const renderToolbar = (doc: Document, items: string[]): HTMLElement => {
696
+ const group = doc.createElement('div');
697
+ group.className = GROUP_CLASS;
698
+ for (const it of items) {
699
+ if (it === 'reload') {
700
+ group.appendChild(btn(doc, TOOL_BTN_CLASS, T('soma.kit.refresh'), { 'data-kit-tool': 'reload' }));
701
+ } else if (it === 'density') {
702
+ const seg = doc.createElement('div');
703
+ seg.className = SEG_GROUP_CLASS;
704
+ seg.setAttribute('role', 'group');
705
+ seg.setAttribute('aria-label', T('soma.kit.row_height'));
706
+ for (const d of DENSITIES) {
707
+ const on = effectiveDensity() === d.id;
708
+ const b = btn(doc, on ? SEG_BTN_ON_CLASS : SEG_BTN_CLASS, T(d.label), { 'data-kit-density': d.id, 'aria-pressed': on ? 'true' : 'false' });
709
+ seg.appendChild(b);
710
+ }
711
+ group.appendChild(seg);
712
+ } else if (it === 'columns') {
713
+ const anchor = doc.createElement('div');
714
+ anchor.className = ANCHOR_CLASS;
715
+ anchor.appendChild(btn(doc, TOOL_BTN_CLASS, T('soma.kit.columns'), { 'data-kit-tool': 'columns', 'aria-haspopup': 'dialog', 'aria-expanded': panelOpen ? 'true' : 'false' }));
716
+ if (panelOpen) anchor.appendChild(columnPanel(doc));
717
+ group.appendChild(anchor);
718
+ } else if (it === 'export') {
719
+ group.appendChild(btn(doc, TOOL_BTN_CLASS, T('soma.kit.export'), { 'data-kit-tool': 'export' }));
720
+ }
721
+ }
722
+ return group;
723
+ };
724
+
725
+ const columnPanel = (doc: Document): HTMLElement => {
726
+ const panel = doc.createElement('div');
727
+ panel.setAttribute('role', 'dialog');
728
+ panel.setAttribute('aria-label', T('soma.kit.columns'));
729
+ panel.setAttribute('data-kit-cols-panel', '');
730
+ panel.className = PANEL_BASE;
731
+ for (const c of cols()) {
732
+ const locked = c.fixed !== '';
733
+ const box = createCheck(doc, 'checkbox', {
734
+ checked: locked || !hidden.has(c.field), disabled: locked, extra: locked ? PANEL_CHECK_LOCKED_CLASS : PANEL_CHECK_CLASS,
735
+ });
736
+ box.setAttribute('data-kit-col-toggle', c.field);
737
+ const text = doc.createElement('span');
738
+ text.textContent = locked ? T('soma.kit.col_fixed', { label: c.label }) : c.label;
739
+ box.appendChild(text);
740
+ panel.appendChild(box);
741
+ }
742
+ const foot = doc.createElement('div');
743
+ foot.className = PANEL_FOOT_CLASS;
744
+ foot.appendChild(btn(doc, LINK_BTN_CLASS, T('soma.kit.restore_default'), { 'data-kit-cols-reset': '' }));
745
+ panel.appendChild(foot);
746
+ queueMicrotask(() => {
747
+ const anchor = panel.parentElement;
748
+ if (!anchor) return;
749
+ // 默认挂到浮层端口,不被表格外层容器的 overflow 裁切;端口不可用时留在原位
750
+ syncDropdown(panel, true, PANEL_BASE, anchor, 'start');
751
+ if (rootEl && !rootEl.contains(panel)) panelBind?.(panel);
752
+ });
753
+ return panel;
754
+ };
755
+
756
+ const renderBatch = (doc: Document, batch: BatchItem[]): HTMLElement => {
757
+ const picked = selectedList();
758
+ const total = num(P().total) ?? 0;
759
+ const rows = rowsList();
760
+ const count = allMode ? Math.max(total, picked.length) : picked.length;
761
+ const bar = doc.createElement('div');
762
+ bar.className = BATCH_BAR_CLASS;
763
+ bar.setAttribute('role', 'group');
764
+ bar.setAttribute('aria-label', T('soma.kit.batch_ops'));
765
+ const text = doc.createElement('span');
766
+ text.className = BATCH_TEXT_CLASS;
767
+ text.textContent = T('soma.kit.selected', { n: count });
768
+ announce(T('soma.kit.selected', { n: count }));
769
+ selAnnounced = true;
770
+ bar.appendChild(text);
771
+ // 本页都选了、总数更多:给「选择全部 N 项」(用户确认后批量动作按当前筛选处理)
772
+ if (str(P().selectScope, 'all') === 'all' && !allMode && pageSelected() && total > rows.length && total > picked.length) {
773
+ bar.appendChild(btn(doc, LINK_BTN_CLASS, T('soma.kit.select_all_n', { n: total }), { 'data-kit-select-all': '' }));
774
+ }
775
+ if (rows.length > 0 && !pageSelected()) bar.appendChild(btn(doc, LINK_BTN_CLASS, T('soma.kit.select_page'), { 'data-kit-page-select': '' }));
776
+ bar.appendChild(btn(doc, LINK_BTN_CLASS, T('soma.kit.clear'), { 'data-kit-sel-clear': '' }));
777
+ if (confirming !== null) {
778
+ const item = batch.find((b) => b.id === confirming);
779
+ if (item) {
780
+ const q = doc.createElement('span');
781
+ q.setAttribute('role', 'alert');
782
+ q.textContent = confirmText(item.confirm, count);
783
+ bar.appendChild(q);
784
+ bar.appendChild(btn(doc, ACTION_BUTTON_CLASS[item.tone], T('soma.kit.confirm'), { 'data-kit-batch-yes': item.id }));
785
+ bar.appendChild(btn(doc, ACTION_BUTTON_CLASS.neutral, T('soma.kit.cancel'), { 'data-kit-batch-no': '' }));
786
+ return bar;
787
+ }
788
+ }
789
+ for (const b of batch) {
790
+ if (b.permission !== '' && check !== null && !check(b.permission)) continue;
791
+ bar.appendChild(btn(doc, ACTION_BUTTON_CLASS[b.tone], b.name, { 'data-kit-batch': b.id }));
792
+ }
793
+ return bar;
794
+ };
795
+
796
+ const render = (root: HTMLElement, p: Rec): void => {
797
+ const doc = root.ownerDocument;
798
+ const items = (Array.isArray(p.items) ? p.items : []).filter((x): x is string => typeof x === 'string');
799
+ const batch = batchOf(p.batch);
800
+ const picked = selectedList();
801
+ const batching = batch.length > 0 && picked.length > 0;
802
+ const selectAll = batch.length > 0 && str(p.selectMode) === 'multi';
803
+ releaseDropdownsIn(root);
804
+ root.replaceChildren();
805
+ if (!liveEl || liveEl.parentElement === null) {
806
+ liveEl = doc.createElement('div');
807
+ liveEl.className = SR_ONLY_CLASS;
808
+ liveEl.setAttribute('role', 'status');
809
+ liveEl.setAttribute('data-kit-live', '');
810
+ root.insertAdjacentElement('afterend', liveEl);
811
+ }
812
+ const parts: HTMLElement[] = [];
813
+ if (!batching && selAnnounced) { selAnnounced = false; liveLast = ''; announce(T('soma.kit.selection_cleared')); }
814
+ if (batching) {
815
+ parts.push(renderBatch(doc, batch));
816
+ } else {
817
+ if (selectAll) {
818
+ const box = createCheck(doc, 'checkbox', { checked: pageState() });
819
+ box.setAttribute('data-kit-page-all', '');
820
+ const text = doc.createElement('span');
821
+ text.className = CHECK_TEXT_CLASS;
822
+ text.textContent = T('soma.kit.select_page');
823
+ box.appendChild(text);
824
+ parts.push(box);
825
+ }
826
+ if (items.length > 0) parts.push(renderToolbar(doc, items));
827
+ }
828
+ if (notice !== null) {
829
+ const n = doc.createElement('span');
830
+ n.className = notice.error ? NOTICE_ERR_CLASS : NOTICE_CLASS;
831
+ n.setAttribute('role', notice.error ? 'alert' : 'status');
832
+ n.textContent = notice.text;
833
+ parts.push(n);
834
+ }
835
+ // 批量条与全选在同一行:全选本页放在批量条之外时与工具栏分居两端
836
+ for (const part of parts) root.appendChild(part);
837
+ root.className = parts.length === 0 ? `${HIDDEN_CLASS}` : `${ROOT_CLASS} ${typeof p.class === 'string' ? p.class : ''}`.trim();
838
+ };
839
+
840
+ return createKitController({
841
+ attach(root, api) {
842
+ rootEl = root;
843
+ apiRef = api;
844
+ const names = (): string[] => cols().map((c) => c.field);
845
+ table = (() => {
846
+ const next = api.host.nextElementSibling;
847
+ if (next instanceof HTMLElement && next.hasAttribute('data-kit-table')) return next;
848
+ return api.host.parentElement?.querySelector<HTMLElement>('[data-kit-table]') ?? null;
849
+ })();
850
+ hidden = parseHidden(readStore(rememberKey(pathname(), object(), 'cols')), names());
851
+ const savedDensity = readStore(rememberKey(pathname(), object(), 'density'));
852
+ density = savedDensity === 'compact' || savedDensity === 'standard' || savedDensity === 'comfortable' ? savedDensity : null;
853
+ rebuild = () => { if (rootEl) render(rootEl, api.props()); };
854
+
855
+ const offs: Array<() => void> = [];
856
+ const on = (el: EventTarget | null | undefined, type: string, fn: (e: never) => void): void => {
857
+ if (!el) return;
858
+ el.addEventListener(type, fn as EventListener);
859
+ offs.push(() => el.removeEventListener(type, fn as EventListener));
860
+ };
861
+
862
+ // 工具栏 / 批量条 的点击与勾选
863
+ on(root, 'click', (event: Event) => {
864
+ const t = event.target as HTMLElement | null;
865
+ if (!t) return;
866
+ const tool = t.closest<HTMLElement>('[data-kit-tool]')?.getAttribute('data-kit-tool');
867
+ if (tool === 'reload') { ctx.emit('reload', {}); return; }
868
+ if (tool === 'export') { exportCsv(); return; }
869
+ if (tool === 'columns') { panelOpen = !panelOpen; rebuild(); return; }
870
+ const dens = t.closest<HTMLElement>('[data-kit-density]')?.getAttribute('data-kit-density');
871
+ if (dens === 'compact' || dens === 'standard' || dens === 'comfortable') {
872
+ density = dens;
873
+ writeStore(rememberKey(pathname(), object(), 'density'), dens);
874
+ applyDensity();
875
+ rebuild();
876
+ return;
877
+ }
878
+ if (t.closest('[data-kit-cols-reset]')) {
879
+ hidden = new Set();
880
+ persistHidden();
881
+ applyHidden();
882
+ resetWidths();
883
+ rebuild();
884
+ return;
885
+ }
886
+ if (t.closest('[data-kit-sel-clear]')) {
887
+ allMode = false;
888
+ confirming = null;
889
+ selectRows(selectedList(), false);
890
+ return;
891
+ }
892
+ if (t.closest('[data-kit-select-all]')) { allMode = true; rebuild(); return; }
893
+ if (t.closest('[data-kit-page-select]')) { selectRows(rowsList(), true); return; }
894
+ const batchId = t.closest<HTMLElement>('[data-kit-batch]')?.getAttribute('data-kit-batch');
895
+ if (batchId) {
896
+ const item = batchOf(api.props().batch).find((b) => b.id === batchId);
897
+ if (!item) return;
898
+ if (item.confirm !== '') { confirming = item.id; rebuild(); return; }
899
+ fireBatch(item);
900
+ return;
901
+ }
902
+ const yes = t.closest<HTMLElement>('[data-kit-batch-yes]')?.getAttribute('data-kit-batch-yes');
903
+ if (yes) {
904
+ const item = batchOf(api.props().batch).find((b) => b.id === yes);
905
+ confirming = null;
906
+ if (item) fireBatch(item);
907
+ return;
908
+ }
909
+ if (t.closest('[data-kit-batch-no]')) { confirming = null; rebuild(); }
910
+ });
911
+ const fireBatch = (item: BatchItem): void => {
912
+ const picked = selectedList();
913
+ const total = num(api.props().total) ?? 0;
914
+ const all = allMode;
915
+ ctx.emit('batch_action', {
916
+ kit_action: item.id, id: item.id, name: item.name, rows: picked, count: all ? Math.max(total, picked.length) : picked.length, all,
917
+ });
918
+ allMode = false;
919
+ };
920
+ // 勾选标记(check-core):全选本页 / 列显隐;乐观着色后再动数据
921
+ const onMark = (mark: HTMLElement, next: boolean): void => {
922
+ paintCheck(mark, { checked: next, extra: mark.hasAttribute('data-kit-col-toggle') ? PANEL_CHECK_CLASS : undefined });
923
+ if (mark.hasAttribute('data-kit-page-all')) {
924
+ selectRows(rowsList(), next);
925
+ return;
926
+ }
927
+ const f = mark.getAttribute('data-kit-col-toggle');
928
+ if (f !== null) {
929
+ if (next) hidden.delete(f);
930
+ else hidden.add(f);
931
+ persistHidden();
932
+ applyHidden();
933
+ }
934
+ };
935
+ offs.push(attachMarkEvents(root, onMark));
936
+ on(root, 'keydown', (event: KeyboardEvent) => {
937
+ if (event.key === 'Escape' && panelOpen) {
938
+ event.preventDefault();
939
+ panelOpen = false;
940
+ rebuild();
941
+ root.querySelector<HTMLElement>('[data-kit-tool="columns"]')?.focus();
942
+ } else if (event.key === 'Escape' && confirming !== null) {
943
+ confirming = null;
944
+ rebuild();
945
+ }
946
+ });
947
+ offs.push(onOutsidePress(root, () => panelOpen, () => { panelOpen = false; rebuild(); }));
948
+ panelBind = (panel) => {
949
+ // 面板在浮层里:勾选 / 恢复默认 / Esc 直接听在面板上(与 root 上的委托同一套处理)
950
+ attachMarkEvents(panel, onMark);
951
+ panel.addEventListener('click', (event: Event) => {
952
+ if (!(event.target as HTMLElement | null)?.closest('[data-kit-cols-reset]')) return;
953
+ hidden = new Set();
954
+ persistHidden();
955
+ applyHidden();
956
+ resetWidths();
957
+ rebuild();
958
+ });
959
+ panel.addEventListener('keydown', (event: KeyboardEvent) => {
960
+ if (event.key !== 'Escape' || !panelOpen) return;
961
+ event.preventDefault();
962
+ event.stopPropagation();
963
+ panelOpen = false;
964
+ rebuild();
965
+ root.querySelector<HTMLElement>('[data-kit-tool="columns"]')?.focus();
966
+ });
967
+ };
968
+
969
+ // 表格外壳:滚动边缘 / 新渲染的行 / 就地编辑
970
+ if (table) {
971
+ const tb = table;
972
+ on(tb, 'scroll', () => applyEdges());
973
+ on(tb, 'dblclick', (event: Event) => {
974
+ const cell = (event.target as HTMLElement | null)?.closest<HTMLElement>('[data-kit-editable]');
975
+ if (cell && !(event.target as HTMLElement).closest('[data-kit-edit-control]')) startEdit(cell);
976
+ });
977
+ on(tb, 'keydown', (event: KeyboardEvent) => {
978
+ const t = event.target as HTMLElement | null;
979
+ if (!t) return;
980
+ const control = t.closest('[data-kit-edit-control]');
981
+ if (control && editing) {
982
+ // 自绘下拉自己处理 Enter(开面板 / 选中,已 preventDefault),不当作整行提交
983
+ const onSelect = editing.cells.some((c) => c.col.kind === 'select' && c.control === control);
984
+ if (event.key === 'Enter') { if (onSelect && event.defaultPrevented) return; event.preventDefault(); commitEdit(); }
985
+ else if (event.key === 'Escape') { event.preventDefault(); cancelEdit(true); }
986
+ return;
987
+ }
988
+ if ((event.key === 'Enter' || event.key === 'F2') && t.hasAttribute('data-kit-editable')) {
989
+ event.preventDefault();
990
+ startEdit(t);
991
+ }
992
+ });
993
+ // 编辑器自带的浮层(日期 / 日期范围 / 时间 / 下拉的面板挂在浮层端口,不在表格 DOM 内)算编辑区内部:
994
+ // 面板的锚点在表格里即属本表;点击瞬间已被重画摘掉的节点(日历翻月、选中后重绘)也不算外部
995
+ offs.push(onOutsidePress(tb, () => editing !== null, () => cancelEdit(false), (node) => {
996
+ const v = overlayVerdict(node, tb);
997
+ if (v === 'inside') return true;
998
+ if (v === 'foreign-layer') return editing !== null && editing.cells.some((c) => c.handle !== null);
999
+ return false;
1000
+ }));
1001
+ if (typeof MutationObserver !== 'undefined') {
1002
+ let queued = false;
1003
+ const mo = new MutationObserver(() => {
1004
+ if (queued) return;
1005
+ queued = true;
1006
+ queueMicrotask(() => {
1007
+ queued = false;
1008
+ // 表体被整块重建:正在编辑的单元格已脱离文档,先释放上一轮挂进去的日期框 / 下拉(含它们已展开的浮层)
1009
+ if (editing && editing.cells.some((c) => !c.cell.isConnected)) cancelEdit(false);
1010
+ applyAll();
1011
+ });
1012
+ });
1013
+ mo.observe(tb, { childList: true, subtree: true });
1014
+ offs.push(() => mo.disconnect());
1015
+ }
1016
+ if (typeof ResizeObserver !== 'undefined') {
1017
+ const ro = new ResizeObserver(() => applyEdges());
1018
+ ro.observe(tb);
1019
+ offs.push(() => ro.disconnect());
1020
+ }
1021
+ }
1022
+
1023
+ // 就地编辑的写入结果:失败文案进状态行(沿用 data.submit 的结果回写)
1024
+ const port = dataPort();
1025
+ if (port?.onWriteOutcome) {
1026
+ offs.push(port.onWriteOutcome((scope) => {
1027
+ if (scope !== cellScope()) return;
1028
+ const view = port.writeOutcome(scope);
1029
+ if (view.status === 'failed') {
1030
+ const fe = Object.values(view.fieldErrors ?? {}).filter((x) => x !== '');
1031
+ notice = { text: T('soma.kit.save_failed', { reason: view.message !== '' ? view.message : fe.join(T('soma.kit.list_sep')) || T('soma.kit.retry') }), error: true };
1032
+ rebuild();
1033
+ } else if (view.status === 'saved') {
1034
+ notice = null;
1035
+ rebuild();
1036
+ }
1037
+ }));
1038
+ }
1039
+ applyAll();
1040
+ return () => {
1041
+ for (const off of offs) off();
1042
+ if (rootEl) releaseDropdownsIn(rootEl);
1043
+ panelBind = null;
1044
+ for (const h of resizeHandles.values()) h.destroy();
1045
+ resizeHandles.clear();
1046
+ cancelEdit(false);
1047
+ embeds.release(rootEl);
1048
+ liveEl?.remove();
1049
+ liveEl = null;
1050
+ liveLast = '';
1051
+ table = null;
1052
+ rootEl = null;
1053
+ apiRef = null;
1054
+ rebuild = () => undefined;
1055
+ };
1056
+ },
1057
+ render(root, p) {
1058
+ // 翻页 / 重取后:scope=page 时丢弃不在本页的勾选;选择清空后退出「全部」模式
1059
+ const rows = Array.isArray(p.rows) ? p.rows : null;
1060
+ if (str(p.selectMode) === 'multi' && str(p.selectScope, 'all') === 'page' && rows !== null && rows.length > 0) {
1061
+ const here = new Set(rows.map((r) => rowKeyOf(r, str(p.keyField))));
1062
+ const stale = (Array.isArray(p.selected) ? p.selected : []).filter((r) => !here.has(rowKeyOf(r, str(p.keyField))));
1063
+ if (stale.length > 0) queueMicrotask(() => selectRows(stale, false));
1064
+ }
1065
+ if (allMode && (!Array.isArray(p.selected) || p.selected.length === 0)) allMode = false;
1066
+ render(root, p);
1067
+ applyAll();
1068
+ },
1069
+ })(ctx);
1070
+ },
1071
+ };
1072
+ }