soma-kit 0.1.4 → 0.1.5

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soma-kit",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "SOMA 第三条 UI 路线:写死模板与规则,DSL 显式传入,基础组件 + 数据组件",
5
5
  "type": "module",
6
6
  "exports": {
@@ -48,8 +48,8 @@
48
48
  "next": "16.4.1",
49
49
  "react": "18.3.1",
50
50
  "react-dom": "18.3.1",
51
- "soma-core": "^2.1.5",
52
- "soma-foundation": "^0.1.1",
51
+ "soma-core": "^2.1.6",
52
+ "soma-foundation": "^0.1.2",
53
53
  "tailwindcss": "^4.1.0"
54
54
  },
55
55
  "devDependencies": {
@@ -122,17 +122,40 @@ export function registerKitAppEnvelopeFromYaml(appYamlText: string): void {
122
122
  appEnvelope = env;
123
123
  }
124
124
 
125
- /** 把有效信封编进一份 core 数据声明(`data:` 段):写通道与取数来源各加 failWhen / messagePath,已自带的不覆盖 */
125
+ /**
126
+ * 拼装业务信封子路径(纯函数):
127
+ * - 若 dataPath === undefined || dataPath === '',返回 subPath;
128
+ * - 若 subPath === '',返回 dataPath;
129
+ * - 向后兼容守卫:若 subPath === dataPath || subPath.startsWith(`${dataPath}.`),直接返回 subPath(避免重复拼成 data.data.rows);
130
+ * - 否则返回 `${dataPath}.${subPath}`。
131
+ */
132
+ export function resolveEnvelopeSubPath(subPath: string, dataPath?: string): string {
133
+ if (dataPath === undefined || dataPath === '') return subPath;
134
+ if (subPath === '') return dataPath;
135
+ if (subPath === dataPath || subPath.startsWith(`${dataPath}.`)) return subPath;
136
+ return `${dataPath}.${subPath}`;
137
+ }
138
+
139
+ /** 把有效信封编进一份 core 数据声明(`data:` 段):写通道与取数来源各加 failWhen / messagePath,单对象取数来源补 dataPath,已自带的不覆盖 */
126
140
  export function applyEnvelopeToData(data: Record<string, unknown>, env: KitEnvelope | undefined): void {
127
- if (env?.failWhen === undefined) return;
141
+ if (env === undefined || (env.failWhen === undefined && env.dataPath === undefined)) return;
128
142
  for (const decl of Object.values(data)) {
129
143
  if (!isRec(decl)) continue;
130
144
  const stamp = (target: Rec): void => {
131
- if (target.failWhen !== undefined) return;
132
- target.failWhen = env.failWhen;
133
- if (env.messagePath !== undefined) target.messagePath = env.messagePath;
145
+ if (env.failWhen !== undefined && target.failWhen === undefined) {
146
+ target.failWhen = env.failWhen;
147
+ if (env.messagePath !== undefined) target.messagePath = env.messagePath;
148
+ }
134
149
  };
135
150
  if (isRec(decl.write)) stamp(decl.write);
136
- if (Array.isArray(decl.from)) for (const source of decl.from) if (isRec(source)) stamp(source);
151
+ if (Array.isArray(decl.from)) {
152
+ for (const source of decl.from) {
153
+ if (!isRec(source)) continue;
154
+ stamp(source);
155
+ if (env.dataPath !== undefined && source.into === undefined && source.dataPath === undefined) {
156
+ source.dataPath = env.dataPath;
157
+ }
158
+ }
159
+ }
137
160
  }
138
161
  }
@@ -54,8 +54,9 @@ export function createKitNotifyRenderer(): NotifyRenderer {
54
54
  show(entry) {
55
55
  const host = ensure();
56
56
  if (host === undefined) return { dismiss() {} };
57
+ const level: NotifyEntry['level'] = (entry.level as string) === 'danger' ? 'error' : entry.level;
57
58
  const item = document.createElement('div');
58
- item.className = `${ITEM_BASE} ${LEVEL_CLASS[entry.level] ?? LEVEL_CLASS.info}`;
59
+ item.className = `${ITEM_BASE} ${LEVEL_CLASS[level] ?? LEVEL_CLASS.info}`;
59
60
  const body = document.createElement('div');
60
61
  body.className = BODY_CLASS;
61
62
  if (entry.title !== undefined && entry.title !== '') {
@@ -67,7 +68,7 @@ export function createKitNotifyRenderer(): NotifyRenderer {
67
68
  const m = document.createElement('div');
68
69
  m.textContent = entry.message;
69
70
  body.appendChild(m);
70
- item.append(kitIcon(LEVEL_ICON[entry.level] ?? 'info', 'md', ICON_CLASS), body);
71
+ item.append(kitIcon(LEVEL_ICON[level] ?? 'info', 'md', ICON_CLASS), body);
71
72
  let timer: ReturnType<typeof setTimeout> | undefined;
72
73
  const dismiss = (): void => {
73
74
  if (timer !== undefined) clearTimeout(timer);
@@ -87,7 +88,7 @@ export function createKitNotifyRenderer(): NotifyRenderer {
87
88
  host.appendChild(item);
88
89
  // duration 为 0 = 常驻(手动关闭);NaN / 负数 / 非数字按级别默认时长
89
90
  const d = entry.duration;
90
- const ms = typeof d === 'number' && Number.isFinite(d) && d >= 0 ? d : (DEFAULT_DURATION_MS[entry.level] ?? 3000);
91
+ const ms = typeof d === 'number' && Number.isFinite(d) && d >= 0 ? d : (DEFAULT_DURATION_MS[level] ?? 3000);
91
92
  if (ms > 0) timer = setTimeout(dismiss, ms);
92
93
  return { dismiss };
93
94
  },
@@ -23,7 +23,7 @@ import { safeHref } from '../../base/link';
23
23
  import { closeKitHub, hasKitHub, kitActionExtras } from './runtime-hub';
24
24
  import { readKitStepValues } from './step-values';
25
25
  import { askKitPrompt } from '../../data/prompt-dialog';
26
- import { setKitAppEnvelope, type KitEnvelope } from '../../app/envelope';
26
+ import { setKitAppEnvelope, getKitAppEnvelope, resolveEnvelopeSubPath, type KitEnvelope } from '../../app/envelope';
27
27
  import { draftFieldsOfBody, recordKitOutcomeDraft } from '../../object-renderer/outcome-draft';
28
28
  import { kitText } from '../../i18n/kit-text';
29
29
  import { KIT_GRAMMAR } from '../../object-renderer/defaults';
@@ -299,11 +299,14 @@ export function createKitActionHost(): SomaComponentDefinition {
299
299
  }
300
300
  // 拆分(into.keyBy):整次请求的状态落合成对象名(不可见),成功后由 core 把列表按项落成 <名字>#<键值> 的按行结果
301
301
  let split: Record<string, unknown> | undefined;
302
+ let splitPath = '';
302
303
  if (spec.splitBy !== undefined) {
303
304
  outcomeScope = spec.writeObject;
304
305
  const env = rec(props().envelope);
306
+ const dataPath = typeof env.dataPath === 'string' ? env.dataPath : getKitAppEnvelope()?.dataPath;
307
+ splitPath = resolveEnvelopeSubPath(spec.splitBy.path, dataPath);
305
308
  split = {
306
- path: spec.splitBy.path, key: spec.splitBy.key, prefix: spec.outcome, separator: OUTCOME_KEY_SEP,
309
+ path: splitPath, key: spec.splitBy.key, prefix: spec.outcome, separator: OUTCOME_KEY_SEP,
307
310
  ...(env.failWhen !== undefined ? { failWhen: env.failWhen } : {}),
308
311
  ...(typeof env.messagePath === 'string' ? { messagePath: env.messagePath } : {}),
309
312
  };
@@ -330,7 +333,7 @@ export function createKitActionHost(): SomaComponentDefinition {
330
333
  let message = view.message;
331
334
  let ok = view.status === 'saved';
332
335
  // 拆分:响应体里取不到列表(接口形状不对)按请求失败,不假装拆出了结果
333
- if (ok && spec.splitBy !== undefined && !Array.isArray(walk(rec(view.result).data, spec.splitBy.path.split('.')))) {
336
+ if (ok && spec.splitBy !== undefined && !Array.isArray(walk(rec(view.result).data, splitPath.split('.')))) {
334
337
  ok = false;
335
338
  message = kitText('soma.kit.request_failed', undefined, ctx.host);
336
339
  }
@@ -27,7 +27,7 @@ import { KIT_BUSY_PROP_DEFS, cancelKitAction, isKitActionBusy, isKitActionCancel
27
27
  import { holds } from '../object-renderer/linkage';
28
28
  import { adoptPlan, gateOutcomeNames, gateReason, sameValue, type KitAdoptDecl, type KitAdoptPlan, type KitGateDecl } from '../object-renderer/adopt-gate';
29
29
  import { watchKitOutcome, type KitOutcome } from './outcome-watch';
30
- import { fetchRemoteOptionRows } from './remote-options';
30
+ import { fetchRemoteOptionRows, rowsOfOptionsResponse } from './remote-options';
31
31
  import { clearStaleFlowSelections, clearStaleRowSelections, flowOptionSlots, flowOptionsOfRows, rowColumnSlots, ROW_COLUMN_SLOT_TYPE, withFlowOptions, withRowColumnOptions, type FlowOptionResolved, type FlowOptionSlot } from './flow-remote-options';
32
32
  import { evalActionGate, gateFrom, gateOutcomeNamesOf } from '../base/action-gate';
33
33
  import { asyncResultOf, outcomePanelData } from './async-result-panel';
@@ -1071,24 +1071,6 @@ function createController(
1071
1071
  };
1072
1072
 
1073
1073
  // ── 远程选项(options.from):经 services.http 取,依赖字段变化清值并重取 ──
1074
- const pickPath = (root: unknown, path: string): unknown => {
1075
- let cur: unknown = root;
1076
- for (const seg of path.split('.')) {
1077
- if (!isRec(cur)) return undefined;
1078
- cur = cur[seg];
1079
- }
1080
- return cur;
1081
- };
1082
- const rowsOfResponse = (res: unknown, rowsPath: string): Rec[] => {
1083
- if (Array.isArray(res)) return res.filter(isRec);
1084
- for (const p of rowsPath !== '' ? [rowsPath] : FL.optionsFrom.rowsPathCandidates) {
1085
- const direct = pickPath(res, p);
1086
- if (Array.isArray(direct)) return direct.filter(isRec);
1087
- const wrapped = pickPath(pickPath(res, 'data'), p);
1088
- if (Array.isArray(wrapped)) return wrapped.filter(isRec);
1089
- }
1090
- return [];
1091
- };
1092
1074
  /** 选项源请求计划;params 里的 { steps: 's0.字段' }(GB1)先换成该步已确认的值,值为空等同依赖字段为空(不发请求) */
1093
1075
  const planFor = (of: NonNullable<KitCell['optionsFrom']>, vals: Rec): ReturnType<typeof planOptionSourceRequest> => {
1094
1076
  if (hasStepParams(of.params)) {
@@ -1129,7 +1111,7 @@ function createController(
1129
1111
  const api = baseURL !== '' && baseURL !== '/' && of.from.startsWith(`${baseURL}/`) ? of.from.slice(baseURL.length) : of.from;
1130
1112
  void http.get<unknown>(api, { params }).then((res) => {
1131
1113
  if (!alive || st.seq !== mine) return;
1132
- st.rows = rowsOfResponse(res, of.rowsPath);
1114
+ st.rows = rowsOfOptionsResponse(res, of.rowsPath);
1133
1115
  repaint();
1134
1116
  }).catch(() => {
1135
1117
  if (!alive || st.seq !== mine) return;
@@ -1247,7 +1229,7 @@ function createController(
1247
1229
  (st.children ??= new Map<string, Rec[]>()).set(cascadeKey(path), rows);
1248
1230
  repaint();
1249
1231
  };
1250
- void http.get<unknown>(api, { params }).then((res) => store(rowsOfResponse(res, of.rowsPath))).catch(() => store([]));
1232
+ void http.get<unknown>(api, { params }).then((res) => store(rowsOfOptionsResponse(res, of.rowsPath))).catch(() => store([]));
1251
1233
  };
1252
1234
 
1253
1235
  const buildRows = (): KitFormRow[] => {
@@ -4,6 +4,7 @@
4
4
  // 失败照实 reject(调用方显示『选项加载失败』),不吞成空列表。
5
5
 
6
6
  import { KIT_FORM_LINKAGE } from '../object-renderer/defaults';
7
+ import { unwrapEnvelope, envelopeMessage, getKitAppEnvelope, type KitEnvelope } from '../app/envelope';
7
8
 
8
9
  type Rec = Record<string, unknown>;
9
10
  type Json = Record<string, any>;
@@ -21,15 +22,34 @@ function pickPath(root: unknown, path: string): unknown {
21
22
  return cur;
22
23
  }
23
24
 
24
- /** 响应体 -> 候选行数组(响应本身是数组、或在 rowsPath / 候选路径下、或再包一层 data) */
25
- export function rowsOfOptionsResponse(res: unknown, rowsPath: string): Rec[] {
26
- if (Array.isArray(res)) return res.filter(isRec);
27
- for (const p of rowsPath !== '' ? [rowsPath] : CANDIDATES) {
28
- const direct = pickPath(res, p);
25
+ /** 响应体 -> 候选行数组(拆信封,命中业务失败则抛错;成功在 unwrapped.data 或原响应上查找数组) */
26
+ export function rowsOfOptionsResponse(res: unknown, rowsPath: string, env: KitEnvelope | undefined = getKitAppEnvelope()): Rec[] {
27
+ const unwrapped = unwrapEnvelope(res, env);
28
+ if (!unwrapped.ok) {
29
+ const msg = envelopeMessage(res, env) || '选项加载失败';
30
+ throw new Error(msg);
31
+ }
32
+ const payload = unwrapped.data;
33
+ if (Array.isArray(payload)) return payload.filter(isRec);
34
+
35
+ const paths = rowsPath !== '' ? [rowsPath] : CANDIDATES;
36
+ for (const p of paths) {
37
+ const direct = pickPath(payload, p);
29
38
  if (Array.isArray(direct)) return direct.filter(isRec);
30
- const wrapped = pickPath(pickPath(res, 'data'), p);
39
+ const wrapped = pickPath(pickPath(payload, 'data'), p);
31
40
  if (Array.isArray(wrapped)) return wrapped.filter(isRec);
32
41
  }
42
+
43
+ // 兼容存量已写 rowsPath: 'data.rows' 的情况:在 unwrapped.data 找不到时再回退试原始 res
44
+ if (payload !== res) {
45
+ for (const p of paths) {
46
+ const direct = pickPath(res, p);
47
+ if (Array.isArray(direct)) return direct.filter(isRec);
48
+ const wrapped = pickPath(pickPath(res, 'data'), p);
49
+ if (Array.isArray(wrapped)) return wrapped.filter(isRec);
50
+ }
51
+ }
52
+
33
53
  return [];
34
54
  }
35
55
 
@@ -27,6 +27,7 @@ import { kitIcon } from '../base/icons';
27
27
  import { KIT_TREE_TABLE } from '../object-renderer/defaults';
28
28
  import { ACTION_BUTTON_CLASS } from '../object-renderer/table-actions';
29
29
  import { provideCtxRows } from './context-menu';
30
+ import { unwrapEnvelope, envelopeMessage, getKitAppEnvelope } from '../app/envelope';
30
31
 
31
32
  // ── 类串表(整串字面量;候选类汇总在底部) ──
32
33
 
@@ -395,8 +396,24 @@ export function createKitTreeTable(): SomaComponentDefinition {
395
396
  const baseURL = typeof rawBase === 'string' ? rawBase.replace(/\/+$/, '') : '/api';
396
397
  const apiPath = baseURL && baseURL !== '/' && from.api.startsWith(`${baseURL}/`) ? from.api.slice(baseURL.length) : from.api;
397
398
  const res = await http.get<unknown>(apiPath, { params: { [from.param]: node.key } });
398
- const direct = pickPath(res, from.rows);
399
- const list = Array.isArray(direct) ? direct : pickPath(pickPath(res, 'data'), from.rows);
399
+ const unwrapped = unwrapEnvelope(res, getKitAppEnvelope());
400
+ if (!unwrapped.ok) throw new Error(envelopeMessage(res, getKitAppEnvelope()) || '加载子行失败');
401
+ const payload = unwrapped.data;
402
+ let list: unknown;
403
+ if (Array.isArray(payload)) {
404
+ list = payload;
405
+ } else {
406
+ const p1 = pickPath(payload, from.rows);
407
+ if (Array.isArray(p1)) {
408
+ list = p1;
409
+ } else if (from.rows === 'result.rows' && Array.isArray(pickPath(payload, 'rows'))) {
410
+ list = pickPath(payload, 'rows');
411
+ } else if (Array.isArray(pickPath(res, from.rows))) {
412
+ list = pickPath(res, from.rows);
413
+ } else {
414
+ list = pickPath(pickPath(res, 'data'), from.rows);
415
+ }
416
+ }
400
417
  loaded.set(node.key, Array.isArray(list) ? list.filter(isRec) : []);
401
418
  rebuild();
402
419
  open.add(node.key);
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { regionMirrorStatePath } from 'soma-core';
14
14
  import type { SomaScopeDecl, SomaScopeMirrorDecl, SomaScopeSliceDecl } from 'soma-core';
15
+ import { getCompileEnvelope, resolveEnvelopeSubPath } from '../app/envelope';
15
16
  import { KIT_CORE_MAPPING, KIT_FORM_LINKAGE, KIT_GRAMMAR } from './defaults';
16
17
  import { predicateToCore, staticOptionsOf } from './linkage';
17
18
  import type {
@@ -157,13 +158,42 @@ export const VIEW_MIRROR_SIZE = 'view_size';
157
158
 
158
159
  /** 对象级轮询的隐藏接线件实例 id */
159
160
 
160
- export function listShapeOf(behavior: KitBehavior): KitListShape {
161
- const { rowsPath, totalPath, ...rest } = behavior.list ?? {};
161
+ export function listShapeOf(behavior: KitBehavior, dataPath = getCompileEnvelope()?.dataPath): KitListShape {
162
+ const { rowsPath, totalPath, errorPath, ...rest } = behavior.list ?? {};
162
163
  const shape: KitListShape = { ...KIT_CORE_MAPPING.listShape, ...rest };
163
164
  // rowsPath / totalPath 相对响应体,补上 listInto 前缀;与存量的 rows / total(相对对象)同写时 rowsPath / totalPath 优先
164
165
  const base = KIT_CORE_MAPPING.fromWrap.listInto;
165
- if (typeof rowsPath === 'string' && rowsPath !== '') shape.rows = `${base}.${rowsPath}`;
166
- if (typeof totalPath === 'string' && totalPath !== '') shape.total = `${base}.${totalPath}`;
166
+ const hasDataPath = typeof dataPath === 'string' && dataPath !== '';
167
+
168
+ if (hasDataPath) {
169
+ if (typeof rowsPath === 'string' && rowsPath !== '') {
170
+ shape.rows = `${base}.${resolveEnvelopeSubPath(rowsPath, dataPath)}`;
171
+ } else if (behavior.list?.rows === undefined) {
172
+ shape.rows = `${base}.${resolveEnvelopeSubPath('rows', dataPath)}`;
173
+ }
174
+ if (typeof totalPath === 'string' && totalPath !== '') {
175
+ shape.total = `${base}.${resolveEnvelopeSubPath(totalPath, dataPath)}`;
176
+ } else if (behavior.list?.total === undefined) {
177
+ shape.total = `${base}.${resolveEnvelopeSubPath('total', dataPath)}`;
178
+ }
179
+ if (errorPath === undefined) {
180
+ shape.errorPath = `${base}.${resolveEnvelopeSubPath('error', dataPath)}`;
181
+ } else if (typeof errorPath === 'string') {
182
+ if (errorPath === '') {
183
+ shape.errorPath = '';
184
+ } else if (errorPath.startsWith(`${base}.`)) {
185
+ shape.errorPath = errorPath;
186
+ } else {
187
+ shape.errorPath = `${base}.${resolveEnvelopeSubPath(errorPath, dataPath)}`;
188
+ }
189
+ }
190
+ } else {
191
+ if (typeof rowsPath === 'string' && rowsPath !== '') shape.rows = `${base}.${rowsPath}`;
192
+ if (typeof totalPath === 'string' && totalPath !== '') shape.total = `${base}.${totalPath}`;
193
+ if (typeof errorPath === 'string') {
194
+ shape.errorPath = errorPath === '' || errorPath.startsWith(`${base}.`) ? errorPath : `${base}.${errorPath}`;
195
+ }
196
+ }
167
197
  return shape;
168
198
  }
169
199