soma-kit 0.1.18 → 0.1.20

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 (58) hide show
  1. package/package.json +2 -2
  2. package/spec/generated/kit-page.schema.json +15 -1
  3. package/spec/kit-grammar.json +142 -18
  4. package/spec/kit-grammar.schema.json +4 -0
  5. package/src/app/component-gate.ts +247 -16
  6. package/src/app/index.ts +4 -1
  7. package/src/app/kit-view-context.ts +44 -2
  8. package/src/app/server.ts +11 -2
  9. package/src/base/button.ts +11 -1
  10. package/src/biz/compose.ts +66 -0
  11. package/src/biz/define.ts +8 -0
  12. package/src/biz/index.ts +1 -0
  13. package/src/biz/layout-contracts.ts +119 -4
  14. package/src/biz/link/hub.ts +31 -0
  15. package/src/biz/master-sub/compile.ts +45 -3
  16. package/src/biz/master-sub/index.ts +3 -1
  17. package/src/biz/multi-board/compile.ts +5 -1
  18. package/src/biz/multi-board/prose-fold.ts +78 -5
  19. package/src/biz/multi-board/shell.ts +10 -3
  20. package/src/biz/record-detail/compile.ts +120 -10
  21. package/src/biz/shared/coordinator.ts +245 -48
  22. package/src/biz/shared/index.ts +5 -1
  23. package/src/biz/shared/object-aliases.ts +14 -3
  24. package/src/biz/shared/overlay-compile.ts +56 -5
  25. package/src/biz/shared/overlay-shell.ts +5 -2
  26. package/src/biz/shared/page-form.ts +9 -5
  27. package/src/biz/shared/page-overlay-host.ts +126 -0
  28. package/src/biz/shared/page-overlay-names.ts +27 -0
  29. package/src/biz/shared/runtime-hub.ts +37 -2
  30. package/src/biz/single-form/compile.ts +60 -5
  31. package/src/biz/single-form/index.ts +2 -1
  32. package/src/biz/standard-crud/compile.ts +9 -2
  33. package/src/biz/types.ts +18 -0
  34. package/src/cli/kit-cli.ts +1 -0
  35. package/src/cli/view-writes.ts +130 -3
  36. package/src/compile/compile-page.ts +49 -4
  37. package/src/compile/page-pipeline.ts +4 -0
  38. package/src/compile/parse.ts +14 -0
  39. package/src/compile/stages.ts +5 -4
  40. package/src/compile/types.ts +1 -1
  41. package/src/compile/view-check.ts +50 -19
  42. package/src/data/comment-thread.ts +78 -18
  43. package/src/data/navbar.ts +4 -0
  44. package/src/data/object-form.ts +17 -3
  45. package/src/data/prompt-dialog.ts +102 -15
  46. package/src/frames/page-header.ts +11 -2
  47. package/src/frames/shared.ts +6 -0
  48. package/src/frames/types.ts +2 -0
  49. package/src/generated/kit-grammar-runtime.ts +48 -8
  50. package/src/i18n/kit-text.ts +1 -0
  51. package/src/object-renderer/emit-static.ts +10 -3
  52. package/src/object-renderer/request-actions.ts +145 -17
  53. package/src/object-renderer/types.ts +7 -0
  54. package/src/shared/dom-attrs-registry.ts +9 -5
  55. package/src/shared/dom-attrs.ts +4 -0
  56. package/src/spatial/declared-actions.ts +6 -3
  57. package/src/spatial/emit.ts +1 -1
  58. package/src/spatial/expand.ts +7 -2
@@ -12,6 +12,13 @@ import { defineKitBizComponent } from './define';
12
12
  import { validateBizAreaClass } from './shared/compile-helpers';
13
13
  import type { KitBizContext, KitBizDefinition, KitBizEnvelopeTrait, KitBizInput, KitBizRole } from './types';
14
14
  import { kitFail } from '../shared/kit-error';
15
+ import { KIT_BIZ_LAYOUT_CONTRACTS, kitLayoutContract, kitLayoutContractProblems, kitRebaseLayoutContract, type KitBizLayoutContract } from './layout-contracts';
16
+
17
+ /** 组件的版式契约来源:内置冻结表优先,其次组件定义上声明的 layoutContract;都没有为 undefined */
18
+ function contractOfDef(def: KitBizDefinition): KitBizLayoutContract | undefined {
19
+ if (Object.hasOwn(KIT_BIZ_LAYOUT_CONTRACTS, def.kind)) return KIT_BIZ_LAYOUT_CONTRACTS[def.kind]!;
20
+ return def.layoutContract ?? undefined;
21
+ }
15
22
 
16
23
  export interface WrapBizShellContext {
17
24
  input: KitBizInput;
@@ -31,6 +38,12 @@ export interface WrapBizOptions {
31
38
  acceptConfig?: boolean;
32
39
  /** 可选:覆写底层业务组件的声明式版心特征;缺省透传 inner.envelope */
33
40
  envelope?: KitBizEnvelopeTrait;
41
+ /**
42
+ * 可选:版式契约(规则同 defineKitBizComponent 的 layoutContract,不合法报 KIT-COMP-007)。
43
+ * 缺省继承 inner 的契约(内置冻结表或 inner.layoutContract);roles 被重定义时只在新角色都在旧契约里时继承(按新角色裁剪),
44
+ * 裁剪后不合法(如依附目标被裁掉)则不继承;null = 不声明(取 FREE)
45
+ */
46
+ layoutContract?: KitBizLayoutContract | null;
34
47
  /** 包装层写死的 Tailwind 类串或类名列表(自动校验并并入产物 candidates) */
35
48
  candidates?: readonly string[];
36
49
  /**
@@ -61,11 +74,39 @@ export function wrapKitBizComponent(inner: KitBizDefinition, options: WrapBizOpt
61
74
  }
62
75
 
63
76
  const resolvedEnvelope = options.envelope ?? inner.envelope;
77
+ // 版式契约:显式给了用显式的(定义期校验、不合法抛 KIT-COMP-007);没给则继承 inner 的(角色被重定义时按新角色裁剪),继承结果不合法就不继承(与改前同为 FREE)
78
+ const innerContract = contractOfDef(inner);
79
+ const wrapRoles = options.roles ?? inner.roles;
80
+ let inherited: KitBizLayoutContract | undefined;
81
+ if (innerContract !== undefined) {
82
+ if (options.roles === undefined) {
83
+ inherited = innerContract;
84
+ } else if (Object.keys(wrapRoles).every((r) => Object.hasOwn(innerContract.roles, r))) {
85
+ const keptRoles = Object.freeze(Object.fromEntries(Object.keys(wrapRoles).map((r) => [r, innerContract.roles[r]!])));
86
+ if (innerContract.exclusiveGroups !== undefined) {
87
+ const used = new Set(Object.values(keptRoles).map((r) => r.exclusiveGroup).filter((g): g is string => g !== undefined));
88
+ const filteredEntries = Object.entries(innerContract.exclusiveGroups).filter(([g]) => used.has(g));
89
+ const remainingKinds = filteredEntries.map(([, e]) => e);
90
+ if (filteredEntries.length <= 1 && remainingKinds.includes(innerContract.exclusive)) {
91
+ const { exclusiveGroups: _drop, ...rest } = innerContract;
92
+ inherited = Object.freeze({ ...rest, roles: keptRoles });
93
+ } else {
94
+ inherited = Object.freeze({ ...innerContract, roles: keptRoles, exclusiveGroups: Object.freeze(Object.fromEntries(filteredEntries)) });
95
+ }
96
+ } else {
97
+ inherited = Object.freeze({ ...innerContract, roles: keptRoles });
98
+ }
99
+ }
100
+ }
101
+ const resolvedContract = options.layoutContract !== undefined
102
+ ? options.layoutContract
103
+ : inherited !== undefined && kitLayoutContractProblems(options.kind, wrapRoles, inherited).length === 0 ? inherited : undefined;
64
104
  return defineKitBizComponent({
65
105
  kind: options.kind,
66
106
  roles: options.roles ?? inner.roles,
67
107
  areas: allAreas,
68
108
  acceptConfig: options.acceptConfig ?? true,
109
+ ...(resolvedContract !== undefined ? { layoutContract: resolvedContract } : {}),
69
110
  ...(resolvedEnvelope !== undefined ? { envelope: resolvedEnvelope } : {}),
70
111
  ...(resolvedEnvelope === undefined && inner.pageMaxWidth !== undefined ? { pageMaxWidth: inner.pageMaxWidth } : {}),
71
112
  compile(input: KitBizInput, ctx: KitBizContext): KitFragment {
@@ -169,6 +210,12 @@ export interface ComposeBizOptions {
169
210
  acceptConfig?: boolean;
170
211
  /** 复合外壳写死的 Tailwind 类串或类名列表(自动校验并并入 candidates) */
171
212
  candidates?: readonly string[];
213
+ /**
214
+ * 可选:版式契约(规则同 defineKitBizComponent 的 layoutContract,不合法报 KIT-COMP-007)。
215
+ * 缺省:只有一个子部件且它有契约时合成——角色按 roleMap 改名、锚点按子部件前缀改写(kitRebaseLayoutContract)、互斥组加子部件前缀、
216
+ * 排法 / 互斥 / 版面事实沿用该子部件;多个子部件时排法与互斥没有确定解,不合成(取 FREE),需要契约请显式给。null = 不声明
217
+ */
218
+ layoutContract?: KitBizLayoutContract | null;
172
219
  /** 将各子部件生成的 HTML(`partHtml[partKey]`)装入写死的复合网格/边框外壳中 */
173
220
  renderShell: (partHtml: Record<string, string>, ctx: ComposeBizShellContext) => string;
174
221
  }
@@ -213,6 +260,24 @@ export function composeKitBizComponents(options: ComposeBizOptions): KitBizDefin
213
260
  const badRoot = checkClasses(baseRootClass, `${options.kind}.rootClass`);
214
261
  if (badRoot.length > 0) kitFail('KIT-COMP-003', `${options.kind}.rootClass`, `${options.kind} 的 rootClass 非法:${badRoot[0]!.message}`, 'rootClass 只能用刻度内的 Tailwind 类');
215
262
 
263
+ // 版式契约:显式给了用显式的;没给且只有一个子部件、它有契约时合成(合成结果不合法就不合成,与改前同为 FREE)
264
+ let composed: KitBizLayoutContract | undefined;
265
+ if (options.layoutContract === undefined && partEntries.length === 1) {
266
+ const [key, p] = partEntries[0]!;
267
+ const c = contractOfDef(p.component);
268
+ if (c !== undefined) {
269
+ const rb = kitRebaseLayoutContract(c, p.roleMap, key);
270
+ const candidate = kitLayoutContract({
271
+ arrange: c.arrange, exclusive: c.exclusive, defaultSelected: c.defaultSelected, roles: rb.roles,
272
+ ...(Object.keys(rb.exclusiveGroups).length > 0 ? { exclusiveGroups: rb.exclusiveGroups } : {}),
273
+ ...(rb.overlayAnchor !== undefined && p.forwardOverlays === true ? { overlayAnchor: rb.overlayAnchor } : {}),
274
+ frameFacts: { ...c.frameFacts },
275
+ });
276
+ if (kitLayoutContractProblems(options.kind, roles, candidate).length === 0) composed = candidate;
277
+ }
278
+ }
279
+ const resolvedContract = options.layoutContract !== undefined ? options.layoutContract : composed;
280
+
216
281
  const areas = [...new Set(['root', ...(options.areas ?? [])])];
217
282
  const areaSet = new Set<string>(areas);
218
283
  const extraTokens = splitCandidateTokens([baseRootClass, ...(options.candidates ?? [])]);
@@ -226,6 +291,7 @@ export function composeKitBizComponents(options: ComposeBizOptions): KitBizDefin
226
291
  roles,
227
292
  areas,
228
293
  acceptConfig: options.acceptConfig ?? true,
294
+ ...(resolvedContract !== undefined ? { layoutContract: resolvedContract } : {}),
229
295
  compile(input: KitBizInput, ctx: KitBizContext): KitFragment {
230
296
  const diagnostics: KitDiagnostic[] = [];
231
297
  const areaMap = input.areaClass ?? {};
package/src/biz/define.ts CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import type { KitBizDefinition } from './types';
6
6
  import { kitFail } from '../shared/kit-error';
7
+ import { kitLayoutContractProblems } from './layout-contracts';
7
8
 
8
9
  const KIND = /^[A-Z][A-Za-z0-9]*$/;
9
10
  const DEFINED_BIZ_COMPONENTS = new WeakSet<KitBizDefinition>();
@@ -48,6 +49,13 @@ export function defineKitBizComponent(def: KitBizDefinition): KitBizDefinition {
48
49
  if (typeof def.compile !== 'function') {
49
50
  kitFail('KIT-COMP-002', `bizComponents.${def.kind}.compile`, `业务组件 ${def.kind} 缺 compile()`, '提供 compile(input, ctx) 返回片段');
50
51
  }
52
+ // 版式契约(可选):与内置冻结表同一份不变量(kitLayoutContractProblems);不写或写 null = 不声明(页面线取 FREE,动作报 KIT-PAGE-GATE-006 告警)
53
+ if (def.layoutContract !== undefined && def.layoutContract !== null) {
54
+ const problems = kitLayoutContractProblems(def.kind, def.roles, def.layoutContract);
55
+ if (problems.length > 0) {
56
+ kitFail('KIT-COMP-007', `bizComponents.${def.kind}.layoutContract`, `业务组件 ${def.kind} 的版式契约不合法:${problems.join(';')}`, '契约角色键与 roles 一一相等、取值在闭集内、锚点拼法带 {page} / {object} 占位;用 kitLayoutContract({...}) 简写补缺省');
57
+ }
58
+ }
51
59
  DEFINED_BIZ_COMPONENTS.add(def);
52
60
  return def;
53
61
  }
package/src/biz/index.ts CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  import type { KitBizDefinition } from './types';
35
35
 
36
36
  export { defineKitBizComponent } from './define';
37
+ export { kitLayoutContract, kitLayoutContractProblems, type KitBizLayoutContract, type KitLayoutContractInput, type KitRoleLayout } from './layout-contracts';
37
38
  export { wrapKitBizComponent, composeKitBizComponents } from './compose';
38
39
  export type { WrapBizOptions, WrapBizShellContext, ComposeBizPart, ComposeBizOptions, ComposeBizShellContext } from './compose';
39
40
  export type {
@@ -5,10 +5,13 @@
5
5
  // 版面事实依据 compile/stages.ts 的 derivePageEnvelopeFacts 与各业务组件声明的版心特征(envelope)。
6
6
  // 栅格份数的出处(grid,SCON-151 构成同源)也登记在这里:模板交给构成求解的输入与页面线交给构成求解的输入走本文件同一个构造函数
7
7
  // (kitBoardPanelFacts / kitBoardCompositionNodes / kitDomainRegions / kitDomainCompositionInput),份数只有这一个出处。
8
- // 只 import shared/page-attrs 与排布门面的类型(构成节点 / 构成计划)和列表栏份数一个常量:spatial/ 从 biz/ 只许读本文件,不能借它把具体组件目录带进来。
8
+ // 只 import shared/page-attrs(类型与闭集,契约校验 kitLayoutContractProblems 用)、排布门面的类型(构成节点 / 构成计划)和列表栏份数一个常量:
9
+ // spatial/ 从 biz/ 只许读本文件,不能借它把具体组件目录带进来。
10
+ // 应用业务组件也可以声明契约(defineKitBizComponent({ layoutContract })):查表顺序为内置冻结表 → 应用声明(编排层传入)→ FREE。
9
11
 
10
12
  import type { CompositionNodeInput, CompositionPlan } from 'soma-foundation/arrange';
11
13
  import type { KitArrange, KitExclusive, KitFunc, KitIdentity, KitPresent, KitRegionKind, KitStripKind } from '../shared/page-attrs';
14
+ import { KIT_ARRANGES, KIT_EXCLUSIVES, KIT_FUNCS, KIT_IDENTITIES, KIT_PRESENTS } from '../shared/page-attrs';
12
15
  import { KIT_LIST_PANE_SPAN } from '../recipes/page-width';
13
16
 
14
17
  /** 声明里表示「这是一个数据对象」的公共键表(展开 / 动作计数 / 界面规则投影 / 层级求解 / 尺寸推导统一共用) */
@@ -740,6 +743,8 @@ export const KIT_BIZ_LAYOUT_CONTRACTS: Readonly<Record<string, KitBizLayoutContr
740
743
  subs: role('secondary', 'tab-face', { attachTo: 'record', exclusiveGroup: 'subs', memberPrefix: 'sub_', anchor: OBJ }),
741
744
  },
742
745
  exclusiveGroups: { subs: 'tabs', edit: 'swap' },
746
+ // 附加浮层(overlays.<名>)容器锚点:与 StandardCrud / MasterSub 同一拼法(共享 compileOverlay 在新模式下写 kitObjectAnchor(浮层对象))
747
+ overlayAnchor: OBJ,
743
748
  rootAnchor: '{page}__rd_root',
744
749
  frameFacts: facts('detail', { detail: true }),
745
750
  }),
@@ -912,7 +917,117 @@ export const KIT_FREE_LAYOUT_CONTRACT: KitBizLayoutContract = contract({
912
917
  frameFacts: facts('free'),
913
918
  });
914
919
 
915
- /** 未登记的业务组件(应用自定义)取缺省:不猜它的版式,交给识别按构成规则推 */
916
- export function kitBizLayoutContract(kind: string): KitBizLayoutContract {
917
- return Object.hasOwn(KIT_BIZ_LAYOUT_CONTRACTS, kind) ? KIT_BIZ_LAYOUT_CONTRACTS[kind]! : KIT_FREE_LAYOUT_CONTRACT;
920
+ /**
921
+ * 业务组件的版式契约:内置冻结表优先;其次应用业务组件在 defineKitBizComponent({ layoutContract }) 里声明的契约
922
+ * (extra:由编排层从 app.bizComponents 收集后传入,spatial/ 不 import 业务组件定义);都没有取缺省 FREE(不猜版式,交给识别按构成规则推)
923
+ */
924
+ export function kitBizLayoutContract(kind: string, extra?: Readonly<Record<string, KitBizLayoutContract>>): KitBizLayoutContract {
925
+ if (Object.hasOwn(KIT_BIZ_LAYOUT_CONTRACTS, kind)) return KIT_BIZ_LAYOUT_CONTRACTS[kind]!;
926
+ if (extra !== undefined && Object.hasOwn(extra, kind)) return extra[kind]!;
927
+ return KIT_FREE_LAYOUT_CONTRACT;
928
+ }
929
+
930
+ // ── 应用业务组件声明的版式契约(defineKitBizComponent({ layoutContract }))────────────────────────────
931
+
932
+ /** 应用声明契约的入参:frameFacts 只写差异(缺省同 FACTS),pageMode 必填 */
933
+ export type KitLayoutContractInput = Omit<KitBizLayoutContract, 'frameFacts'> & {
934
+ readonly frameFacts: Partial<Omit<KitBizLayoutContract['frameFacts'], 'pageMode'>> & { readonly pageMode: KitPageMode };
935
+ };
936
+
937
+ /** 应用声明契约的简写:frameFacts 只写差异(缺省同 FACTS),pageMode 必填;返回冻结的完整契约(合法性由 defineKitBizComponent 定义期校验) */
938
+ export function kitLayoutContract(c: KitLayoutContractInput): KitBizLayoutContract {
939
+ const { pageMode, ...over } = c.frameFacts;
940
+ return contract({
941
+ ...c,
942
+ roles: Object.fromEntries(Object.entries(c.roles).map(([k, r]) => [k, Object.freeze({ ...r })])),
943
+ frameFacts: facts(pageMode, over),
944
+ });
945
+ }
946
+
947
+ /** 页面模式的闭集(与 KitPageMode 一一对应;意图词表逐词对账见 tests/spatial/layout-contracts.test.ts) */
948
+ const PAGE_MODES: readonly KitPageMode[] = Object.freeze(['crud', 'master-detail', 'category', 'board', 'report', 'form', 'detail', 'steps', 'approval', 'settings', 'import', 'result', 'free'] as const);
949
+ const NAV_RAILS: readonly string[] = Object.freeze(['none', 'narrow', 'wide']);
950
+
951
+ const isPlainRec = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
952
+
953
+ /**
954
+ * 版式契约的不变量(冻结表单测 tests/spatial/layout-contracts.test.ts 与 defineKitBizComponent 定义期共用这一份判据)。
955
+ * roles:组件定义的角色表(契约角色键必须与它一一相等)。返回问题清单(空 = 合法),每条带组件名前缀。
956
+ * grid.by: domain 只供内置领域模板:只认 KIT_DOMAIN_TOPOLOGY 里的拓扑(包装 / 组合内置领域模板时原样继承的那份)
957
+ */
958
+ export function kitLayoutContractProblems(kind: string, roles: Readonly<Record<string, unknown>>, c: KitBizLayoutContract): string[] {
959
+ const out: string[] = [];
960
+ if (!isPlainRec(c) || !isPlainRec(c.roles) || !isPlainRec(c.frameFacts)) {
961
+ return [`${kind}:契约必须是对象,且含 roles 与 frameFacts(用 kitLayoutContract({...}) 构造)`];
962
+ }
963
+ const keys = Object.keys(c.roles).sort();
964
+ const want = Object.keys(roles).sort();
965
+ if (keys.join('|') !== want.join('|')) out.push(`契约角色键(${keys.join(' / ') || '无'})与组件角色键(${want.join(' / ') || '无'})不一致`);
966
+ if (!KIT_ARRANGES.includes(c.arrange)) out.push(`arrange "${String(c.arrange)}" 不在闭集`);
967
+ if (!KIT_EXCLUSIVES.includes(c.exclusive)) out.push(`exclusive "${String(c.exclusive)}" 不在闭集`);
968
+ if (typeof c.defaultSelected !== 'boolean') out.push('defaultSelected 必须是布尔');
969
+ if (c.exclusiveGroups !== undefined) {
970
+ const kinds = Object.values(c.exclusiveGroups);
971
+ for (const [g, e] of Object.entries(c.exclusiveGroups)) if (!KIT_EXCLUSIVES.includes(e)) out.push(`exclusiveGroups.${g} "${String(e)}" 不在闭集`);
972
+ if (!kinds.includes(c.exclusive)) out.push(`顶层 exclusive "${String(c.exclusive)}" 必须是 exclusiveGroups 里的一组`);
973
+ }
974
+ for (const [name, r] of Object.entries(c.roles)) {
975
+ if (!isPlainRec(r)) { out.push(`roles.${name} 必须是对象`); continue; }
976
+ if (!KIT_IDENTITIES.includes(r.identity)) out.push(`roles.${name}.identity "${String(r.identity)}" 不在闭集`);
977
+ if (r.present !== 'unset' && !KIT_PRESENTS.includes(r.present)) out.push(`roles.${name}.present "${String(r.present)}" 不在闭集`);
978
+ if (typeof r.inset !== 'boolean') out.push(`roles.${name}.inset 必须是布尔`);
979
+ if (r.attachTo !== undefined && (!Object.hasOwn(c.roles, r.attachTo) || r.attachTo === name)) out.push(`roles.${name}.attachTo 必须指向另一个已登记角色`);
980
+ if (r.exclusiveGroup !== undefined && c.exclusiveGroups !== undefined && !Object.hasOwn(c.exclusiveGroups, r.exclusiveGroup)) out.push(`roles.${name}.exclusiveGroup "${r.exclusiveGroup}" 未在 exclusiveGroups 登记`);
981
+ for (const f of r.defaultActions ?? []) if (!KIT_FUNCS.includes(typeof f === 'string' ? f : f.func)) out.push(`roles.${name}.defaultActions 含未知功能`);
982
+ for (const a of [r.anchor, r.editAnchor, ...Object.values(r.stripAnchors ?? {}), ...(r.rowActionAnchors ?? [])]) {
983
+ if (a !== undefined && (typeof a !== 'string' || (!a.includes('{page}') && !a.includes('{object}')))) out.push(`roles.${name} 的锚点拼法 "${String(a)}" 必须含 {page} 或 {object} 占位(同页多槽不撞)`);
984
+ }
985
+ }
986
+ const all = Object.values(c.roles).filter(isPlainRec);
987
+ const primaries = all.filter((r) => r.identity === 'primary').length;
988
+ if (primaries > 1 && !all.some((r) => r.identity === 'peers')) out.push('主对象(identity: primary)至多一个,除非另有平级组');
989
+ if (c.rootAnchor !== undefined && (typeof c.rootAnchor !== 'string' || !c.rootAnchor.includes('{page}'))) out.push('rootAnchor 必须含 {page} 占位');
990
+ if (c.overlayAnchor !== undefined && (typeof c.overlayAnchor !== 'string' || (!c.overlayAnchor.includes('{page}') && !c.overlayAnchor.includes('{object}')))) out.push('overlayAnchor 必须含 {page} 或 {object} 占位');
991
+ const ff = c.frameFacts;
992
+ if (!PAGE_MODES.includes(ff.pageMode)) out.push(`frameFacts.pageMode "${String(ff.pageMode)}" 不在闭集`);
993
+ if (!Number.isInteger(ff.panes) || ff.panes < 1) out.push('frameFacts.panes 必须是不小于 1 的整数');
994
+ if (!NAV_RAILS.includes(ff.navRail)) out.push(`frameFacts.navRail "${String(ff.navRail)}" 不在闭集(none / narrow / wide)`);
995
+ for (const k of ['stepper', 'reading', 'showcase', 'detail'] as const) if (typeof ff[k] !== 'boolean') out.push(`frameFacts.${k} 必须是布尔`);
996
+ if (c.grid !== undefined && c.grid.by === 'domain' && !Object.values(KIT_DOMAIN_TOPOLOGY).includes(c.grid.topology)) {
997
+ out.push('grid.by: domain 只供内置领域模板;应用组件用 fixed / board 或不写');
998
+ }
999
+ return out.map((m) => `${kind}:${m}`);
1000
+ }
1001
+
1002
+ /**
1003
+ * 把子部件的契约改写成复合组件里的样子(composeKitBizComponents 缺省合成契约用):
1004
+ * 子部件以 `${pageId}_${part}` 为前缀编译(compose.ts 的 subCtx),对象运行期名是 `<页>_<子部件>_<子角色>`(分组成员 `<页>_<子部件>_<成员前缀><成员名>`),
1005
+ * 而展开按复合组件的对外角色拼 `{object}`(`<页>_<对外角色>`)。所以锚点拼法里的 `{object}` 先按子角色写成字面前缀,`{page}` 换成 `{page}_<子部件>`;
1006
+ * 角色名按 roleMap 改名(未映射的可选角色不出现)、互斥组加子部件前缀。
1007
+ * 已知限制:对象渲染器的宿主锚点(工具条按钮、行操作等,KIT_HOST_ANCHOR_PATTERN)由展开按对外角色的运行期名拼,与子部件产物对不上,会报「没有落到产物上」的 KIT-PAGE-GATE-006
1008
+ */
1009
+ export function kitRebaseLayoutContract(
1010
+ c: KitBizLayoutContract, roleMap: Readonly<Record<string, string>>, part: string,
1011
+ ): { roles: Record<string, KitRoleLayout>; exclusiveGroups: Record<string, KitExclusive>; overlayAnchor?: string } {
1012
+ const rebase = (s: string, objectAs: string): string => s.split('{object}').join(objectAs).split('{page}').join(`{page}_${part}`);
1013
+ const roles: Record<string, KitRoleLayout> = {};
1014
+ for (const [inner, r] of Object.entries(c.roles)) {
1015
+ const outer = roleMap[inner];
1016
+ if (outer === undefined) continue; // 未映射的可选角色不出现在复合组件里
1017
+ // 子部件里这个角色对象的运行期名(改写前的拼法,下一步统一把 {page} 换成 {page}_<子部件>)
1018
+ const objectAs = r.memberPrefix !== undefined ? `{page}_${r.memberPrefix}{member}` : `{page}_${inner}`;
1019
+ const re = (s: string): string => rebase(s, objectAs);
1020
+ roles[outer] = Object.freeze({
1021
+ ...r,
1022
+ ...(r.attachTo !== undefined ? { attachTo: roleMap[r.attachTo] ?? r.attachTo } : {}),
1023
+ ...(r.exclusiveGroup !== undefined ? { exclusiveGroup: `${part}.${r.exclusiveGroup}` } : {}),
1024
+ ...(r.anchor !== undefined ? { anchor: re(r.anchor) } : {}),
1025
+ ...(r.editAnchor !== undefined ? { editAnchor: re(r.editAnchor) } : {}),
1026
+ ...(r.stripAnchors !== undefined ? { stripAnchors: Object.freeze(Object.fromEntries(Object.entries(r.stripAnchors).map(([k, v]) => [k, re(v)]))) } : {}),
1027
+ ...(r.rowActionAnchors !== undefined ? { rowActionAnchors: Object.freeze(r.rowActionAnchors.map((a) => re(a))) } : {}),
1028
+ });
1029
+ }
1030
+ const exclusiveGroups = Object.fromEntries(Object.entries(c.exclusiveGroups ?? {}).map(([g, e]) => [`${part}.${g}`, e]));
1031
+ // 附加浮层对象的运行期名是 `<页>_<浮层名>`(展开里 member = 浮层名)
1032
+ return { roles, exclusiveGroups, ...(c.overlayAnchor !== undefined ? { overlayAnchor: rebase(c.overlayAnchor, '{page}_{member}') } : {}) };
918
1033
  }
@@ -4,6 +4,7 @@
4
4
  // KitCoordinator focus 切片 owner:表单弹窗开关与初值、保存 / 重取 / 删除、kit_pick(写选中键与新建预填并重取)
5
5
  // KitLinkHub selection 切片 owner(MasterSub)或只读订阅者(CategoryCrud,分类树自己写):
6
6
  // · 行选中(语义事件 link_pick,载荷带整行)→ 写 selection;行数据到达时默认选首行(autoSelect);
7
+ // 页面指定了选中键(preferKey,MasterSub master.selectedFrom 绑地址参数)时先选主键等于它的行,找不到再回落首行;
7
8
  // · 选中项一变(不论谁写的):把依赖对象的 view 切片回第 1 页(经路径写者 `page`),等镜像落地后上抛 picked { id, item, prefill },
8
9
  // 页面再接 `SCOPE | window-reload`(MasterSub)或 `SCOPE | semantic kit_pick`(CategoryCrud,交给协调组件写预填并重取);
9
10
  // · 摘要字段动作(语义事件 link_field_<序号>):字段事件自己的载荷只有 { value },由本组件补上当前选中行后抛槽位事件 field_action_<序号> { value, row },
@@ -94,6 +95,15 @@ export function pickDefault(
94
95
  return JSON.stringify(next) === JSON.stringify(current) ? undefined : next;
95
96
  }
96
97
 
98
+ /**
99
+ * 页面指定的初始选中(MasterSub master.selectedFrom,绑地址参数):行里主键等于 prefer 的那一行;
100
+ * prefer 为空 / 行里没有它返回 undefined(调用方回落到 pickDefault 的现有行为)
101
+ */
102
+ export function pickPreferred(rows: readonly unknown[], prefer: string | null, keyField: string): Rec | undefined {
103
+ if (prefer === null || prefer === '') return undefined;
104
+ return rows.filter(isRec).find((r) => linkKeyOf(r, keyField) === prefer);
105
+ }
106
+
97
107
  /** 新建时的预填:关联键 = 当前选中项的主键 */
98
108
  export function createPrefill(selected: unknown, keyField: string, linkKey: string): Rec {
99
109
  if (linkKey === '' || keyField === '' || !isRec(selected)) return {};
@@ -122,6 +132,7 @@ export function createKitLinkHub(): SomaComponentDefinition {
122
132
  createObjects: { type: 'object', default: {}, desc: '新建保存成功回第 1 页后要发起第 1 页重取的映射(scopeId -> objectName);仅对原 view.page > 1 的作用域回页并重取' },
123
133
  pickSlots: { type: 'number', default: 0, desc: '选中项变化时依次抛 picked_0 … picked_<n-1> 的个数(每个依赖对象的重取各绑一个槽位;0 = 只抛 picked)' },
124
134
  watchFilters: { type: 'array', default: [], desc: '筛选条的作用域 id:它们的 filter 切片一变(每次提交 / 重置都算,值没变也算)就回第 1 页并上抛 picked,页面据此重取(MultiObjectBoard 的全局筛选)' },
135
+ preferKey: { type: 'string', default: '', desc: '页面指定的选中键(MasterSub master.selectedFrom 编成的页面路径绑定,如 page.query.task_id;值按字符串比对主键):行数据到达时选中主键等于它的行,找不到回落 autoSelect 的现有行为;它变化时重新对齐一次(用户点选后的行数据刷新不会被它拉回)' },
125
136
  },
126
137
  emits: {
127
138
  picked: { payload: { id: { type: 'string' }, item: { type: 'object' }, prefill: { type: 'object' } }, desc: '选中项变化(页面据此重取依赖对象)' },
@@ -292,6 +303,14 @@ export function createKitLinkHub(): SomaComponentDefinition {
292
303
  }));
293
304
  };
294
305
 
306
+ /** 页面指定的选中键(preferKey 绑地址参数,整数参数到这里是 number):空 / 未绑到值为 null */
307
+ const preferOf = (): string | null => {
308
+ const v = props().preferKey;
309
+ return typeof v === 'string' ? (v === '' ? null : v) : typeof v === 'number' && Number.isFinite(v) ? String(v) : null;
310
+ };
311
+ /** 已对齐过的页面指定键:同一个值只在首批非空行到达时对齐一次,之后行刷新不再把用户点选拉回;值变了(地址参数变化)再对齐一次 */
312
+ let appliedPrefer: string | null = null;
313
+
295
314
  const syncDefault = (): void => {
296
315
  const p = props();
297
316
  if (p.autoSelect !== true && p.autoSelect !== 'true') return;
@@ -300,6 +319,18 @@ export function createKitLinkHub(): SomaComponentDefinition {
300
319
  const rows = Array.isArray(p.rows) ? p.rows : [];
301
320
  const previous = lastRows;
302
321
  lastRows = rows;
322
+ const prefer = preferOf();
323
+ if (prefer === null) {
324
+ appliedPrefer = null;
325
+ } else if (prefer !== appliedPrefer && rows.some(isRec)) {
326
+ // 行到了才算对齐过:找到就选它,找不到回落下面的现有行为(保留仍在行里的当前项 / 首行)
327
+ appliedPrefer = prefer;
328
+ const hit = pickPreferred(rows, prefer, keyField());
329
+ if (hit !== undefined) {
330
+ if (JSON.stringify(hit) !== JSON.stringify(selectedOf(sel.get()))) setSelection(hit);
331
+ return;
332
+ }
333
+ }
303
334
  const next = pickDefault(rows, selectedOf(sel.get()), keyField(), p.afterRemove === 'next' ? { afterRemove: 'next', previous } : undefined);
304
335
  if (next !== undefined) setSelection(next);
305
336
  };
@@ -1,7 +1,9 @@
1
1
  // MasterSubWorkstation 编译:左栏主列表 + 右栏主对象摘要与多个从属对象(规格 5.3)。
2
2
  // 对象渲染全部交 emitObject;本文件只做壳和写死的协作链:
3
3
  //
4
- // 初次加载默认选中首条 KitLinkHub 的 rows(绑主列表行数据)到达时选首行
4
+ // 初次加载默认选中首条 KitLinkHub 的 rows(绑主列表行数据)到达时选首行;master.selectedFrom($page.params.* / $page.query.*)
5
+ // 编成枢纽 preferKey(页面路径绑定):先选主键相等的行,找不到回落首行,地址参数变化时再对齐;
6
+ // master.selectAction:枢纽 picked 事件接具名动作(如回写地址参数)
5
7
  // 切换选中行 行点击(pickOnRow,kit_action: select)-> SCOPE semantic link_pick -> 枢纽写 selection
6
8
  // -> 摘要读 selection 镜像(summaryPath);各从属对象 from.params 带关联键(link_sel_key);
7
9
  // 枢纽抛 picked -> 页面对每个从属对象 `SCOPE | window-reload` 并行重取(回第 1 页由枢纽经 page 路径写者完成)
@@ -31,7 +33,7 @@ import { OVERLAY_SHELL_CLASS, dialogHtml, dialogIds } from '../shared/overlay-sh
31
33
  import { applyFlowCopy } from '../shared/verbs';
32
34
  import { dialogWidthOf, editContainerOf } from '../../object-renderer/overlay-decide';
33
35
  import { PAGE_FORM_FOCUS_INITIAL, pageBrowsingMirror, wireMainPageForm } from '../shared/page-form';
34
- import { KIT_CRUD_LINK_KEY, adviseDialogFooter, compileOverlay, validateOverlayNames } from '../shared/overlay-compile';
36
+ import { KIT_CRUD_LINK_KEY, adviseDialogFooter, compileOverlay, isAutoRowlessOverlay, validateOverlayNames } from '../shared/overlay-compile';
35
37
  import type { KitAction } from '../../object-renderer/types';
36
38
  import { KIT_LINK_MIRRORS, KIT_NONE_PATH, KIT_SEL_PATH } from '../link/hub';
37
39
  import {
@@ -51,6 +53,9 @@ export function masterSubObjectName(pageId: string, role: string): string {
51
53
  return bizObjectName(pageId, role);
52
54
  }
53
55
 
56
+ /** master.selectedFrom 的合法写法:地址路径参数或查询参数(名与 page.params / page.query 的命名规则一致) */
57
+ const SELECTED_FROM = /^\$page\.(params|query)\.[a-z][a-z0-9_]{0,31}$/;
58
+
54
59
  /** 详情头记录卡的 map 占位键:数据里没有它,卡就不画对应项(标题 / 状态让给详情头) */
55
60
  const HEADLESS_KEY = '__ms_head__';
56
61
 
@@ -273,6 +278,34 @@ export function compileMasterSub(input: KitBizInput, ctx: KitBizContext): KitFra
273
278
  else if (!isStatic) fail('KIT-PAGE-001', `subs.${n} 是详情头成员,必须是写死形状组件(StatGroup / RecordCard 等 staticComponent)`, `product.objects.subs.${n}.view`);
274
279
  }
275
280
  }
281
+ // 页面指定的初始选中(selectedFrom:$page.params.<名> / $page.query.<名>)与选中变化后执行的具名动作(selectAction,如回写地址参数)
282
+ const selectedFromRaw = (rawMaster as Rec).selectedFrom;
283
+ let preferKey: string | undefined;
284
+ if (selectedFromRaw !== undefined) {
285
+ if (typeof selectedFromRaw !== 'string' || !SELECTED_FROM.test(selectedFromRaw)) {
286
+ fail('KIT-BIZ-003', `master.selectedFrom 取值 ${JSON.stringify(selectedFromRaw)} 不合法:只许 $page.params.<名> 或 $page.query.<名>(地址参数决定初始选中的主记录)`, 'product.objects.master.selectedFrom');
287
+ } else {
288
+ // 引用的参数必须在 page.params / page.query 里声明(上下文带了声明名才校验;没带时跳过,不误报)
289
+ const [, kindOf, pname] = selectedFromRaw.split('.') as [string, 'params' | 'query', string];
290
+ const declared = kindOf === 'params' ? ctx.pageParams : ctx.pageQuery;
291
+ if (declared !== undefined && !declared.includes(pname)) {
292
+ fail('KIT-PAGE-004', `master.selectedFrom 引用的 ${selectedFromRaw} 未在 page.${kindOf} 里声明(已声明:${declared.length > 0 ? declared.join(' / ') : '无'})`, 'product.objects.master.selectedFrom');
293
+ }
294
+ // 编成枢纽 prop 的页面路径绑定(core 首段是页面变量即按路径读,地址参数变化时随之更新)
295
+ preferKey = selectedFromRaw.slice(1);
296
+ }
297
+ }
298
+ const selectActionRaw = (rawMaster as Rec).selectAction;
299
+ let selectAction: string | undefined;
300
+ if (selectActionRaw !== undefined) {
301
+ if (typeof selectActionRaw !== 'string' || selectActionRaw === '') {
302
+ fail('KIT-BIZ-003', 'master.selectAction 必须是非空字符串(应用登记的具名动作名)', 'product.objects.master.selectAction');
303
+ } else if (!ctx.registeredActions.has(selectActionRaw)) {
304
+ fail('KIT-EVT-001', `master.selectAction "${selectActionRaw}" 未在应用的具名动作中登记`, 'product.objects.master.selectAction');
305
+ } else {
306
+ selectAction = selectActionRaw;
307
+ }
308
+ }
276
309
  if (out.diagnostics.length > 0) return finishBizCompile(out, '');
277
310
 
278
311
  const ids = masterSubIds(ctx.pageId);
@@ -490,10 +523,14 @@ export function compileMasterSub(input: KitBizInput, ctx: KitBizContext): KitFra
490
523
  const overlayObjects: Record<string, string> = {};
491
524
  /** 编辑表单按容器公式得整页的附加浮层(协调组件 pageOverlays) */
492
525
  const pageOverlays: string[] = [];
526
+ const rowTriggeredOverlays = new Set<string>([...Object.values(overlayActions), ...Object.values(showEdit)]);
527
+ const rowlessOverlays = new Set<string>(
528
+ Object.entries(overlays).filter(([n, d]) => isAutoRowlessOverlay(d, rowTriggeredOverlays.has(n))).map(([n]) => n),
529
+ );
493
530
  const EDIT_LABEL = kitText('soma.kit.edit', undefined, ctx.locale);
494
531
  for (const [name, decl] of Object.entries(overlays)) {
495
532
  const compiled = compileOverlay(
496
- { out, ctx, scope: link, object: masterName, keyField: masterKey, actions: requestPool, areaClass, closeLabel: CLOSE_LABEL, cancelLabel: CANCEL_LABEL, editLabel: EDIT_LABEL, showEdit },
533
+ { out, ctx, scope: link, object: masterName, keyField: masterKey, actions: requestPool, areaClass, closeLabel: CLOSE_LABEL, cancelLabel: CANCEL_LABEL, editLabel: EDIT_LABEL, showEdit, ...(rowlessOverlays.size > 0 ? { rowless: rowlessOverlays } : {}) },
497
534
  name,
498
535
  decl,
499
536
  );
@@ -517,6 +554,7 @@ export function compileMasterSub(input: KitBizInput, ctx: KitBizContext): KitFra
517
554
  out.show[ids.subs] = { when: mirrorPath(link, KIT_LINK_MIRRORS.selHas) };
518
555
  out.show[ids.empty] = { when: mirrorPath(link, KIT_LINK_MIRRORS.selNone) };
519
556
  for (const x of [mk.openForm, mk.creating, mk.editing, mk.mode, mk.row, mk.id, mk.sel]) mirrors.push({ key: x.key, slice: 'focus', path: x.path, as: x.as });
557
+ if (rowlessOverlays.size > 0) mirrors.push({ key: mk.ovMode.key, slice: 'focus', path: mk.ovMode.path, as: mk.ovMode.as });
520
558
  mirrors.push(...overlayMirrors);
521
559
  if (Object.keys(overlayObjects).length > 0) mirrors.push({ key: KIT_CRUD_LINK_KEY, slice: 'focus', path: `row.${masterKey}`, as: 'value' });
522
560
  // 新建 / 编辑表单(只有主对象有)的容器由公式推出(KT-P-window):对话框,或同页切换的整页表单视图;
@@ -570,8 +608,12 @@ export function compileMasterSub(input: KitBizInput, ctx: KitBizContext): KitFra
570
608
  scope: link, keyField: masterKey, linkKey: '', autoSelect: true, rows: rowsPath, pageScopes,
571
609
  ...(createScopes.length > 0 ? { createScopes } : {}),
572
610
  ...(Object.keys(createObjects).length > 0 ? { createObjects } : {}),
611
+ // 页面指定的选中键(selectedFrom):不声明时不带,产物与改前一致
612
+ ...(preferKey !== undefined ? { preferKey } : {}),
573
613
  },
574
614
  };
615
+ // 选中变化(含默认选中、地址参数对齐):枢纽的 picked { id, item, prefill } 交具名动作(如回写地址参数);picked_<序号> 槽位仍各管各的重取
616
+ if (selectAction !== undefined) out.events[`${ids.hub}.picked`] = `ACTION | ${selectAction}`;
575
617
  out.show[ids.coord] = {
576
618
  props: {
577
619
  scope: link, objectScope: masterScope, object: masterName, keyField: masterKey, reloads: reloadTargets.map((s) => s.object), overlays: overlayObjects, showEdit, rowsPath: m.r.compiled.listShape.rows,
@@ -9,7 +9,9 @@ export const MasterSubWorkstation = defineKitBizComponent({
9
9
  kind: 'MasterSubWorkstation',
10
10
  roles: {
11
11
  // unselectedText:没有选中主行时从属区整区空态的文案(缺省取内置「请选择左侧记录」)
12
- master: { required: true, views: ['filter', 'list', 'summary', 'form'], extraKeys: ['unselectedText'] },
12
+ // selectedFrom:页面指定初始选中的主记录($page.params.<名> / $page.query.<名>,主键相等的行;找不到回落首行)
13
+ // selectAction:选中变化后执行的具名动作(载荷 { id, item, prefill },如回写地址参数)
14
+ master: { required: true, views: ['filter', 'list', 'summary', 'form'], extraKeys: ['unselectedText', 'selectedFrom', 'selectAction'] },
13
15
  // group:详情里的分组名(同名从属收进页内页签的同一签;不写 group 的常显在页签之上)
14
16
  subs: { required: true, views: ['list', 'summary'], many: true, extraKeys: ['group'] },
15
17
  aside: { required: false, views: ['list', 'summary'] },
@@ -108,6 +108,9 @@ export function compileMultiBoard(input: KitBizInput, ctx: KitBizContext): KitFr
108
108
  if (s.group !== undefined && (typeof s.group !== 'string' || s.group.trim() === '')) {
109
109
  fail('KIT-PAGE-001', `panels.${n}.group 必须是非空字符串(面板组名,同名面板收进页内页签的同一签)`, `${at}.group`);
110
110
  }
111
+ if (s.whenEmpty !== undefined && s.whenEmpty !== 'show' && s.whenEmpty !== 'hide') {
112
+ fail('KIT-PAGE-001', `panels.${n}.whenEmpty 只许写 show(缺省:空了显示空态)或 hide(主体只剩空态时整块面板不渲染,数据回来再出现)`, `${at}.whenEmpty`);
113
+ }
111
114
  if (s.head !== undefined) {
112
115
  const host = typeof s.head === 'string' ? s.head.trim() : '';
113
116
  const hostRaw = host === '' ? undefined : rawPanels[host];
@@ -118,7 +121,7 @@ export function compileMultiBoard(input: KitBizInput, ctx: KitBizContext): KitFr
118
121
  } else if (!isStatic) {
119
122
  fail('KIT-PAGE-001', `panels.${n} 是面板头控件,必须是写死形状组件(staticComponent:SegmentedSwitch / MetaAction / ScopeSwitch 等)`, `${at}.view`);
120
123
  }
121
- for (const k of ['title', 'span', 'class', 'group'] as const) {
124
+ for (const k of ['title', 'span', 'class', 'group', 'whenEmpty'] as const) {
122
125
  if (s[k] !== undefined) fail('KIT-PAGE-001', `panels.${n} 是面板头控件,不写 ${k}(位置与分组随宿主面板 "${host}")`, `${at}.${k}`);
123
126
  }
124
127
  }
@@ -280,6 +283,7 @@ export function compileMultiBoard(input: KitBizInput, ctx: KitBizContext): KitFr
280
283
  ...(p.class !== '' ? { class: p.class } : {}),
281
284
  ...(p.group !== '' ? { group: p.group } : {}),
282
285
  ...(next ? { object: p.object } : {}),
286
+ ...((rawPanels[p.name] as unknown as Rec).whenEmpty === 'hide' ? { hideWhenEmpty: true } : {}),
283
287
  };
284
288
  // 构成分析附着(作者没写 head):控件进宿主标题行、宽条筛选作整宽顶带 top-band、说明并为宿主页脚;宿主不是独立面板时在下面退回独立成块
285
289
  const att = pl?.attach;
@@ -13,7 +13,7 @@ import { KIT_NOTICE_BOX_FOOTER, KIT_NOTICE_LIST, KIT_NOTICE_TOGGLE_FOOTER } from
13
13
  import { kitTypographyRecipe } from '../../recipes/typography';
14
14
  import { mergeClass } from '../../shared/merge-class';
15
15
  import {
16
- KIT_ATTR_BOARD, KIT_ATTR_BOARD_PANEL, KIT_ATTR_EMPTY_COLLAPSED, KIT_ATTR_NOTICE, KIT_ATTR_NOTICE_FOOTER, KIT_ATTR_PART, KIT_ATTR_PROSE_FOLDED,
16
+ KIT_ATTR_ACTION_GROUP, KIT_ATTR_BOARD, KIT_ATTR_BOARD_PANEL, KIT_ATTR_BOARD_PANEL_WHEN_EMPTY, KIT_ATTR_EMPTY_COLLAPSED, KIT_ATTR_HOST_EMPTY, KIT_ATTR_NOTICE, KIT_ATTR_NOTICE_FOOTER, KIT_ATTR_PANEL_FOOTER, KIT_ATTR_PANEL_HEAD, KIT_ATTR_PART, KIT_ATTR_PROSE_FOLDED,
17
17
  KIT_ATTR_PROSE_FOOTER, KIT_ATTR_SKELETON, KIT_ATTR_STATE, kitAttrSel,
18
18
  } from '../../shared/dom-attrs';
19
19
  import { kitText } from '../../i18n/kit-text';
@@ -46,9 +46,11 @@ function proseIn(panel: HTMLElement): HTMLElement[] {
46
46
  const EMPTY_ATTR = KIT_ATTR_EMPTY_COLLAPSED;
47
47
  const CONTENT = `svg, canvas, img, video, table, input, select, textarea, button, a, [role="img"], [role="progressbar"], ${kitAttrSel(KIT_ATTR_STATE)}, ${kitAttrSel(KIT_ATTR_SKELETON)}, [aria-busy="true"]`;
48
48
 
49
- /** el 到 panel 之间(不含 panel 自己)没有被 hidden 的祖先 */
49
+ /** el 到 panel 之间(不含 panel 自己)没有被 hidden 或 Tailwind .hidden 藏起的祖先 */
50
50
  function shownWithin(el: HTMLElement, panel: HTMLElement): boolean {
51
- for (let n: HTMLElement | null = el; n !== null && n !== panel; n = n.parentElement) if (n.hidden) return false;
51
+ for (let n: HTMLElement | null = el; n !== null && n !== panel; n = n.parentElement) {
52
+ if (n.hidden || n.classList.contains('hidden')) return false;
53
+ }
52
54
  return true;
53
55
  }
54
56
 
@@ -62,8 +64,73 @@ export function panelHasContent(panel: HTMLElement): boolean {
62
64
  return false;
63
65
  }
64
66
 
67
+ // ── 声明了 whenEmpty: hide 的面板:主体只剩空态(内置空态块或成员自报为空)且不在加载中 / 报错、无其它可见数据时整块收起,数据回来再还原
68
+ const WHEN_EMPTY_HIDE = kitAttrSel(KIT_ATTR_BOARD_PANEL_WHEN_EMPTY, 'hide');
69
+ const EMPTY_MARK = `${kitAttrSel(KIT_ATTR_STATE, 'empty')}, ${kitAttrSel(KIT_ATTR_HOST_EMPTY)}`;
70
+ const BUSY_MARK = `${kitAttrSel(KIT_ATTR_STATE, 'loading')}, ${kitAttrSel(KIT_ATTR_SKELETON)}, [aria-busy="true"]`;
71
+ const ERROR_MARK = `${kitAttrSel(KIT_ATTR_STATE, 'error')}, [role="alert"]`;
72
+ // 面板壳外围部件(标题 / 标题行工具条 / 头控件 / 页脚)与空态块自身子树:不计作「空态之外的主体数据内容」
73
+ const EMPTY_SHELL_EXEMPT = [
74
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
75
+ `[${KIT_ATTR_PART}^="title"]`,
76
+ kitAttrSel(KIT_ATTR_PANEL_HEAD),
77
+ kitAttrSel(KIT_ATTR_ACTION_GROUP),
78
+ kitAttrSel(KIT_ATTR_PANEL_FOOTER),
79
+ kitAttrSel(KIT_ATTR_PROSE_FOOTER),
80
+ kitAttrSel(KIT_ATTR_NOTICE_FOOTER),
81
+ EMPTY_MARK,
82
+ ].join(', ');
83
+
84
+ /** 紧邻空态块之前的纯装饰图标(aria-hidden="true",如 KitCollectionState 的空收件箱图标) */
85
+ function isEmptyCompanionIcon(el: HTMLElement, panel: HTMLElement): boolean {
86
+ for (let n: HTMLElement | null = el; n !== null && n !== panel; n = n.parentElement) {
87
+ if (n.getAttribute('aria-hidden') === 'true' && n.nextElementSibling instanceof HTMLElement && n.nextElementSibling.matches(EMPTY_MARK)) {
88
+ return true;
89
+ }
90
+ }
91
+ return false;
92
+ }
93
+
94
+ /**
95
+ * 面板主体此刻是否「只剩空态」:
96
+ * 1. 存在可见的加载态或报错态 → false(加载中与报错绝不隐藏面板);
97
+ * 2. 不存在可见的空态标记 → false;
98
+ * 3. 排除标题 / 标题行工具条 / 头控件 / 页脚与空态子树后,若仍存在任何可见真实内容(图形 / 表格 / 表单控件 / 链接 / 按钮 / 非空白文字)→ false。
99
+ */
100
+ export function panelIsEmptyState(panel: HTMLElement): boolean {
101
+ const shown = (sel: string): boolean => Array.from(panel.querySelectorAll<HTMLElement>(sel)).some((el) => shownWithin(el, panel));
102
+ if (shown(BUSY_MARK) || shown(ERROR_MARK)) return false;
103
+ if (!shown(EMPTY_MARK)) return false;
104
+ for (const node of Array.from(panel.childNodes)) {
105
+ if (node.nodeType === 3 && (node.textContent ?? '').trim() !== '') return false;
106
+ }
107
+ for (const el of Array.from(panel.querySelectorAll<HTMLElement>('*'))) {
108
+ if (!shownWithin(el, panel)) continue;
109
+ const exempt = el.closest(EMPTY_SHELL_EXEMPT);
110
+ if (exempt !== null && panel.contains(exempt) && exempt !== panel) continue;
111
+ if (isEmptyCompanionIcon(el, panel)) continue;
112
+ if (el.matches(CONTENT)) return false;
113
+ for (const node of Array.from(el.childNodes)) {
114
+ if (node.nodeType === 3 && (node.textContent ?? '').trim() !== '') return false;
115
+ }
116
+ }
117
+ return true;
118
+ }
119
+
65
120
  function collapseEmpty(board: HTMLElement): void {
66
121
  for (const panel of Array.from(board.querySelectorAll<HTMLElement>(PANEL))) {
122
+ if (panel.matches(WHEN_EMPTY_HIDE)) {
123
+ const byUs = panel.hasAttribute(EMPTY_ATTR);
124
+ if (panel.hidden && !byUs) continue; // 别人收起的不动
125
+ if (panelIsEmptyState(panel)) {
126
+ panel.hidden = true;
127
+ panel.setAttribute(EMPTY_ATTR, '');
128
+ } else if (byUs) {
129
+ panel.hidden = false;
130
+ panel.removeAttribute(EMPTY_ATTR);
131
+ }
132
+ continue;
133
+ }
67
134
  if (panel.getAttribute(KIT_ATTR_BOARD_PANEL) !== 'bare') continue;
68
135
  const collapsedByUs = panel.hasAttribute(EMPTY_ATTR);
69
136
  if (panel.hidden && !collapsedByUs) continue; // 别人(kitCollapseBlock)收起的不动
@@ -118,6 +185,12 @@ function scan(board: HTMLElement): void {
118
185
  }
119
186
  }
120
187
 
188
+ /** 观察范围:结构与文字变化,外加空态 / 加载中 / 报错标记与 hidden 的切换(whenEmpty: hide 的面板靠它们判空) */
189
+ const OBSERVE: MutationObserverInit = {
190
+ childList: true, subtree: true, characterData: true,
191
+ attributes: true, attributeFilter: ['hidden', 'aria-busy', 'role', KIT_ATTR_STATE, KIT_ATTR_HOST_EMPTY],
192
+ };
193
+
121
194
  export function createKitBoardProse(): SomaComponentDefinition {
122
195
  return {
123
196
  contract: { name: 'KitBoardProse', layer: 'data', props: {} },
@@ -132,11 +205,11 @@ export function createKitBoardProse(): SomaComponentDefinition {
132
205
  const run = (): void => {
133
206
  frame = 0;
134
207
  observer?.disconnect();
135
- try { scan(board); } finally { observer?.observe(board, { childList: true, subtree: true, characterData: true }); }
208
+ try { scan(board); } finally { observer?.observe(board, OBSERVE); }
136
209
  };
137
210
  const queue = (): void => { if (frame === 0) frame = board.ownerDocument.defaultView?.requestAnimationFrame(run) ?? 0; };
138
211
  observer = new MutationObserver(queue);
139
- observer.observe(board, { childList: true, subtree: true, characterData: true });
212
+ observer.observe(board, OBSERVE);
140
213
  queue();
141
214
  return () => { observer?.disconnect(); observer = null; };
142
215
  },