soma-core 1.0.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 (78) hide show
  1. package/app/api/page/route.ts +97 -0
  2. package/app/globals.css +3 -0
  3. package/app/layout.tsx +18 -0
  4. package/app/page.tsx +129 -0
  5. package/bin/soma.cjs +2 -0
  6. package/core/base/SomaApi.ts +14 -0
  7. package/core/base/SomaDict.ts +168 -0
  8. package/core/base/SomaEntity.ts +41 -0
  9. package/core/base/SomaHttpClient.ts +126 -0
  10. package/core/base/SomaLocaleOnlyPageRoot.ts +4 -0
  11. package/core/base/SomaPageRootBase.ts +54 -0
  12. package/core/base/SomaValidator.ts +147 -0
  13. package/core/base/index.ts +7 -0
  14. package/core/compiler/full-manifest-builder.ts +43 -0
  15. package/core/compiler/manifest-compiler.ts +237 -0
  16. package/core/compiler/route-builder.ts +31 -0
  17. package/core/compiler/soma-precompile.ts +48 -0
  18. package/core/compiler/soma-webpack-loader.js +35 -0
  19. package/core/compiler/vite-plugin-soma.ts +73 -0
  20. package/core/container/SomaContainerAdapter.ts +169 -0
  21. package/core/diagnostics/SomaDiagnostics.ts +186 -0
  22. package/core/engine/asset-resolver.ts +67 -0
  23. package/core/engine/dom-renderer.ts +366 -0
  24. package/core/engine/event-engine.ts +287 -0
  25. package/core/engine/lis.ts +60 -0
  26. package/core/engine/reactive-proxy.ts +225 -0
  27. package/core/engine/render-engine.ts +264 -0
  28. package/core/engine/runtime-builder.ts +100 -0
  29. package/core/engine/scope-resolver.ts +252 -0
  30. package/core/engine/soma-bootstrap.ts +244 -0
  31. package/core/index.ts +6 -0
  32. package/core/infra/auth/IAuthService.ts +13 -0
  33. package/core/infra/auth/TokenAuthService.ts +98 -0
  34. package/core/infra/cache/ICache.ts +13 -0
  35. package/core/infra/cache/MemoryCache.ts +95 -0
  36. package/core/infra/cache/ServerFileCache.ts +123 -0
  37. package/core/infra/config/IConfig.ts +9 -0
  38. package/core/infra/config/SomaConfig.ts +85 -0
  39. package/core/infra/event-bus/IEventBus.ts +9 -0
  40. package/core/infra/event-bus/SomaEventBus.ts +53 -0
  41. package/core/infra/http/IHttpClient.ts +21 -0
  42. package/core/infra/http/SomaHttpService.ts +141 -0
  43. package/core/infra/i18n/DefaultI18n.ts +41 -0
  44. package/core/infra/i18n/II18n.ts +7 -0
  45. package/core/infra/logger/ConsoleLogger.ts +81 -0
  46. package/core/infra/logger/ILogger.ts +19 -0
  47. package/core/infra/notify/DefaultNotifyService.ts +31 -0
  48. package/core/infra/notify/INotifyService.ts +14 -0
  49. package/core/infra/permission/IPermission.ts +10 -0
  50. package/core/infra/permission/SomaPermission.ts +48 -0
  51. package/core/infra/router/IRouter.ts +19 -0
  52. package/core/infra/router/SomaRouter.ts +66 -0
  53. package/core/infra/storage/IStorageService.ts +7 -0
  54. package/core/infra/storage/MemoryStorageService.ts +53 -0
  55. package/core/infra/timer/ITimer.ts +9 -0
  56. package/core/infra/timer/SomaTimer.ts +118 -0
  57. package/core/middleware/SomaMiddlewareChain.ts +29 -0
  58. package/core/parser/pipeline-parser.ts +276 -0
  59. package/core/parser/ui-config-parser.ts +336 -0
  60. package/core/parser/yaml-loader.ts +36 -0
  61. package/core/router/RouteHandler.ts +93 -0
  62. package/core/runtime/SomaSnapshotStore.ts +98 -0
  63. package/core/scheduler/SomaScheduler.ts +190 -0
  64. package/core/types/domain.types.ts +88 -0
  65. package/core/types/engine.types.ts +35 -0
  66. package/core/types/event.types.ts +57 -0
  67. package/core/types/keyboard.types.ts +18 -0
  68. package/core/types/manifest.types.ts +30 -0
  69. package/core/types/scheduler.types.ts +10 -0
  70. package/core/types/ui-config.types.ts +89 -0
  71. package/core/validation/contract-validator.ts +465 -0
  72. package/dist/cli/soma.js +49 -0
  73. package/global.d.ts +14 -0
  74. package/next.config.js +61 -0
  75. package/package.json +77 -0
  76. package/postcss.config.js +6 -0
  77. package/tailwind.config.ts +21 -0
  78. package/tsconfig.json +35 -0
@@ -0,0 +1,366 @@
1
+ import type { SomaContainerAdapter } from '../container/SomaContainerAdapter';
2
+ import type { SomaCompiledBinding } from '../types/manifest.types';
3
+ import type { BindingEntry } from '../types/engine.types';
4
+ import type { ShowMapping } from '../types/ui-config.types';
5
+ import type { SomaScopeResolver } from './scope-resolver';
6
+ import { longestIncreasingSubsequence } from './lis';
7
+
8
+ export type ModelWriteBack = (path: string, value: string) => void;
9
+
10
+ export class SomaDomRenderer {
11
+ private adapter: SomaContainerAdapter | null = null;
12
+ private resolver: SomaScopeResolver | null = null;
13
+ private scopeTracker: WeakMap<HTMLElement, any> | null = null;
14
+ private modelWriteBack: ModelWriteBack | null = null;
15
+ private modelListeners = new WeakSet<HTMLElement>();
16
+ private modelAbort = new AbortController();
17
+
18
+ init(
19
+ adapter: SomaContainerAdapter,
20
+ resolver: SomaScopeResolver,
21
+ scopeTracker: WeakMap<HTMLElement, any>,
22
+ ): void {
23
+ this.adapter = adapter;
24
+ this.resolver = resolver;
25
+ this.scopeTracker = scopeTracker;
26
+ }
27
+
28
+ setModelWriteBack(fn: ModelWriteBack): void {
29
+ this.modelWriteBack = fn;
30
+ }
31
+
32
+ bindEntry(binding: SomaCompiledBinding, container: HTMLElement): BindingEntry | null {
33
+ if (!this.adapter) {
34
+ return null;
35
+ }
36
+
37
+ const element = this.adapter.findAnchor(container, binding.somaId);
38
+ if (!element) {
39
+ return null;
40
+ }
41
+
42
+ const entry: BindingEntry = {
43
+ somaId: binding.somaId,
44
+ dataPath: binding.dataPath,
45
+ watchPaths: binding.watchPaths,
46
+ element,
47
+ type: binding.type,
48
+ templateCache:
49
+ binding.type === 'list' || binding.type === 'obj'
50
+ ? this.adapter.cloneTemplate(element) ?? undefined
51
+ : undefined,
52
+ childShowConfig: binding.childShowConfig,
53
+ attrName: binding.attrName,
54
+ negate: binding.negate,
55
+ classRules: binding.classRules,
56
+ };
57
+
58
+ // 编译渲染函数:消除运行时 switch + 类型判断
59
+ entry.compiledRender = this.compileRenderFn(entry);
60
+
61
+ return entry;
62
+ }
63
+
64
+ /**
65
+ * 为 binding 编译专用的渲染闭包。
66
+ *
67
+ * 类似 C++ 编译器将 switch/case 消除为直接函数指针调用:
68
+ * - text 绑定编译为 (v) => el.textContent = String(v)
69
+ * - attr 绑定编译为 (v) => el.setAttribute('src', String(v))
70
+ * - when 绑定编译为 (v) => el.style.display = v ? '' : 'none'
71
+ *
72
+ * 运行时路径:compiledRender(value) → 1 次函数调用 → 1 次 DOM 操作
73
+ * 之前路径:renderEntry(entry, value) → switch 7 分支 → 类型判断 → DOM 操作
74
+ */
75
+ private compileRenderFn(entry: BindingEntry): (value: any) => void {
76
+ const adapter = this.adapter!;
77
+ const el = entry.element;
78
+
79
+ switch (entry.type) {
80
+ case 'text':
81
+ return (v) => {
82
+ if (v != null && typeof v !== 'object') {
83
+ adapter.setText(el, String(v));
84
+ }
85
+ };
86
+
87
+ case 'attr': {
88
+ const attrName = entry.attrName!;
89
+ return (v) => {
90
+ if (v != null && typeof v !== 'object') {
91
+ adapter.setAttribute(el, attrName, String(v));
92
+ }
93
+ };
94
+ }
95
+
96
+ case 'html':
97
+ return (v) => adapter.setHtml(el, String(v ?? ''));
98
+
99
+ case 'model': {
100
+ const modelEl = el;
101
+ const modelAdapter = adapter;
102
+ const modelListeners = this.modelListeners;
103
+ const modelWriteBack = this.modelWriteBack;
104
+ const modelAbort = this.modelAbort;
105
+ const dataPath = entry.dataPath;
106
+ const self = this;
107
+ return (v) => {
108
+ const strValue = String(v ?? '');
109
+ if (modelAdapter.getValue(modelEl) !== strValue) {
110
+ modelAdapter.setValue(modelEl, strValue);
111
+ }
112
+ if (modelWriteBack && !modelListeners.has(modelEl)) {
113
+ modelListeners.add(modelEl);
114
+ modelAdapter.listen(
115
+ modelEl,
116
+ 'input',
117
+ () => {
118
+ modelWriteBack(dataPath, self.adapter!.getValue(modelEl));
119
+ },
120
+ modelAbort.signal,
121
+ );
122
+ }
123
+ };
124
+ }
125
+
126
+ case 'when': {
127
+ if (entry.negate) {
128
+ return (v) => adapter.setVisibility(el, !v);
129
+ }
130
+ return (v) => adapter.setVisibility(el, !!v);
131
+ }
132
+
133
+ case 'class': {
134
+ if (!entry.classRules || !this.resolver) {
135
+ return () => {};
136
+ }
137
+ // 预解析 class 规则:将 "a b c" 拆分为数组,避免运行时 split
138
+ const resolver = this.resolver;
139
+ const rules = Object.entries(entry.classRules).map(([classes, condPath]) => ({
140
+ classList: classes.split(' ').filter(Boolean),
141
+ condPath,
142
+ }));
143
+ return () => {
144
+ for (const rule of rules) {
145
+ const enabled = !!resolver.readFromRootCompiled(rule.condPath);
146
+ adapter.toggleClasses(el, rule.classList, enabled);
147
+ }
148
+ };
149
+ }
150
+
151
+ case 'list':
152
+ return (v) => {
153
+ if (Array.isArray(v)) this.renderList(entry, v);
154
+ };
155
+
156
+ case 'obj':
157
+ return (v) => {
158
+ if (v && typeof v === 'object') this.renderObj(entry, v);
159
+ };
160
+
161
+ default:
162
+ return (v) => this.renderEntry(entry, v);
163
+ }
164
+ }
165
+
166
+ destroy(): void {
167
+ this.modelAbort.abort();
168
+ this.modelAbort = new AbortController();
169
+ this.modelListeners = new WeakSet<HTMLElement>();
170
+ this.modelWriteBack = null;
171
+ }
172
+
173
+ renderEntry(entry: BindingEntry, value: any): void {
174
+ if (!this.adapter) return;
175
+ // 所有 entry 在 bindEntry 时已编译 compiledRender,直接调用
176
+ entry.compiledRender!(value);
177
+ }
178
+
179
+ private renderList(entry: BindingEntry, dataArray: any[]): void {
180
+ if (!this.adapter || !entry.templateCache) {
181
+ return;
182
+ }
183
+
184
+ // Key-based diff:如果列表项有 id 或 key 属性,尝试复用 DOM 节点
185
+ const hasKey = dataArray.length > 0 && dataArray[0] != null &&
186
+ typeof dataArray[0] === 'object' && ('id' in dataArray[0] || 'key' in dataArray[0]);
187
+
188
+ if (!hasKey) {
189
+ // 无 key 时保持全量更新
190
+ this.adapter.clearRenderedChildren(entry.element);
191
+ for (const itemData of dataArray) {
192
+ this.appendListItem(entry, itemData);
193
+ }
194
+ return;
195
+ }
196
+
197
+ const keyProp = 'id' in dataArray[0] ? 'id' : 'key';
198
+
199
+ // ── 阶段 1:收集旧节点 key → { element, index } ──
200
+ const oldChildren: HTMLElement[] = [];
201
+ const oldKeyMap = new Map<string, { el: HTMLElement; index: number }>();
202
+ let idx = 0;
203
+ for (const child of Array.from(entry.element.children)) {
204
+ if (child.tagName === 'TEMPLATE') continue;
205
+ const el = child as HTMLElement;
206
+ const nodeKey = el.getAttribute('data-soma-key');
207
+ if (nodeKey) {
208
+ oldKeyMap.set(nodeKey, { el, index: idx });
209
+ oldChildren.push(el);
210
+ }
211
+ idx++;
212
+ }
213
+
214
+ const newKeys = dataArray.map(item => String(item[keyProp]));
215
+ const newKeySet = new Set(newKeys);
216
+
217
+ // ── 阶段 2:删除不再存在的旧节点 ──
218
+ for (const [key, { el }] of oldKeyMap) {
219
+ if (!newKeySet.has(key)) {
220
+ el.remove();
221
+ oldKeyMap.delete(key);
222
+ }
223
+ }
224
+
225
+ // ── 阶段 3:构建新 key 在旧序列中的位置数组,用于 LIS ──
226
+ // source[i] = 新列表第 i 项在旧列表中的位置,-1 表示新增
227
+ const source = new Array(newKeys.length).fill(-1);
228
+ const newElements: (HTMLElement | null)[] = new Array(newKeys.length).fill(null);
229
+
230
+ for (let i = 0; i < newKeys.length; i++) {
231
+ const old = oldKeyMap.get(newKeys[i]);
232
+ if (old) {
233
+ source[i] = old.index;
234
+ newElements[i] = old.el;
235
+ // 更新数据
236
+ this.scopeTracker?.set(old.el, dataArray[i]);
237
+ if (entry.childShowConfig) {
238
+ this.applyShowConfig(old.el, dataArray[i], entry.childShowConfig);
239
+ }
240
+ }
241
+ }
242
+
243
+ // ── 阶段 4:计算最长递增子序列(LIS),最小化 DOM 移动 ──
244
+ const lisIndices = longestIncreasingSubsequence(source);
245
+ const lisSet = new Set(lisIndices);
246
+
247
+ // ── 阶段 5:从后往前遍历,插入/移动不在 LIS 中的节点 ──
248
+ // 这样后面的节点已经就位,可以作为 insertBefore 的锚点
249
+ let nextSibling: Node | null = null;
250
+ for (let i = newKeys.length - 1; i >= 0; i--) {
251
+ if (source[i] === -1) {
252
+ // 新增节点:克隆模板
253
+ const fragment = entry.templateCache.cloneNode(true) as DocumentFragment;
254
+ const wrapper = fragment.firstElementChild as HTMLElement | null;
255
+ if (!wrapper) continue;
256
+
257
+ wrapper.setAttribute('data-soma-key', newKeys[i]);
258
+ this.scopeTracker?.set(wrapper, dataArray[i]);
259
+ if (entry.childShowConfig) {
260
+ this.applyShowConfig(wrapper, dataArray[i], entry.childShowConfig);
261
+ }
262
+
263
+ if (nextSibling) {
264
+ entry.element.insertBefore(wrapper, nextSibling);
265
+ } else {
266
+ entry.element.appendChild(wrapper);
267
+ }
268
+ newElements[i] = wrapper;
269
+ } else if (!lisSet.has(i)) {
270
+ // 需要移动的旧节点(不在 LIS 中)
271
+ const el = newElements[i]!;
272
+ if (nextSibling) {
273
+ entry.element.insertBefore(el, nextSibling);
274
+ } else {
275
+ entry.element.appendChild(el);
276
+ }
277
+ }
278
+ // LIS 中的节点不需要移动
279
+
280
+ nextSibling = newElements[i];
281
+ }
282
+ }
283
+
284
+ private appendListItem(entry: BindingEntry, itemData: any): void {
285
+ if (!this.adapter || !entry.templateCache) return;
286
+
287
+ const fragment = entry.templateCache.cloneNode(true) as DocumentFragment;
288
+ const wrapper = fragment.firstElementChild as HTMLElement | null;
289
+ if (!wrapper) return;
290
+
291
+ this.scopeTracker?.set(wrapper, itemData);
292
+ if (entry.childShowConfig) {
293
+ this.applyShowConfig(wrapper, itemData, entry.childShowConfig);
294
+ }
295
+
296
+ this.adapter.appendFragment(entry.element, fragment);
297
+ }
298
+
299
+ private renderObj(entry: BindingEntry, data: object): void {
300
+ if (!this.adapter || !entry.templateCache) {
301
+ return;
302
+ }
303
+
304
+ this.adapter.clearRenderedChildren(entry.element);
305
+ const fragment = entry.templateCache.cloneNode(true) as DocumentFragment;
306
+ const wrapper = fragment.firstElementChild as HTMLElement | null;
307
+ if (!wrapper) {
308
+ return;
309
+ }
310
+
311
+ this.scopeTracker?.set(wrapper, data);
312
+ if (entry.childShowConfig) {
313
+ this.applyShowConfig(wrapper, data, entry.childShowConfig);
314
+ }
315
+
316
+ this.adapter.appendFragment(entry.element, fragment);
317
+ }
318
+
319
+ private applyShowConfig(
320
+ root: HTMLElement,
321
+ data: any,
322
+ showConfig: ShowMapping,
323
+ ): void {
324
+ for (const [rawKey, config] of Object.entries(showConfig)) {
325
+ if (typeof config !== 'string') {
326
+ continue;
327
+ }
328
+
329
+ const [somaId, attrName] = rawKey.split('@');
330
+ const element = root.querySelector<HTMLElement>(`[data-soma-id="${somaId}"]`);
331
+ if (!element) {
332
+ continue;
333
+ }
334
+
335
+ const value = this.resolveShowValue(config, data);
336
+ if (attrName === 'html') {
337
+ this.adapter?.setHtml(element, String(value ?? ''));
338
+ continue;
339
+ }
340
+
341
+ if (attrName) {
342
+ if (value != null) {
343
+ this.adapter?.setAttribute(element, attrName, String(value));
344
+ }
345
+ continue;
346
+ }
347
+
348
+ this.adapter?.setText(element, value != null ? String(value) : '--');
349
+ }
350
+ }
351
+
352
+ private resolveShowValue(valuePath: string, itemData: any): any {
353
+ const segments = valuePath.split('.');
354
+ const firstSeg = segments[0];
355
+
356
+ if (this.resolver && this.resolver.hasVar(firstSeg)) {
357
+ const varPath = this.resolver.getVarPath(firstSeg);
358
+ if (!varPath) {
359
+ return this.resolver.readFromRoot(segments.slice(1).join('.'));
360
+ }
361
+ return segments.slice(1).reduce((obj: any, key: string) => obj?.[key], itemData);
362
+ }
363
+
364
+ return segments.reduce((obj: any, key: string) => obj?.[key], itemData);
365
+ }
366
+ }
@@ -0,0 +1,287 @@
1
+ import type { SomaContainerAdapter } from '../container/SomaContainerAdapter';
2
+ import { SOMA_KEY_MODIFIERS } from '../types/keyboard.types';
3
+ import type { SomaDiagnostics } from '../diagnostics/SomaDiagnostics';
4
+ import { SomaMiddlewareChain } from '../middleware/SomaMiddlewareChain';
5
+ import { SomaScheduler } from '../scheduler/SomaScheduler';
6
+ import type { SomaCompiledEvent, SomaRuntimeManifest } from '../types/manifest.types';
7
+ import type { InteractAction } from '../types/event.types';
8
+ import type { SomaScopeResolver } from './scope-resolver';
9
+
10
+ export interface SomaEventMiddlewareContext {
11
+ config: SomaCompiledEvent;
12
+ element: HTMLElement;
13
+ originalEvent: Event;
14
+ currentVar: any;
15
+ status: 'success' | 'blocked' | 'error';
16
+ message?: string;
17
+ }
18
+
19
+ export interface SomaEventEngineOptions<TContext extends Record<string, unknown> = Record<string, never>> {
20
+ manifest: SomaRuntimeManifest;
21
+ container: HTMLElement;
22
+ adapter: SomaContainerAdapter;
23
+ resolver: SomaScopeResolver;
24
+ scopeTracker: WeakMap<HTMLElement, any>;
25
+ callbacks: {
26
+ onRefresh: () => void | Promise<void>;
27
+ onFlush: () => void | Promise<void>;
28
+ };
29
+ diagnostics?: SomaDiagnostics;
30
+ scheduler?: SomaScheduler;
31
+ middleware?: SomaMiddlewareChain<any>;
32
+ eventContextFactory?: (
33
+ config: SomaCompiledEvent,
34
+ element: HTMLElement,
35
+ originalEvent: Event,
36
+ ) => TContext;
37
+ }
38
+
39
+ export class SomaEventEngine<TContext extends Record<string, unknown> = Record<string, never>> {
40
+ private readonly manifest: SomaRuntimeManifest;
41
+ private readonly container: HTMLElement;
42
+ private readonly adapter: SomaContainerAdapter;
43
+ private readonly resolver: SomaScopeResolver;
44
+ private readonly scopeTracker: WeakMap<HTMLElement, any>;
45
+ private readonly callbacks: {
46
+ onRefresh: () => void | Promise<void>;
47
+ onFlush: () => void | Promise<void>;
48
+ };
49
+ private readonly diagnostics: SomaDiagnostics | null;
50
+ private readonly scheduler: SomaScheduler;
51
+ private readonly middleware: SomaMiddlewareChain<any> | null;
52
+ private readonly eventContextFactory?: (
53
+ config: SomaCompiledEvent,
54
+ element: HTMLElement,
55
+ originalEvent: Event,
56
+ ) => TContext;
57
+ private readonly pendingSet = new Set<string>();
58
+ private readonly abortController = new AbortController();
59
+
60
+ constructor(options: SomaEventEngineOptions<TContext>) {
61
+ this.manifest = options.manifest;
62
+ this.container = options.container;
63
+ this.adapter = options.adapter;
64
+ this.resolver = options.resolver;
65
+ this.scopeTracker = options.scopeTracker;
66
+ this.callbacks = options.callbacks;
67
+ this.diagnostics = options.diagnostics ?? null;
68
+ this.scheduler = options.scheduler ?? new SomaScheduler();
69
+ this.middleware = options.middleware ?? null;
70
+ this.eventContextFactory = options.eventContextFactory;
71
+ }
72
+
73
+ init(): void {
74
+ const eventTypes = new Set<string>();
75
+ for (const event of this.manifest.events) {
76
+ eventTypes.add(event.domEvent ?? 'click');
77
+ }
78
+
79
+ for (const eventType of eventTypes) {
80
+ this.adapter.listen(
81
+ this.container,
82
+ eventType,
83
+ (event) => {
84
+ const target = this.adapter.findClosestAnchor(event.target);
85
+ if (!target) {
86
+ return;
87
+ }
88
+
89
+ const somaId = this.adapter.getAnchorId(target);
90
+ if (!somaId) {
91
+ return;
92
+ }
93
+
94
+ const config = this.manifest.eventIndex.get(`${eventType}:${somaId}`);
95
+ if (config) {
96
+ void this.execute(config, target, event);
97
+ }
98
+ },
99
+ this.abortController.signal,
100
+ );
101
+ }
102
+ }
103
+
104
+ execute(config: SomaCompiledEvent, element: HTMLElement, originalEvent: Event): Promise<void> {
105
+ return this.scheduler.schedule(
106
+ () => this.executeNow(config, element, originalEvent),
107
+ {
108
+ priority: config.priority,
109
+ label: `event:${config.eventKey}`,
110
+ },
111
+ );
112
+ }
113
+
114
+ destroy(): void {
115
+ this.abortController.abort();
116
+ this.pendingSet.clear();
117
+ }
118
+
119
+ private async executeNow(
120
+ config: SomaCompiledEvent,
121
+ element: HTMLElement,
122
+ originalEvent: Event,
123
+ ): Promise<void> {
124
+ const startedAt = this.adapter.now();
125
+ const currentVar = this.getContext(element);
126
+ const context = {
127
+ config,
128
+ element,
129
+ originalEvent,
130
+ currentVar,
131
+ status: 'success' as 'success' | 'blocked' | 'error',
132
+ message: undefined as string | undefined,
133
+ ...(this.eventContextFactory?.(config, element, originalEvent) ?? {} as TContext),
134
+ };
135
+
136
+ const terminal = async (runtime: SomaEventMiddlewareContext & TContext): Promise<void> => {
137
+ if (!this.preCheck(config, config.somaId)) {
138
+ runtime.status = 'blocked';
139
+ runtime.message = 'pre-check rejected';
140
+ return;
141
+ }
142
+
143
+ if (config.keyModifier && originalEvent instanceof KeyboardEvent) {
144
+ if (originalEvent.key !== (SOMA_KEY_MODIFIERS[config.keyModifier] ?? config.keyModifier)) {
145
+ runtime.status = 'blocked';
146
+ runtime.message = `key modifier mismatch: expected ${config.keyModifier}`;
147
+ return;
148
+ }
149
+ }
150
+
151
+ let result = true;
152
+ if (config.funcPath && config.type !== 'NAV_STATIC') {
153
+ try {
154
+ this.pendingSet.add(config.somaId);
155
+ const fn = this.resolveFunction(config.funcPath, currentVar);
156
+ result = await fn(currentVar, originalEvent);
157
+ } catch (error) {
158
+ runtime.status = 'error';
159
+ runtime.message = error instanceof Error ? error.message : String(error);
160
+ result = false;
161
+ } finally {
162
+ this.pendingSet.delete(config.somaId);
163
+ }
164
+ }
165
+
166
+ if (result !== false) {
167
+ await this.callbacks.onFlush();
168
+ await this.postAction(config, element);
169
+ } else if (runtime.status !== 'error') {
170
+ runtime.status = 'blocked';
171
+ runtime.message = runtime.message ?? 'business handler returned false';
172
+ }
173
+ };
174
+
175
+ if (this.middleware) {
176
+ await this.middleware.execute(context, terminal);
177
+ } else {
178
+ await terminal(context);
179
+ }
180
+
181
+ this.diagnostics?.recordEvent({
182
+ somaId: config.somaId,
183
+ domEvent: config.domEvent ?? 'click',
184
+ eventType: config.type,
185
+ funcPath: config.funcPath,
186
+ status: context.status,
187
+ durationMs: this.adapter.now() - startedAt,
188
+ message: context.message,
189
+ });
190
+ }
191
+
192
+ private getContext(element: HTMLElement): any {
193
+ let current: HTMLElement | null = element;
194
+ while (current && current !== this.container) {
195
+ const context = this.scopeTracker.get(current);
196
+ if (context !== undefined) {
197
+ return context;
198
+ }
199
+ current = current.parentElement;
200
+ }
201
+ return undefined;
202
+ }
203
+
204
+ private preCheck(config: SomaCompiledEvent, somaId: string): boolean {
205
+ if (this.pendingSet.has(somaId)) {
206
+ return false;
207
+ }
208
+
209
+ if ((config as { confirm?: string }).confirm) {
210
+ return this.adapter.confirm((config as { confirm?: string }).confirm!);
211
+ }
212
+
213
+ return true;
214
+ }
215
+
216
+ private async postAction(config: SomaCompiledEvent, element: HTMLElement): Promise<void> {
217
+ switch (config.type) {
218
+ case 'NAV_STATIC':
219
+ case 'NAV_ACTION':
220
+ if (config.targetUrl) {
221
+ this.adapter.navigate(config.targetUrl);
222
+ }
223
+ break;
224
+
225
+ case 'UI_REFRESH':
226
+ await this.callbacks.onRefresh();
227
+ break;
228
+
229
+ case 'UI_INTERACT':
230
+ this.handleInteraction(config, element);
231
+ break;
232
+ }
233
+ }
234
+
235
+ private handleInteraction(config: SomaCompiledEvent, triggerEl: HTMLElement): void {
236
+ const targetId = config.targetId;
237
+ const action: InteractAction = config.action || 'toggle';
238
+ const targetEl =
239
+ !targetId || targetId === 'self'
240
+ ? triggerEl
241
+ : this.adapter.findAnchor(this.container, targetId);
242
+
243
+ if (!targetEl) {
244
+ return;
245
+ }
246
+
247
+ switch (action) {
248
+ case 'open':
249
+ this.adapter.setVisibility(targetEl, true);
250
+ break;
251
+ case 'close':
252
+ this.adapter.setVisibility(targetEl, false);
253
+ break;
254
+ case 'toggle':
255
+ this.adapter.setVisibility(targetEl, !this.adapter.isVisible(targetEl));
256
+ break;
257
+ }
258
+ }
259
+
260
+ private resolveFunction(funcPath: string, currentVar: any): Function {
261
+ const segments = funcPath.split('.');
262
+ const rootToken = segments[0];
263
+
264
+ // When the root token refers to a list-item var alias and we have a
265
+ // concrete item context, resolve the function directly on that item rather
266
+ // than on the root instance.
267
+ if (currentVar !== undefined && this.resolver.isListVar(rootToken)) {
268
+ let current = currentVar;
269
+ let owner = currentVar;
270
+ for (let index = 1; index < segments.length; index++) {
271
+ owner = current;
272
+ current = current?.[segments[index]];
273
+ if (current === undefined) {
274
+ throw new Error(`[SomaEventEngine] Cannot resolve "${segments[index]}" in "${funcPath}"`);
275
+ }
276
+ }
277
+
278
+ if (typeof current !== 'function') {
279
+ throw new Error(`[SomaEventEngine] "${funcPath}" is not a function`);
280
+ }
281
+
282
+ return current.bind(owner);
283
+ }
284
+
285
+ return this.resolver.resolveFunction(funcPath);
286
+ }
287
+ }
@@ -0,0 +1,60 @@
1
+ // core/engine/lis.ts
2
+ // 最长递增子序列(LIS)算法 — 用于列表 diff 最小化 DOM 移动
3
+ // O(n log n) 时间,O(n) 空间
4
+
5
+ /**
6
+ * 计算 source 数组中值 >= 0 的最长严格递增子序列。
7
+ * 返回值为这些元素在 source 中的索引数组。
8
+ *
9
+ * source 中值为 -1 的位置被跳过(表示新增项,无旧位置)。
10
+ *
11
+ * @param source - 新列表中每个元素在旧列表中的位置,-1 表示新增
12
+ * @returns 构成 LIS 的索引数组(在 source 中的位置)
13
+ */
14
+ export function longestIncreasingSubsequence(source: number[]): number[] {
15
+ const n = source.length;
16
+ if (n === 0) return [];
17
+
18
+ // tails[i] = 长度为 i+1 的递增子序列的最小末尾值
19
+ const tails: number[] = [];
20
+ // tailIndices[i] = tails[i] 对应的 source 索引
21
+ const tailIndices: number[] = [];
22
+ // prev[i] = source[i] 在 LIS 中的前驱索引
23
+ const prev = new Array<number>(n).fill(-1);
24
+
25
+ for (let i = 0; i < n; i++) {
26
+ if (source[i] === -1) continue;
27
+
28
+ const val = source[i];
29
+
30
+ // 二分查找 tails 中第一个 >= val 的位置
31
+ let lo = 0;
32
+ let hi = tails.length;
33
+ while (lo < hi) {
34
+ const mid = (lo + hi) >> 1;
35
+ if (tails[mid] < val) {
36
+ lo = mid + 1;
37
+ } else {
38
+ hi = mid;
39
+ }
40
+ }
41
+
42
+ tails[lo] = val;
43
+ tailIndices[lo] = i;
44
+
45
+ if (lo > 0) {
46
+ prev[i] = tailIndices[lo - 1];
47
+ }
48
+ }
49
+
50
+ // 回溯重建 LIS
51
+ const result: number[] = [];
52
+ let k = tailIndices[tails.length - 1];
53
+ for (let i = tails.length - 1; i >= 0; i--) {
54
+ result.push(k);
55
+ k = prev[k];
56
+ }
57
+
58
+ result.reverse();
59
+ return result;
60
+ }