soma-core 1.4.0 → 1.4.2

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 (132) hide show
  1. package/README.md +1 -1
  2. package/core/build/blocks/block-compile.ts +31 -2
  3. package/core/build/blocks/block-container.ts +2 -11
  4. package/core/build/compiler/page-declaration-compiler.ts +30 -2
  5. package/core/build/compiler/soma-precompile.js +2053 -23
  6. package/core/build/component/component-graph.ts +208 -0
  7. package/core/build/component/package-loader.ts +32 -0
  8. package/core/build/eject/component-eject.ts +473 -0
  9. package/core/build/eject/component-upgrade.ts +359 -0
  10. package/core/build/layout/constraint-solver.ts +235 -0
  11. package/core/build/layout/css-emitter.ts +116 -0
  12. package/core/build/layout/page-layout.ts +85 -0
  13. package/core/build/pack/pack-init.ts +270 -0
  14. package/core/client/base/SomaHttpClient.ts +34 -1
  15. package/core/client/base/SomaPageRootBase.ts +61 -0
  16. package/core/client/component/ai-catalog.ts +121 -4
  17. package/core/client/component/component-defaults.ts +100 -0
  18. package/core/client/component/component-definition.types.ts +39 -0
  19. package/core/client/component/component-manager.ts +79 -4
  20. package/core/client/component/component-pack.ts +126 -2
  21. package/core/client/component/keyboard-matrix.ts +144 -0
  22. package/core/client/component/pack-styles.ts +59 -1
  23. package/core/client/component/style-features.ts +131 -0
  24. package/core/client/component/theme-component-tokens.ts +83 -0
  25. package/core/client/component/verify-pack.ts +120 -1
  26. package/core/client/container/SomaContainerAdapter.ts +6 -2
  27. package/core/client/data/data-object-resolver.ts +407 -4
  28. package/core/client/data/reaction-engine.ts +176 -0
  29. package/core/client/data/window-engine.ts +477 -0
  30. package/core/client/engine/event-engine.ts +98 -0
  31. package/core/client/engine/soma-bootstrap.ts +265 -5
  32. package/core/client/engine/step-runner.ts +134 -0
  33. package/core/client/infra/http/SomaHttpService.ts +2 -2
  34. package/core/client/parser/blocks/page-parser.ts +15 -1
  35. package/core/client/parser/blocks/use-parser.ts +5 -12
  36. package/core/client/parser/data-config-parser.ts +316 -8
  37. package/core/client/parser/duration.ts +16 -0
  38. package/core/client/parser/layout-parser.ts +157 -0
  39. package/core/client/parser/page-state-parser.ts +166 -0
  40. package/core/client/parser/pipeline-parser.ts +76 -1
  41. package/core/client/parser/reaction-parser.ts +459 -0
  42. package/core/client/parser/reaction-sugar.ts +47 -0
  43. package/core/client/parser/step-parser.ts +359 -0
  44. package/core/client/parser/ui-config-parser.ts +59 -0
  45. package/core/client/parser/window-parser.ts +294 -0
  46. package/core/client/theme/theme-engine.ts +102 -2
  47. package/core/index.ts +184 -0
  48. package/core/shared/block-errors.ts +11 -0
  49. package/core/shared/calc/coerce.ts +29 -0
  50. package/core/shared/calc/errors.ts +43 -0
  51. package/core/shared/calc/evaluator.ts +101 -0
  52. package/core/shared/calc/index.ts +12 -0
  53. package/core/shared/calc/lexer.ts +194 -0
  54. package/core/shared/calc/parser.ts +204 -0
  55. package/core/shared/calc/typer.ts +184 -0
  56. package/core/shared/component/derive-sample.ts +105 -0
  57. package/core/shared/component/field-lines.ts +473 -0
  58. package/core/shared/path-algebra.ts +169 -0
  59. package/core/shared/predicates/index.ts +527 -0
  60. package/core/shared/types/component-contract.types.ts +151 -9
  61. package/core/shared/types/data-config.types.ts +120 -1
  62. package/core/shared/types/domain.types.ts +13 -0
  63. package/core/shared/types/event.types.ts +22 -2
  64. package/core/shared/types/layout-constraint.types.ts +73 -0
  65. package/core/shared/types/page-state.types.ts +60 -0
  66. package/core/shared/types/reaction.types.ts +144 -0
  67. package/core/shared/types/step.types.ts +91 -0
  68. package/core/shared/types/ui-config.types.ts +18 -0
  69. package/core/shared/types/window.types.ts +177 -0
  70. package/dist/cli/soma.js +13 -1
  71. package/dist/core/index.cjs +5529 -631
  72. package/dist/types/build/blocks/block-container.d.ts +1 -6
  73. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
  74. package/dist/types/build/component/component-graph.d.ts +85 -0
  75. package/dist/types/build/eject/component-eject.d.ts +121 -0
  76. package/dist/types/build/eject/component-upgrade.d.ts +43 -0
  77. package/dist/types/build/layout/constraint-solver.d.ts +36 -0
  78. package/dist/types/build/layout/css-emitter.d.ts +18 -0
  79. package/dist/types/build/layout/page-layout.d.ts +24 -0
  80. package/dist/types/build/pack/pack-init.d.ts +8 -0
  81. package/dist/types/client/base/SomaHttpClient.d.ts +8 -0
  82. package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
  83. package/dist/types/client/component/ai-catalog.d.ts +33 -1
  84. package/dist/types/client/component/component-defaults.d.ts +15 -0
  85. package/dist/types/client/component/component-definition.types.d.ts +38 -0
  86. package/dist/types/client/component/component-manager.d.ts +36 -0
  87. package/dist/types/client/component/component-pack.d.ts +32 -2
  88. package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
  89. package/dist/types/client/component/pack-styles.d.ts +21 -0
  90. package/dist/types/client/component/style-features.d.ts +26 -0
  91. package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
  92. package/dist/types/client/component/verify-pack.d.ts +10 -0
  93. package/dist/types/client/data/data-object-resolver.d.ts +106 -1
  94. package/dist/types/client/data/reaction-engine.d.ts +21 -0
  95. package/dist/types/client/data/window-engine.d.ts +27 -0
  96. package/dist/types/client/engine/event-engine.d.ts +15 -0
  97. package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
  98. package/dist/types/client/engine/step-runner.d.ts +24 -0
  99. package/dist/types/client/parser/blocks/use-parser.d.ts +2 -2
  100. package/dist/types/client/parser/duration.d.ts +1 -0
  101. package/dist/types/client/parser/layout-parser.d.ts +9 -0
  102. package/dist/types/client/parser/page-state-parser.d.ts +32 -0
  103. package/dist/types/client/parser/reaction-parser.d.ts +16 -0
  104. package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
  105. package/dist/types/client/parser/step-parser.d.ts +23 -0
  106. package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
  107. package/dist/types/client/parser/window-parser.d.ts +25 -0
  108. package/dist/types/client/theme/theme-engine.d.ts +26 -0
  109. package/dist/types/index.d.ts +35 -2
  110. package/dist/types/shared/block-errors.d.ts +5 -0
  111. package/dist/types/shared/calc/coerce.d.ts +4 -0
  112. package/dist/types/shared/calc/errors.d.ts +14 -0
  113. package/dist/types/shared/calc/evaluator.d.ts +2 -0
  114. package/dist/types/shared/calc/index.d.ts +6 -0
  115. package/dist/types/shared/calc/lexer.d.ts +20 -0
  116. package/dist/types/shared/calc/parser.d.ts +49 -0
  117. package/dist/types/shared/calc/typer.d.ts +16 -0
  118. package/dist/types/shared/component/derive-sample.d.ts +23 -0
  119. package/dist/types/shared/component/field-lines.d.ts +19 -0
  120. package/dist/types/shared/path-algebra.d.ts +56 -0
  121. package/dist/types/shared/predicates/index.d.ts +79 -0
  122. package/dist/types/shared/types/component-contract.types.d.ts +134 -6
  123. package/dist/types/shared/types/data-config.types.d.ts +115 -1
  124. package/dist/types/shared/types/domain.types.d.ts +12 -0
  125. package/dist/types/shared/types/event.types.d.ts +8 -2
  126. package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
  127. package/dist/types/shared/types/page-state.types.d.ts +49 -0
  128. package/dist/types/shared/types/reaction.types.d.ts +115 -0
  129. package/dist/types/shared/types/step.types.d.ts +76 -0
  130. package/dist/types/shared/types/ui-config.types.d.ts +18 -0
  131. package/dist/types/shared/types/window.types.d.ts +171 -0
  132. package/package.json +3 -2
@@ -0,0 +1,176 @@
1
+ // 反应图求值(REQ-010 S1b)——一次输入 → 一批字段状态。
2
+ //
3
+ // 引擎只做三件事:找出受影响的反应、按拓扑序求值、把 patch 合并成结果。
4
+ // 它不认识组件、不碰 DOM、不发请求——纯函数,入参不改,出参是新对象。
5
+ //
6
+ // ── 为什么可以「只跑受影响子图」而不是全量重算 ──────────────────────
7
+ // rc-field-form 的做法是给每个字段挂订阅、按 namePath 过滤、脏标记递归传播——
8
+ // 那是因为它的依赖只有运行时才知道。SOMA 的图在解析期就建好了,所以
9
+ // 「改了 amount 会牵动谁」是一次 `byField['amount']` 查表,不需要遍历全表。
10
+ //
11
+ // ── 传播为什么必然终止 ──────────────────────────────────────────────
12
+ // `value` patch 会改字段值,改完的字段要继续往下游传播。图无环(解析期已保证),
13
+ // 所以沿拓扑序单向走一趟就够:一条反应最多被求值一次,步数上界是反应条数。
14
+ // 这是「图」相对「回调链」的直接红利——回调链要靠脏标记与最大轮次去防死循环。
15
+
16
+ import type {
17
+ SomaFieldStatePatch,
18
+ SomaFormStatePatch,
19
+ SomaReactionGraph,
20
+ SomaReactionPhase,
21
+ SomaReactionResult,
22
+ } from '../../shared/types/reaction.types';
23
+ import { SOMA_REACTION_FORM_KEY } from '../../shared/types/reaction.types';
24
+ import { evaluatePredicate, type SomaFieldPredicate, type SomaNamedPredicates } from '../../shared/predicates';
25
+ import { evaluateCalc, type CalcAst } from '../../shared/calc';
26
+
27
+ export interface ReactionRunInput {
28
+ graph: SomaReactionGraph;
29
+ /** 当前值(不会被修改) */
30
+ values: Record<string, unknown>;
31
+ /** 本次变更的字段;空数组表示「全量重算」(挂载时用) */
32
+ changed?: readonly string[];
33
+ phase?: SomaReactionPhase;
34
+ named?: SomaNamedPredicates;
35
+ /** `on: field_validate_*` 的判定面:当前校验失败的字段 */
36
+ failedFields?: readonly string[];
37
+ }
38
+
39
+ export function runReactions(input: ReactionRunInput): SomaReactionResult {
40
+ const { graph, named = {} } = input;
41
+ const phase = input.phase ?? 'field_value_change';
42
+ const values: Record<string, unknown> = { ...input.values };
43
+
44
+ const patches: Record<string, SomaFieldStatePatch> = {};
45
+ const form: SomaFormStatePatch = {};
46
+ const detached = new Set<string>();
47
+ let steps = 0;
48
+
49
+ // 受影响集合:不给 changed 就是全量(挂载/提交等时机本就该全跑一遍)
50
+ const affected = new Set<number>();
51
+ if (input.changed === undefined) {
52
+ graph.reactions.forEach((reaction) => affected.add(reaction.index));
53
+ } else {
54
+ for (const field of input.changed) {
55
+ for (const index of graph.byField[field] ?? []) affected.add(index);
56
+ }
57
+ }
58
+
59
+ // 按拓扑序单向走一趟。`value` patch 改了字段值时,把该字段的下游反应加入集合——
60
+ // 因为是拓扑序且图无环,加入的下游一定还在后面,不会漏也不会回头。
61
+ for (const reaction of graph.reactions) {
62
+ if (!affected.has(reaction.index)) continue;
63
+ if (reaction.phase !== phase) continue;
64
+ steps += 1;
65
+
66
+ const holds = evaluateCondition(reaction.config.when, values, named, reaction, input.failedFields);
67
+ const branch = holds ? reaction.config.fulfill : reaction.config.otherwise;
68
+ if (!branch) continue;
69
+
70
+ for (const [target, patchRaw] of Object.entries(branch)) {
71
+ if (target === SOMA_REACTION_FORM_KEY) {
72
+ // `fulfill: { submit: { disabled: true } }` —— patchRaw 就是 `{ disabled }` 本身,
73
+ // 不是再包一层的 `{ submit: {...} }`。多取一层的话它恒为 undefined,
74
+ // 表单级 patch 会静默丢失(表现是「锁提交」这条反应写了没反应)。
75
+ Object.assign(form, {
76
+ submit: { ...form.submit, ...(patchRaw as SomaFormStatePatch['submit']) },
77
+ });
78
+ continue;
79
+ }
80
+ const patch = patchRaw as SomaFieldStatePatch;
81
+
82
+ // 合并:同一字段被多条反应写时,后写的赢(拓扑序内即声明序)
83
+ const merged: SomaFieldStatePatch = { ...patches[target], ...patch };
84
+ // `visible` 是 `display` 的糖,在这里就归一,下游只认 display
85
+ if (merged.visible !== undefined) {
86
+ merged.display = merged.visible ? 'visible' : 'hidden';
87
+ delete merged.visible;
88
+ }
89
+ patches[target] = merged;
90
+
91
+ if (merged.display === 'none') detached.add(target);
92
+ else detached.delete(target);
93
+
94
+ const nextValue = applyValuePatch(patch, target, values, reaction, holds);
95
+ if (nextValue !== NO_CHANGE) {
96
+ values[target] = nextValue;
97
+ // 下游继续传播(拓扑序保证它们还没跑过)
98
+ for (const index of graph.byField[target] ?? []) affected.add(index);
99
+ }
100
+ }
101
+ }
102
+
103
+ // `display: none` 的字段连数据一起摘除——这正是它与 hidden 的分别,
104
+ // 也是写通道剔除请求体的依据。
105
+ for (const field of detached) delete values[field];
106
+
107
+ return { patches, form, values, detached: [...detached], steps };
108
+ }
109
+
110
+ /** 哨兵:区分「patch 没写 value」与「patch 把值写成了 undefined」 */
111
+ const NO_CHANGE = Symbol('no-change');
112
+
113
+ function applyValuePatch(
114
+ patch: SomaFieldStatePatch,
115
+ target: string,
116
+ values: Record<string, unknown>,
117
+ reaction: SomaReactionGraph['reactions'][number],
118
+ holds: boolean,
119
+ ): unknown {
120
+ if (patch.value === undefined) return NO_CHANGE;
121
+ if (patch.value === 'clear') return null;
122
+
123
+ if (typeof patch.value === 'object' && 'from' in patch.value) {
124
+ return values[patch.value.from] ?? null;
125
+ }
126
+
127
+ if (typeof patch.value === 'object' && 'calc' in patch.value) {
128
+ // AST 在解析期就备好了:每帧重新解析同一串表达式是纯浪费
129
+ const key = `${holds ? 'fulfill' : 'otherwise'}:${target}`;
130
+ const ast = reaction.calcAsts[key] as CalcAst | undefined;
131
+ if (!ast) return NO_CHANGE;
132
+ return evaluateCalc(ast, values);
133
+ }
134
+ return NO_CHANGE;
135
+ }
136
+
137
+ function evaluateCondition(
138
+ when: SomaFieldPredicate | undefined,
139
+ values: Record<string, unknown>,
140
+ named: SomaNamedPredicates,
141
+ reaction: SomaReactionGraph['reactions'][number],
142
+ failedFields: readonly string[] | undefined,
143
+ ): boolean {
144
+ // 校验类时机:条件是「target 这个字段校验失败了没有」,不是谓词
145
+ if (reaction.phase.startsWith('field_validate')) {
146
+ const target = String(reaction.config.target ?? '');
147
+ const failed = (failedFields ?? []).includes(target);
148
+ const wantFailed = reaction.phase === 'field_validate_failed';
149
+ const wantSuccess = reaction.phase === 'field_validate_success';
150
+ if (wantFailed) return failed;
151
+ if (wantSuccess) return !failed;
152
+ return true; // start / end 只是时机,本身不带判定
153
+ }
154
+ // 没有 when(只有 depends)= 依赖变了就执行 fulfill
155
+ if (when === undefined) return true;
156
+ return evaluatePredicate(when, values, named);
157
+ }
158
+
159
+ /**
160
+ * 打印一条字段的回溯链——诊断面。
161
+ *
162
+ * amis 的 `${x}` 只能沿运行时数据链向上找,给不出这个;这是「可静态回溯」
163
+ * 在人能看见的那一端的落点。
164
+ */
165
+ export function explainField(graph: SomaReactionGraph, field: string): string {
166
+ const info = graph.provenance[field];
167
+ if (!info) return `字段 "${field}" 不在字典里`;
168
+ const lines = [`字段 ${field}`];
169
+ if (info.sourceApi) lines.push(` 数据来源:${info.sourceApi}`);
170
+ if (info.writtenBy.length === 0) lines.push(' 没有反应写它(它的值只来自接口或用户输入)');
171
+ else {
172
+ lines.push(` 被反应写:${info.writtenBy.map((i) => `#${i + 1}`).join(' / ')}(声明序)`);
173
+ lines.push(` 上游字段:${info.readsFrom.length > 0 ? info.readsFrom.join(' / ') : '无'}`);
174
+ }
175
+ return lines.join('\n');
176
+ }
@@ -0,0 +1,477 @@
1
+ // 数据窗口引擎(REQ-010 S2)——块缓存、选择态代数、编辑双通道,一份实现覆盖全部列表组件。
2
+ //
3
+ // ── 它替掉了什么 ────────────────────────────────────────────────────────
4
+ // 今天 QueryConsole、DataTable、各家业务台各自持 `page / page_size / sort_key / filters`,
5
+ // 各自拼请求、各自处理竞态、各自决定「换排序要不要回第一页」。这些裁决被复制了 N 份,
6
+ // 而复制品之间的差异只有在用户投诉时才会浮现。窗口把它们收成一份。
7
+ //
8
+ // ── 三条不显然的裁决 ───────────────────────────────────────────────────
9
+ // 1. **改意图即清空缓存**。sort/filter/group/aggregate 任一项变了,旧块全部作废——
10
+ // 不是为了省内存,是因为「按金额排序的第 3 块」与「按时间排序的第 3 块」是两批不同的行,
11
+ // 留着它们等于让用户看到一份拼接自两种排序的列表。
12
+ // 2. **选择态记成基线 + 反选集**。十万行里「全选后取消三行」,朴素做法要传九万九千多个 id。
13
+ // 3. **展示看 pending,请求看 committed**。用户改了一格还没提交时,排序要按旧值排——
14
+ // 否则那一行会在他打字的过程中自己跳走。
15
+
16
+ import type {
17
+ SomaWindowConfig,
18
+ SomaWindowHandle,
19
+ SomaWindowRequest,
20
+ SomaWindowRequestPatch,
21
+ SomaWindowResponse,
22
+ SomaWindowSelection,
23
+ SomaTransaction,
24
+ } from '../../shared/types/window.types';
25
+ import type { SomaDataSubmitResult } from '../../shared/types/data-config.types';
26
+
27
+ /**
28
+ * 引擎只要 GET;写走宿主注入的 commit(写通道的编排不在这里复制一份)。
29
+ *
30
+ * 返回类型写死成窗口响应而不是泛型 `<T>`:引擎知道自己要什么,而泛型只会把
31
+ * 「这个 http 桩返回的形状对不对」这个判断推给每一个调用方(和每一个测试桩)。
32
+ * `SomaDataHttpLike` 的泛型 get 仍然结构兼容它。
33
+ */
34
+ export interface SomaWindowHttpLike {
35
+ get(url: string, config?: { params?: Record<string, string> }): Promise<SomaWindowResponse>;
36
+ }
37
+
38
+ export interface SomaWindowDeps {
39
+ http: SomaWindowHttpLike;
40
+ api: string;
41
+ /** 行主键字段名:选择态与编辑双通道都按它认行 */
42
+ idField: string;
43
+ /** 任何 rows / total / loading / selection 变化都会调一次(由解析器转成页面 render) */
44
+ onChange?: () => void;
45
+ /** 写通道:事务体交给它,引擎不重复实现提交编排 */
46
+ commit?: (tx: SomaTransaction) => Promise<SomaDataSubmitResult>;
47
+ /** 定时器注入(测试用;缺省用全局) */
48
+ now?: () => number;
49
+ }
50
+
51
+ interface CachedBlock {
52
+ rows: unknown[];
53
+ /** 最近访问时间:LRU 的排序键 */
54
+ at: number;
55
+ /** 取回时间:TTL 判过期用。与 `at` 分开是因为它们回答两个问题——
56
+ * `at` 是"最近有没有人看",`fetchedAt` 是"这份数据有多旧"。
57
+ * 合成一个的话,一直被看着的块会永远不过期,而它恰恰是最需要保鲜的那一块。 */
58
+ fetchedAt: number;
59
+ }
60
+
61
+ /** patch 栈上限:与 AG Grid 同值。无界的撤销栈是内存泄漏,不是功能 */
62
+ const SAVEPOINT_LIMIT = 10;
63
+
64
+ export function createWindow(
65
+ spec: SomaWindowConfig,
66
+ deps: SomaWindowDeps,
67
+ ): SomaWindowHandle {
68
+ const now = deps.now ?? (() => Date.now());
69
+
70
+ // 当前意图:从声明起步,之后被 request(patch) 改写
71
+ let sort = spec.sort;
72
+ let filter = spec.filter;
73
+ let group = spec.group;
74
+ let aggregate = spec.aggregate;
75
+ let start = 0;
76
+ let end = spec.block.size;
77
+
78
+ const blocks = new Map<number, CachedBlock>();
79
+ let total: number | undefined;
80
+ let loading = false;
81
+ let error = '';
82
+
83
+ const selection: { base: 'none' | 'all'; toggled: Set<string> } = {
84
+ base: spec.selection.base,
85
+ toggled: new Set(spec.selection.toggled),
86
+ };
87
+
88
+ /** 未提交的编辑:行 id → { 字段: 值 } */
89
+ let pending = new Map<string, Record<string, unknown>>();
90
+ const savepoints: Array<{ id: number; snapshot: Map<string, Record<string, unknown>> }> = [];
91
+ let savepointSeq = 0;
92
+
93
+ // 竞态:每次发请求前 +1,响应回来时对不上就丢弃。
94
+ // 少了这一道,快速改两次排序会以「后发先至」的顺序把旧结果盖在新结果上。
95
+ let generation = 0;
96
+ let debounceTimer: ReturnType<typeof setTimeout> | null = null;
97
+ let destroyed = false;
98
+
99
+ const notify = (): void => { deps.onChange?.(); };
100
+
101
+ /**
102
+ * 后台重验证(`revalidate`)。
103
+ *
104
+ * 只重取**当前视口覆盖的块**,不动其它块:用户此刻在看的那一屏才值得为它多发请求,
105
+ * 而把全部缓存块都重取一遍会在长列表上变成一次周期性的流量尖峰。
106
+ *
107
+ * `keep_previous` 在这里是天然成立的——旧块留在 `blocks` 里,新数据回来才覆盖,
108
+ * 所以重验证期间界面不会闪空。
109
+ *
110
+ * 这一条此前是「解析了、引擎不消费」:`revalidate_ms` 算出来了,但没有任何东西读它,
111
+ * 页面写 `revalidate: 60s` 得到的是完全的静默——声明看起来生效了。
112
+ */
113
+ let revalidateTimer: ReturnType<typeof setInterval> | null = null;
114
+
115
+ const startRevalidate = (): void => {
116
+ if (spec.revalidate_ms === null || revalidateTimer !== null) return;
117
+ revalidateTimer = setInterval(() => {
118
+ if (destroyed || loading) return; // 正在取数时不叠加一轮
119
+ for (const index of viewportBlocks()) blocks.delete(index);
120
+ void ensureRange();
121
+ }, spec.revalidate_ms);
122
+ };
123
+
124
+ const blockIndexOf = (row: number): number => Math.floor(row / spec.block.size);
125
+
126
+ const idOf = (row: unknown): string => {
127
+ if (row === null || typeof row !== 'object') return '';
128
+ const value = (row as Record<string, unknown>)[deps.idField];
129
+ return value === undefined || value === null ? '' : String(value);
130
+ };
131
+
132
+ /**
133
+ * 视口覆盖的块永不淘汰。
134
+ * 少了这条,`max_blocks` 小于视口跨度时会出现「刚取回来就被自己挤掉」的活锁:
135
+ * 每帧都在取同一批块,列表永远在 loading。
136
+ */
137
+ const viewportBlocks = (): Set<number> => {
138
+ const out = new Set<number>();
139
+ for (let index = blockIndexOf(start); index <= blockIndexOf(Math.max(start, end - 1)); index += 1) {
140
+ out.add(index);
141
+ }
142
+ return out;
143
+ };
144
+
145
+ const evictIfNeeded = (): void => {
146
+ if (blocks.size <= spec.block.max_blocks) return;
147
+ const protectedBlocks = viewportBlocks();
148
+ const candidates = [...blocks.entries()]
149
+ .filter(([index]) => !protectedBlocks.has(index))
150
+ .sort((a, b) => a[1].at - b[1].at);
151
+ for (const [index] of candidates) {
152
+ if (blocks.size <= spec.block.max_blocks) break;
153
+ blocks.delete(index);
154
+ }
155
+ };
156
+
157
+ const buildRequest = (from: number, to: number): SomaWindowRequest => ({
158
+ start: from,
159
+ end: to,
160
+ // 数组要拷贝:请求体是要被 stringify、缓存、贴进工单的东西,
161
+ // 交出去一个还会被后续 request() 改写的引用,排障时看到的就不是当时发出去的那份。
162
+ sort: sort.map((entry) => ({ ...entry })),
163
+ filter: filter === null ? null : cloneFilter(filter),
164
+ group: group === null ? null : { by: [...group.by], keys: [...group.keys] },
165
+ aggregate: aggregate.map((entry) => ({ ...entry })),
166
+ dict_hash: spec.dict_hash,
167
+ });
168
+
169
+ /** 缺失块合并成最少的连续区间:相邻缺块合一次请求,不是一块一个往返 */
170
+ const missingRanges = (): Array<[number, number]> => {
171
+ const needed: number[] = [];
172
+ for (let index = blockIndexOf(start); index <= blockIndexOf(Math.max(start, end - 1)); index += 1) {
173
+ if (!blocks.has(index)) needed.push(index);
174
+ }
175
+ const ranges: Array<[number, number]> = [];
176
+ for (const index of needed) {
177
+ const last = ranges[ranges.length - 1];
178
+ if (last && last[1] === index - 1) last[1] = index;
179
+ else ranges.push([index, index]);
180
+ }
181
+ return ranges;
182
+ };
183
+
184
+ const fetchRange = async (fromBlock: number, toBlock: number): Promise<void> => {
185
+ const token = generation;
186
+ const from = fromBlock * spec.block.size;
187
+ const to = (toBlock + 1) * spec.block.size;
188
+ const request = buildRequest(from, to);
189
+ loading = true;
190
+ notify();
191
+ try {
192
+ const raw = await deps.http.get(deps.api, {
193
+ // 请求体作为一个 JSON 串下发:GET 的载荷位只有 query,而窗口意图是结构化的。
194
+ // 拆成十几个扁平 query 参数的话,`filter` 的递归结构在 URL 里就没法表达了。
195
+ params: { window: JSON.stringify(request) },
196
+ });
197
+ if (destroyed || token !== generation) return; // 迟到的响应:丢弃,不是覆盖
198
+ const rows = Array.isArray(raw?.rows) ? raw.rows : [];
199
+ for (let index = fromBlock; index <= toBlock; index += 1) {
200
+ const offset = (index - fromBlock) * spec.block.size;
201
+ const slice = rows.slice(offset, offset + spec.block.size);
202
+ // 只登记真的拿到行的块。空块也登记的话,后端「这一段还没生成好」
203
+ // 会被永久缓存成「这一段是空的」。
204
+ if (slice.length > 0) blocks.set(index, { rows: slice, at: now(), fetchedAt: now() });
205
+ }
206
+ if (typeof raw?.total === 'number') total = raw.total;
207
+ else if (rows.length < to - from) total = from + rows.length; // 尾块短读 = 到底了
208
+ error = '';
209
+ evictIfNeeded();
210
+ } catch (cause) {
211
+ if (destroyed || token !== generation) return;
212
+ error = cause instanceof Error ? cause.message : String(cause);
213
+ } finally {
214
+ if (!destroyed && token === generation) {
215
+ loading = false;
216
+ notify();
217
+ }
218
+ }
219
+ };
220
+
221
+ /**
222
+ * TTL 过期清理(`cache.ttl`)。
223
+ *
224
+ * 在算"缺哪些块"之前做:过期的块要被当成**缺失**,而不是当成命中。
225
+ * 放在之后做的话,这一帧仍会拿旧数据渲染,下一帧才重取——用户看到的是
226
+ * 一次没来由的闪变。
227
+ *
228
+ * 只摘不取:摘掉之后 `missingRanges` 自然会把它算进缺块,走同一条取数路径。
229
+ * 单独为过期块写一条取数分支,等于把"怎么取一段行"实现两遍。
230
+ */
231
+ const dropExpired = (): void => {
232
+ const ttl = spec.cache.ttl_ms;
233
+ if (ttl === null) return;
234
+ const deadline = now() - ttl;
235
+ for (const [index, block] of [...blocks.entries()]) {
236
+ if (block.fetchedAt < deadline) blocks.delete(index);
237
+ }
238
+ };
239
+
240
+ const ensureRange = async (): Promise<void> => {
241
+ dropExpired();
242
+ const ranges = missingRanges();
243
+ if (ranges.length === 0) {
244
+ // 命中缓存也要更新访问时间,否则 LRU 会淘汰掉用户一直在看的那一块
245
+ for (const index of viewportBlocks()) {
246
+ const block = blocks.get(index);
247
+ if (block) block.at = now();
248
+ }
249
+ return;
250
+ }
251
+ await Promise.all(ranges.map(([from, to]) => fetchRange(from, to)));
252
+ };
253
+
254
+ /** debounce:快速滚动期间的中间块不必每一格都发一次请求 */
255
+ const ensureRangeDebounced = (): Promise<void> => {
256
+ if (spec.block.debounce_ms <= 0) return ensureRange();
257
+ if (debounceTimer !== null) clearTimeout(debounceTimer);
258
+ return new Promise((resolve) => {
259
+ debounceTimer = setTimeout(() => {
260
+ debounceTimer = null;
261
+ void ensureRange().then(resolve);
262
+ }, spec.block.debounce_ms);
263
+ });
264
+ };
265
+
266
+ /** 展示值 = 已提交值 ⊕ 未提交编辑 */
267
+ const visibleRows = (): unknown[] => {
268
+ const out: unknown[] = [];
269
+ for (let index = blockIndexOf(start); index <= blockIndexOf(Math.max(start, end - 1)); index += 1) {
270
+ const block = blocks.get(index);
271
+ if (!block) continue;
272
+ const base = index * spec.block.size;
273
+ block.rows.forEach((row, offset) => {
274
+ const absolute = base + offset;
275
+ if (absolute < start || absolute >= end) return;
276
+ const patch = pending.get(idOf(row));
277
+ out.push(patch === undefined ? row : { ...(row as Record<string, unknown>), ...patch });
278
+ });
279
+ }
280
+ return out;
281
+ };
282
+
283
+ /**
284
+ * 分组下钻的子窗口(F-33):`group.keys` 路径 → 独立实例。
285
+ *
286
+ * 每层独立而不是把子行塞进父窗口的块里:子层有**自己的**总数、自己的分页、
287
+ * 自己的取数状态。混在一起的话,展开一个分组会让父层的 `total` 和滚动位置
288
+ * 一起失真,而失真的方式取决于展开了哪几个分组。
289
+ *
290
+ * 折叠时**不销毁**(AG Grid 同一裁决):用户折叠再展开是浏览行为,
291
+ * 不是"我不要这批数据了"。销毁会让每次折叠展开都重新发一轮请求。
292
+ */
293
+ const children = new Map<string, SomaWindowHandle>();
294
+
295
+ const handle: SomaWindowHandle = {
296
+ get spec() { return spec; },
297
+ get rows() { return visibleRows(); },
298
+ get total() { return total; },
299
+ get selection(): SomaWindowSelection {
300
+ return { base: selection.base, toggled: [...selection.toggled] };
301
+ },
302
+ get loading() { return loading; },
303
+ get error() { return error; },
304
+ get blockCount() { return blocks.size; },
305
+ get start() { return start; },
306
+ get end() { return end; },
307
+ // 拷贝而不是交引用:与 buildRequest 同一理由——交出去的东西会被下一次 request 改写
308
+ get sort() { return sort.map((entry) => ({ ...entry })); },
309
+ get filter() { return filter === null ? null : cloneFilter(filter); },
310
+ get pendingCount() { return pending.size; },
311
+
312
+ async request(patch: SomaWindowRequestPatch): Promise<void> {
313
+ // 意图变了 = 旧块全部作废。「按金额排序的第 3 块」与「按时间排序的第 3 块」
314
+ // 是两批不同的行,留着它们等于让用户看到一份拼接自两种排序的列表。
315
+ const intentChanged = patch.sort !== undefined
316
+ || patch.filter !== undefined
317
+ || patch.group !== undefined
318
+ || patch.aggregate !== undefined;
319
+
320
+ if (patch.sort !== undefined) sort = patch.sort;
321
+ if (patch.filter !== undefined) filter = patch.filter;
322
+ if (patch.group !== undefined) group = patch.group;
323
+ if (patch.aggregate !== undefined) aggregate = patch.aggregate;
324
+
325
+ if (intentChanged) {
326
+ generation += 1;
327
+ if (!spec.cache.keep_previous) blocks.clear();
328
+ total = undefined;
329
+ // 换排序回第一页(REQ-008 的既有裁决):留在第 7 页看一份重排过的列表,
330
+ // 用户看到的是一批与他刚才所在位置毫无关系的行。
331
+ start = 0;
332
+ end = spec.block.size;
333
+ }
334
+ if (patch.start !== undefined) start = Math.max(0, patch.start);
335
+ if (patch.end !== undefined) end = Math.max(start, patch.end);
336
+
337
+ await (intentChanged ? ensureRange() : ensureRangeDebounced());
338
+ // 首次真的取过数之后才起重验证钟:挂载即起的话,一个从未被滚动到的
339
+ // 折叠区域也会开始周期性发请求。
340
+ startRevalidate();
341
+ },
342
+
343
+ select(patch: { toggle?: string[]; base?: 'none' | 'all' }): void {
344
+ if (patch.base !== undefined) {
345
+ // 换基线就清空反选集:反选集是相对基线记的,跨基线保留会把
346
+ // 「取消了这三行」翻转成「只选了这三行」。
347
+ selection.base = patch.base;
348
+ selection.toggled.clear();
349
+ }
350
+ for (const id of patch.toggle ?? []) {
351
+ if (selection.toggled.has(id)) selection.toggled.delete(id);
352
+ else selection.toggled.add(id);
353
+ }
354
+ notify();
355
+ },
356
+
357
+ isSelected(id: string): boolean {
358
+ // 基线 XOR 反选:base=all 时在 toggled 里表示"被取消",base=none 时表示"被选中"
359
+ return (selection.base === 'all') !== selection.toggled.has(id);
360
+ },
361
+
362
+ edit(id: string, field: string, value: unknown): void {
363
+ pending.set(id, { ...(pending.get(id) ?? {}), [field]: value });
364
+ notify();
365
+ },
366
+
367
+ async commit(tx?: SomaTransaction): Promise<SomaDataSubmitResult> {
368
+ if (!deps.commit) {
369
+ return { ok: false, message: '本数据对象没有声明 write: 段——窗口是只读的' };
370
+ }
371
+ const body: SomaTransaction = tx ?? {
372
+ update: [...pending.entries()].map(([id, patch]) => ({ [deps.idField]: id, ...patch })),
373
+ };
374
+ const result = await deps.commit(body);
375
+ if (destroyed) return result;
376
+ if (result.ok) {
377
+ // 成功即合并进块并清空暂存——不重取整个窗口:一次单元格编辑触发一轮
378
+ // 全量重取,在十万行的表上是灾难。
379
+ mergePendingIntoBlocks();
380
+ pending = new Map();
381
+ savepoints.length = 0;
382
+ }
383
+ notify();
384
+ return result;
385
+ },
386
+
387
+ savepoint(): number {
388
+ savepointSeq += 1;
389
+ const snapshot = new Map<string, Record<string, unknown>>();
390
+ for (const [id, patch] of pending) snapshot.set(id, { ...patch });
391
+ savepoints.push({ id: savepointSeq, snapshot });
392
+ // 有界栈:超出丢最早的。无界的撤销栈是内存泄漏,不是功能
393
+ if (savepoints.length > SAVEPOINT_LIMIT) savepoints.shift();
394
+ return savepointSeq;
395
+ },
396
+
397
+ revertTo(id: number): void {
398
+ const index = savepoints.findIndex((entry) => entry.id === id);
399
+ if (index === -1) return; // 已被挤出栈:静默,不是抛——撤销失败不该炸掉页面
400
+ const target = savepoints[index];
401
+ pending = new Map();
402
+ for (const [rowId, patch] of target.snapshot) pending.set(rowId, { ...patch });
403
+ savepoints.length = index; // 回到该点之后,它之后的存档点一并作废
404
+ notify();
405
+ },
406
+
407
+ /**
408
+ * 展开某个分组:拿到(必要时创建)那一层的窗口。
409
+ *
410
+ * 键路径是**累加**的:根是 `[]`,展开"华东"是 `['华东']`,
411
+ * 再展开"华东/上海"是 `['华东','上海']`。子窗口继承父的排序与过滤——
412
+ * 不继承的话,用户按金额排了序,展开一个分组看到的是未排序的子行。
413
+ */
414
+ drillDown(keys: readonly string[]): SomaWindowHandle | null {
415
+ if (group === null) return null;
416
+ if (keys.length === 0 || keys.length > group.by.length) return null;
417
+ const path = keys.join('\u0000');
418
+ const existing = children.get(path);
419
+ if (existing) return existing;
420
+
421
+ const child = createWindow(
422
+ {
423
+ ...spec,
424
+ sort,
425
+ filter,
426
+ group: { by: group.by, keys: [...keys] },
427
+ // 选择态不继承:子层的行 id 与父层的分组行不是一回事,
428
+ // 把父层的反选集带下去会让子行凭空处于"已选"状态
429
+ selection: { base: 'none', toggled: [] },
430
+ },
431
+ deps,
432
+ );
433
+ children.set(path, child);
434
+ return child;
435
+ },
436
+
437
+ /** 已展开的子窗口(诊断与批量销毁用) */
438
+ get childPaths(): string[] {
439
+ return [...children.keys()].map((path) => path.split('\u0000').join(' / '));
440
+ },
441
+
442
+ destroy(): void {
443
+ destroyed = true;
444
+ generation += 1;
445
+ if (debounceTimer !== null) clearTimeout(debounceTimer);
446
+ if (revalidateTimer !== null) clearInterval(revalidateTimer);
447
+ revalidateTimer = null;
448
+ blocks.clear();
449
+ pending.clear();
450
+ savepoints.length = 0;
451
+ for (const child of children.values()) child.destroy();
452
+ children.clear();
453
+ },
454
+ };
455
+
456
+ function mergePendingIntoBlocks(): void {
457
+ for (const block of blocks.values()) {
458
+ block.rows = block.rows.map((row) => {
459
+ const patch = pending.get(idOf(row));
460
+ return patch === undefined ? row : { ...(row as Record<string, unknown>), ...patch };
461
+ });
462
+ }
463
+ }
464
+
465
+ return handle;
466
+ }
467
+
468
+ /** 过滤树深拷贝:请求体不能与仍会被改写的声明共享结构 */
469
+ function cloneFilter(node: SomaWindowConfig['filter']): NonNullable<SomaWindowConfig['filter']> {
470
+ if (node === null) throw new Error('unreachable');
471
+ if ('join' in node) {
472
+ return { join: node.join, conditions: node.conditions.map((child) => cloneFilter(child)) };
473
+ }
474
+ return node.value === undefined
475
+ ? { field: node.field, op: node.op }
476
+ : { field: node.field, op: node.op, value: node.value };
477
+ }