@geastack/geatsc-plugin-gea 0.1.6

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 (63) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +37 -0
  3. package/dist/analyze.d.ts +4 -0
  4. package/dist/analyze.js +195 -0
  5. package/dist/cpp-canvas-colors.d.ts +4 -0
  6. package/dist/cpp-canvas-colors.js +226 -0
  7. package/dist/cpp-field-access.d.ts +49 -0
  8. package/dist/cpp-field-access.js +144 -0
  9. package/dist/cpp-ir-dom-style.d.ts +1 -0
  10. package/dist/cpp-ir-dom-style.js +49 -0
  11. package/dist/cpp-ir.d.ts +30 -0
  12. package/dist/cpp-ir.js +2426 -0
  13. package/dist/cpp-keyed-component-diagnostics.d.ts +8 -0
  14. package/dist/cpp-keyed-component-diagnostics.js +74 -0
  15. package/dist/cpp-keyed-list-diagnostics.d.ts +17 -0
  16. package/dist/cpp-keyed-list-diagnostics.js +84 -0
  17. package/dist/cpp-mounted-lowering.d.ts +81 -0
  18. package/dist/cpp-mounted-lowering.js +2235 -0
  19. package/dist/cpp-mounted.d.ts +25 -0
  20. package/dist/cpp-mounted.js +1376 -0
  21. package/dist/cpp-reactive-component-diagnostics.d.ts +2 -0
  22. package/dist/cpp-reactive-component-diagnostics.js +76 -0
  23. package/dist/cpp-reactive-component.d.ts +14 -0
  24. package/dist/cpp-reactive-component.js +349 -0
  25. package/dist/cpp-replacements.d.ts +14 -0
  26. package/dist/cpp-replacements.js +787 -0
  27. package/dist/cpp-source-replacements.d.ts +11 -0
  28. package/dist/cpp-source-replacements.js +257 -0
  29. package/dist/cpp-store-hub.d.ts +7 -0
  30. package/dist/cpp-store-hub.js +160 -0
  31. package/dist/cpp-store-method-body-parser.d.ts +2 -0
  32. package/dist/cpp-store-method-body-parser.js +392 -0
  33. package/dist/cpp-store-method-context.d.ts +48 -0
  34. package/dist/cpp-store-method-context.js +114 -0
  35. package/dist/cpp-store-method-expressions.d.ts +12 -0
  36. package/dist/cpp-store-method-expressions.js +1263 -0
  37. package/dist/cpp-store-method-replacements.d.ts +5 -0
  38. package/dist/cpp-store-method-replacements.js +1521 -0
  39. package/dist/cpp-store-method-targets.d.ts +19 -0
  40. package/dist/cpp-store-method-targets.js +296 -0
  41. package/dist/cpp-store-typed-arrays.d.ts +2 -0
  42. package/dist/cpp-store-typed-arrays.js +655 -0
  43. package/dist/cpp-stores.d.ts +73 -0
  44. package/dist/cpp-stores.js +1739 -0
  45. package/dist/cpp-template-renderer.d.ts +23 -0
  46. package/dist/cpp-template-renderer.js +3530 -0
  47. package/dist/css-style-declaration-shims.d.ts +3 -0
  48. package/dist/css-style-declaration-shims.js +47 -0
  49. package/dist/host-declarations.d.ts +11 -0
  50. package/dist/host-declarations.js +320 -0
  51. package/dist/host-shims.d.ts +3 -0
  52. package/dist/host-shims.js +3217 -0
  53. package/dist/index.d.ts +3 -0
  54. package/dist/index.js +1239 -0
  55. package/dist/load-ir.d.ts +7 -0
  56. package/dist/load-ir.js +40 -0
  57. package/dist/types.d.ts +604 -0
  58. package/dist/types.js +1 -0
  59. package/dist/utils.d.ts +26 -0
  60. package/dist/utils.js +723 -0
  61. package/dist/validate.d.ts +3 -0
  62. package/dist/validate.js +226 -0
  63. package/package.json +57 -0
@@ -0,0 +1,1376 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { canTemplateMountComponent, parseTemplateRoot, templateMountedRenderer } from './cpp-template-renderer.js';
3
+ import { attributeLines, fieldNameForSlot, isRootSetupSlot, keyedListKeyExpression, keyedListPayload, lowerRowSlots, lowerSlots, mountSlotAttrs, mountSlotImageSourceLines, parseMountAttr, mountSlotStyleSlot, mountSlotTag, parseHtmlRoot, rootSetupLines, rootSetupSlotsSupported, slotAttrName, storeFieldLocalName, storeGlobalIsTyped, stringLiteralValue, unique, } from './cpp-mounted-lowering.js';
4
+ import { cppString, sanitizeCppIdentifier } from './utils.js';
5
+ import { BoxedStoreFieldAccess, reactiveChildInstanceExpression, TypedSelfFieldAccess } from './cpp-field-access.js';
6
+ import { storeHubEmissionEnabled } from './cpp-store-hub.js';
7
+ import ts from 'typescript';
8
+ // Circular at module level (cpp-replacements imports this file back), but both
9
+ // sides only call each other inside function bodies, never during evaluation —
10
+ // the same reason the canMount callbacks below are injected instead of imported.
11
+ import { componentStoreReferences } from './cpp-replacements.js';
12
+ // EXPERIMENTAL (ReactiveComponent): a self-store component renders through the
13
+ // SAME template renderer as every other component, but with typed field access —
14
+ // `read_App_field_x(store)` resolves to the `shared_ptr<App>` overload reading
15
+ // the Signal field, bindings are per-field `store->dep.subscribe(...)`, and
16
+ // events call `store->method(...)` directly. Child-component mounts compose
17
+ // with the regular BOXED renderer, with the store argument resolved per child
18
+ // (see typedChildMountStoreArg). Templates that still can't mount a child
19
+ // surface the gea-unmountable-reactive-component diagnostic instead of a
20
+ // silent black screen.
21
+ // Re-entry guard for nested reactive mounts: generating A's renderer gates
22
+ // child <B/> by generating B's renderer, which may gate <A/> right back. A
23
+ // genuine A→B→A mount cycle must fail (null → diagnostic), not recurse forever.
24
+ const selfStoreRenderersInProgress = new Set();
25
+ export function selfStoreMountedRenderer(component, components, storeFields, storeArrayFields, constants = new Map(), storeMethods = []) {
26
+ if (!component.reactiveState)
27
+ return null;
28
+ if (selfStoreRenderersInProgress.has(component.id))
29
+ return null;
30
+ selfStoreRenderersInProgress.add(component.id);
31
+ try {
32
+ const childStoreArgs = new Map();
33
+ const childStoreArg = (child) => {
34
+ if (child === component)
35
+ return null;
36
+ const cached = childStoreArgs.get(child.id);
37
+ if (cached !== undefined)
38
+ return cached;
39
+ childStoreArgs.set(child.id, null); // cycle guard while the child renders
40
+ const resolved = typedChildMountStoreArg(child, components, storeFields, storeArrayFields, constants, storeMethods);
41
+ childStoreArgs.set(child.id, resolved);
42
+ return resolved;
43
+ };
44
+ const canMountTypedChild = (child) => childStoreArg(child) !== null;
45
+ return templateMountedRenderer(component, components, storeFields, constants, canMountTypedChild, storeMethods, new TypedSelfFieldAccess(component.exportName, childStoreArg), storeArrayFields);
46
+ }
47
+ finally {
48
+ selfStoreRenderersInProgress.delete(component.id);
49
+ }
50
+ }
51
+ // What a typed self-store parent passes as the `store` argument when mounting
52
+ // `child`, or null when it can't supply one:
53
+ // - a ReactiveComponent child mounts a fresh typed instance of its own class
54
+ // (iff the child's own typed renderer generates — cycles land on the
55
+ // in-progress guard above and resolve to null);
56
+ // - a child whose generated boxed renderer never reads its `store` param gets
57
+ // `missing()` — all its reads resolve through `__gea_global_*()` accessors;
58
+ // - a child that DOES read the param (keyed-list renderers bind through it)
59
+ // gets the single global store its template subtree references — the same
60
+ // value the boxed entry threads down — when that store is unambiguous.
61
+ export function typedChildMountStoreArg(child, components, storeFields, storeArrayFields, constants, storeMethods) {
62
+ if (child.reactiveState) {
63
+ return selfStoreMountedRenderer(child, components, storeFields, storeArrayFields, constants, storeMethods)
64
+ ? reactiveChildInstanceExpression(child)
65
+ : null;
66
+ }
67
+ const renderer = mountedRendererForComponent(child, components, storeFields, storeArrayFields, constants, storeMethods);
68
+ if (!renderer)
69
+ return null;
70
+ // Match the child's actual param flavor. A typed-carrier child ALWAYS
71
+ // takes its subtree's shared_ptr global (even when its body never reads
72
+ // the param — missing() can't bind a shared_ptr). A boxed child that
73
+ // never reads its param gets missing(); one fed a TYPED global
74
+ // (recognized store but hub off) crosses through gea_cpp_key — the
75
+ // retained tracked proxy, not a snapshot.
76
+ const childSignatureTyped = renderer.some((line) => line.startsWith(`inline gea::embedded::ui::NodeHandle ${mountedRendererName(child)}(const std::shared_ptr<`));
77
+ if (!childSignatureTyped && !rendererReadsStoreParam(renderer))
78
+ return 'gea_cpp_value::missing()';
79
+ const globalName = childSubtreeGlobalStoreName(child, components, storeFields, storeArrayFields, constants, storeMethods);
80
+ if (!globalName)
81
+ return null;
82
+ const expr = `__gea_global_${sanitizeCppIdentifier(globalName)}()`;
83
+ if (childSignatureTyped)
84
+ return expr;
85
+ return storeGlobalIsTyped(globalName, storeFields) ? `gea_cpp_key(${expr})` : expr;
86
+ }
87
+ // What a template parent passes as a child's mount store argument. A child
88
+ // whose mount takes the typed shared_ptr gets its subtree's typed global
89
+ // accessor directly. A boxed child under a TYPED-param parent crosses through
90
+ // gea_cpp_key (retained tracked proxy); under a boxed parent it keeps the
91
+ // legacy `store` forward. Reactive children mount a fresh typed instance.
92
+ function boxedChildMountStoreArg(child, components, storeFields, storeArrayFields, constants, storeMethods, parentParamTyped) {
93
+ if (child.reactiveState)
94
+ return reactiveChildInstanceExpression(child);
95
+ const renderer = mountedRendererForComponent(child, components, storeFields, storeArrayFields, constants, storeMethods);
96
+ if (!renderer)
97
+ return null;
98
+ const signatureTyped = renderer.some((line) => line.startsWith(`inline gea::embedded::ui::NodeHandle ${mountedRendererName(child)}(const std::shared_ptr<`));
99
+ if (!signatureTyped)
100
+ return parentParamTyped ? 'gea_cpp_key(store)' : 'store';
101
+ const globalName = childSubtreeGlobalStoreName(child, components, storeFields, storeArrayFields, constants, storeMethods);
102
+ if (globalName)
103
+ return `__gea_global_${sanitizeCppIdentifier(globalName)}()`;
104
+ // The child takes a typed store but its subtree global is unresolvable from
105
+ // here — when the parent's own param is the same typed carrier, forward it.
106
+ return parentParamTyped ? 'store' : null;
107
+ }
108
+ // The one bundled global store instance `child`'s template (and its mounted
109
+ // subtree) references, or null when there is none, more than one, or an
110
+ // outer-`this` receiver — the cases a typed parent cannot thread a store for.
111
+ export function childSubtreeGlobalStoreName(child, components, storeFields, storeArrayFields, constants, storeMethods = []) {
112
+ const refs = componentStoreReferences(child, components, storeFields, storeArrayFields, constants, storeMethods);
113
+ if (!refs)
114
+ return null;
115
+ const names = new Set(refs.map((ref) => sanitizeCppIdentifier(ref.storeExpression)));
116
+ if (names.size !== 1)
117
+ return null;
118
+ const name = [...names][0];
119
+ if (name === 'this')
120
+ return null;
121
+ // Must be a real bundled store instance — receivers the reference analysis
122
+ // can't tie to a store global (locals, unresolved identifiers) don't qualify.
123
+ return storeFields.some((field) => field.storeGlobalName === name && !field.storeIsSelfStore) ? name : null;
124
+ }
125
+ // Whether a generated boxed renderer reads its `store` parameter anywhere in
126
+ // its body (field reads, bindReactiveApply roots, lambda captures, forwarding
127
+ // to grandchild mounts). Strip the parameter declarations (`&store`) first so
128
+ // only actual uses remain.
129
+ export function rendererReadsStoreParam(lines) {
130
+ return /\bstore\b/.test(lines.join('\n').replaceAll('&store', ''));
131
+ }
132
+ // The class name when `plan`'s store travels as the TYPED carrier
133
+ // (`std::shared_ptr<Class>` end to end — typed global cell, typed mount
134
+ // param, typed Context): compiled-base, non-self stores with the typed
135
+ // SignalHub active. Everything else stays on the boxed gea_cpp_value channel.
136
+ export function typedStoreCarrier(plan) {
137
+ return storeHubEmissionEnabled() && plan.storeRuntimeBase === 'compiled' && !plan.storeIsSelfStore ? plan.storeClass : null;
138
+ }
139
+ // Derive the forward declaration from the generated definition's signature
140
+ // line so the param flavor (typed shared_ptr store vs boxed gea_cpp_value)
141
+ // can never skew between declaration and definition.
142
+ export function mountedRendererDeclarationFromLines(renderer) {
143
+ const signature = renderer.find((line) => line.startsWith('inline gea::embedded::ui::NodeHandle mount_'));
144
+ if (!signature)
145
+ return null;
146
+ return signature.replace(/^inline\s+/, '').replace(/\s*\{\s*$/, ';');
147
+ }
148
+ export function generateMountedRendererDeclarations(components, storeFields, storeArrayFields, constants = new Map(), storeMethods = []) {
149
+ return components
150
+ .map((component) => mountedRendererForComponent(component, components, storeFields, storeArrayFields, constants, storeMethods))
151
+ .filter((renderer) => renderer !== null)
152
+ .map((renderer) => mountedRendererDeclarationFromLines(renderer))
153
+ .filter((declaration) => declaration !== null);
154
+ }
155
+ export function generateMountedRenderers(components, storeFields, storeArrayFields, constants = new Map(), storeMethods = []) {
156
+ const renderers = generateMountedRendererSections(components, storeFields, storeArrayFields, constants, storeMethods).map((section) => section.lines);
157
+ return renderers.flat();
158
+ }
159
+ export function generateMountedRendererSections(components, storeFields, storeArrayFields, constants = new Map(), storeMethods = []) {
160
+ return components
161
+ .map((component) => {
162
+ const renderer = mountedRendererForComponent(component, components, storeFields, storeArrayFields, constants, storeMethods);
163
+ if (!renderer)
164
+ return null;
165
+ return {
166
+ componentId: component.id,
167
+ exportName: component.exportName,
168
+ functionName: mountedRendererName(component),
169
+ lines: withComponentLocalConstAccessors(component, renderer)
170
+ };
171
+ })
172
+ .filter((section) => section !== null);
173
+ }
174
+ function withComponentLocalConstAccessors(component, renderer) {
175
+ const locals = componentLocalConsts(component);
176
+ if (locals.length === 0)
177
+ return renderer;
178
+ const localByName = new Map(locals.map((local) => [local.name, local]));
179
+ const rendererText = renderer.join('\n');
180
+ const needed = componentLocalConstClosure([...identifiersInText(rendererText)].filter((name) => localByName.has(name)), localByName);
181
+ if (needed.size === 0)
182
+ return renderer;
183
+ const accessorByName = new Map();
184
+ for (const name of needed) {
185
+ accessorByName.set(name, `__gea_local_${sanitizeCppIdentifier(component.exportName)}_${sanitizeCppIdentifier(name)}`);
186
+ }
187
+ const accessors = [];
188
+ for (const local of locals) {
189
+ if (!needed.has(local.name))
190
+ continue;
191
+ const expr = lowerComponentLocalConstExpression(local.initializer, accessorByName);
192
+ if (!expr)
193
+ continue;
194
+ accessors.push(`inline auto ${accessorByName.get(local.name)}() { return ${expr}; }`);
195
+ }
196
+ if (accessors.length === 0)
197
+ return renderer;
198
+ const emitted = new Set([...accessorByName.entries()].filter(([name]) => needed.has(name)).map(([, accessor]) => accessor));
199
+ const rewritten = renderer.map((line) => {
200
+ let next = line;
201
+ for (const [name, accessor] of accessorByName) {
202
+ if (!emitted.has(accessor))
203
+ continue;
204
+ next = replaceIdentifierToken(next, name, `${accessor}()`);
205
+ }
206
+ return next;
207
+ });
208
+ return [...accessors, '', ...rewritten];
209
+ }
210
+ function componentLocalConsts(component) {
211
+ const fileName = component.id.split('#')[0];
212
+ if (!fileName || !existsSync(fileName))
213
+ return [];
214
+ const text = readFileSync(fileName, 'utf8');
215
+ const sourceFile = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
216
+ const locals = [];
217
+ for (const statement of sourceFile.statements) {
218
+ if (!ts.isVariableStatement(statement))
219
+ continue;
220
+ if (!(statement.declarationList.flags & ts.NodeFlags.Const))
221
+ continue;
222
+ for (const declaration of statement.declarationList.declarations) {
223
+ if (!ts.isIdentifier(declaration.name) || !declaration.initializer)
224
+ continue;
225
+ locals.push({ name: declaration.name.text, initializer: declaration.initializer });
226
+ }
227
+ }
228
+ return locals;
229
+ }
230
+ function componentLocalConstClosure(seed, localByName) {
231
+ const needed = new Set();
232
+ const visit = (name) => {
233
+ if (needed.has(name))
234
+ return;
235
+ const local = localByName.get(name);
236
+ if (!local)
237
+ return;
238
+ needed.add(name);
239
+ for (const dependency of identifiersInExpression(local.initializer)) {
240
+ if (localByName.has(dependency))
241
+ visit(dependency);
242
+ }
243
+ };
244
+ for (const name of seed)
245
+ visit(name);
246
+ return needed;
247
+ }
248
+ function lowerComponentLocalConstExpression(node, accessorByName) {
249
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isNonNullExpression(node)) {
250
+ return lowerComponentLocalConstExpression(node.expression, accessorByName);
251
+ }
252
+ if (ts.isNumericLiteral(node))
253
+ return node.getText();
254
+ if (ts.isStringLiteralLike(node))
255
+ return `std::string(${cppString(node.text)})`;
256
+ if (node.kind === ts.SyntaxKind.TrueKeyword)
257
+ return 'true';
258
+ if (node.kind === ts.SyntaxKind.FalseKeyword)
259
+ return 'false';
260
+ if (ts.isIdentifier(node))
261
+ return accessorByName.has(node.text) ? `${accessorByName.get(node.text)}()` : sanitizeCppIdentifier(node.text);
262
+ if (ts.isPrefixUnaryExpression(node)) {
263
+ const operand = lowerComponentLocalConstExpression(node.operand, accessorByName);
264
+ if (!operand)
265
+ return null;
266
+ if (node.operator === ts.SyntaxKind.MinusToken)
267
+ return `(-${operand})`;
268
+ if (node.operator === ts.SyntaxKind.PlusToken)
269
+ return `(+${operand})`;
270
+ if (node.operator === ts.SyntaxKind.ExclamationToken)
271
+ return `(!${operand})`;
272
+ return null;
273
+ }
274
+ if (ts.isConditionalExpression(node)) {
275
+ const condition = lowerComponentLocalConstExpression(node.condition, accessorByName);
276
+ const whenTrue = lowerComponentLocalConstExpression(node.whenTrue, accessorByName);
277
+ const whenFalse = lowerComponentLocalConstExpression(node.whenFalse, accessorByName);
278
+ if (!condition || !whenTrue || !whenFalse)
279
+ return null;
280
+ return `(gea::runtime::coerce::to_boolean(${condition}) ? ${whenTrue} : ${whenFalse})`;
281
+ }
282
+ if (ts.isBinaryExpression(node)) {
283
+ const left = lowerComponentLocalConstExpression(node.left, accessorByName);
284
+ const right = lowerComponentLocalConstExpression(node.right, accessorByName);
285
+ const op = cppLocalConstBinaryOperator(node.operatorToken.kind);
286
+ if (!left || !right || !op)
287
+ return null;
288
+ return `(${left} ${op} ${right})`;
289
+ }
290
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)) {
291
+ const receiver = node.expression.expression.text;
292
+ const method = node.expression.name.text;
293
+ const args = node.arguments.map((arg) => lowerComponentLocalConstExpression(arg, accessorByName));
294
+ if (args.some((arg) => !arg))
295
+ return null;
296
+ if (receiver === 'Math' && method === 'floor' && args.length === 1)
297
+ return `std::floor(${args[0]})`;
298
+ if (receiver === 'Math' && method === 'ceil' && args.length === 1)
299
+ return `std::ceil(${args[0]})`;
300
+ if (receiver === 'Math' && method === 'round' && args.length === 1)
301
+ return `std::round(${args[0]})`;
302
+ if (receiver === 'Math' && method === 'abs' && args.length === 1)
303
+ return `std::abs(${args[0]})`;
304
+ if (receiver === 'Math' && method === 'max' && args.length > 0)
305
+ return `gea::runtime::math::max({${args.join(', ')}})`;
306
+ if (receiver === 'Math' && method === 'min' && args.length > 0)
307
+ return `gea::runtime::math::min({${args.join(', ')}})`;
308
+ }
309
+ return null;
310
+ }
311
+ function cppLocalConstBinaryOperator(kind) {
312
+ if (kind === ts.SyntaxKind.PlusToken)
313
+ return '+';
314
+ if (kind === ts.SyntaxKind.MinusToken)
315
+ return '-';
316
+ if (kind === ts.SyntaxKind.AsteriskToken)
317
+ return '*';
318
+ if (kind === ts.SyntaxKind.SlashToken)
319
+ return '/';
320
+ if (kind === ts.SyntaxKind.PercentToken)
321
+ return '%';
322
+ if (kind === ts.SyntaxKind.LessThanToken)
323
+ return '<';
324
+ if (kind === ts.SyntaxKind.LessThanEqualsToken)
325
+ return '<=';
326
+ if (kind === ts.SyntaxKind.GreaterThanToken)
327
+ return '>';
328
+ if (kind === ts.SyntaxKind.GreaterThanEqualsToken)
329
+ return '>=';
330
+ if (kind === ts.SyntaxKind.EqualsEqualsToken || kind === ts.SyntaxKind.EqualsEqualsEqualsToken)
331
+ return '==';
332
+ if (kind === ts.SyntaxKind.ExclamationEqualsToken || kind === ts.SyntaxKind.ExclamationEqualsEqualsToken)
333
+ return '!=';
334
+ if (kind === ts.SyntaxKind.AmpersandAmpersandToken)
335
+ return '&&';
336
+ if (kind === ts.SyntaxKind.BarBarToken)
337
+ return '||';
338
+ return null;
339
+ }
340
+ function identifiersInExpression(node) {
341
+ const identifiers = new Set();
342
+ const visit = (next) => {
343
+ if (ts.isIdentifier(next))
344
+ identifiers.add(next.text);
345
+ ts.forEachChild(next, visit);
346
+ };
347
+ visit(node);
348
+ return identifiers;
349
+ }
350
+ function identifiersInText(text) {
351
+ const identifiers = new Set();
352
+ const pattern = /\b[A-Za-z_$][A-Za-z0-9_$]*\b/g;
353
+ let match;
354
+ while ((match = pattern.exec(text)))
355
+ identifiers.add(match[0]);
356
+ return identifiers;
357
+ }
358
+ function replaceIdentifierToken(text, name, replacement) {
359
+ return text.replace(new RegExp(`\\b${escapeRegExp(name)}\\b`, 'g'), replacement);
360
+ }
361
+ export function mountedRendererName(component) {
362
+ return `mount_${sanitizeCppIdentifier(component.exportName)}`;
363
+ }
364
+ function canUseDedicatedKeyedListRenderer(component, constants) {
365
+ const keyed = component.template.slots.filter((slot) => slot.kind === 'keyed-list');
366
+ if (keyed.length === 0)
367
+ return false;
368
+ return component.template.slots.every((slot) => slot.kind === 'keyed-list' || isRootSetupSlot(slot, constants));
369
+ }
370
+ export function mountedRendererForComponent(component, components, storeFields, storeArrayFields, constants, storeMethods) {
371
+ // Self-store ReactiveComponent: typed template renderer only (no boxed paths).
372
+ if (component.reactiveState) {
373
+ return selfStoreMountedRenderer(component, components, storeFields, storeArrayFields, constants, storeMethods);
374
+ }
375
+ const dedicatedKeyed = canUseDedicatedKeyedListRenderer(component, constants);
376
+ const multiKeyed = dedicatedKeyed ? multiKeyedListMountedRenderer(component, storeArrayFields, constants) : null;
377
+ if (multiKeyed)
378
+ return multiKeyed;
379
+ const keyed = dedicatedKeyed ? keyedListMountedRenderer(component, components, storeFields, storeArrayFields, constants, storeMethods) : null;
380
+ if (keyed)
381
+ return keyed;
382
+ // A template component whose whole subtree reads ONE typed-carrier global
383
+ // store takes the typed shared_ptr param itself — the boxed gea_cpp_value
384
+ // channel disappears from the entire mount chain. Multi-store or
385
+ // non-typed-store components keep the boxed param.
386
+ const ownGlobal = childSubtreeGlobalStoreName(component, components, storeFields, storeArrayFields, constants, storeMethods);
387
+ const hasKeyedListSlot = component.template.slots.some((slot) => slot.kind === 'keyed-list');
388
+ const ownTypedClass = (ownGlobal &&
389
+ !hasKeyedListSlot &&
390
+ storeFields.find((field) => field.storeGlobalName === ownGlobal && field.storeRuntimeBase === 'compiled' && !field.storeIsSelfStore)?.storeClass) ||
391
+ null;
392
+ const canNativeChildMount = (child) => child !== component && mountedRendererForComponent(child, components, storeFields, storeArrayFields, constants, storeMethods) !== null;
393
+ const template = templateMountedRenderer(component, components, storeFields, constants, canNativeChildMount, storeMethods, new BoxedStoreFieldAccess((child) => boxedChildMountStoreArg(child, components, storeFields, storeArrayFields, constants, storeMethods, !!ownTypedClass), storeHubEmissionEnabled() ? ownTypedClass : null), storeArrayFields);
394
+ if (template)
395
+ return template;
396
+ const root = parseHtmlRoot(component.template.html);
397
+ if (!root)
398
+ return null;
399
+ const lowered = lowerSlots(component.template.slots, storeFields, constants);
400
+ const setup = rootSetupLines('root', component.template.slots, storeFields, storeMethods, undefined, root.tag, constants, 'disposer');
401
+ if (!setup)
402
+ return null;
403
+ if (!lowered) {
404
+ if (component.template.slots.some((slot) => !isRootSetupSlot(slot, constants)))
405
+ return null;
406
+ return staticMountedRenderer(component, root, setup);
407
+ }
408
+ if (!canUseStyleTextMountedSlots(component.template.slots))
409
+ return null;
410
+ if (!canUseMountedFieldReaders(lowered))
411
+ return null;
412
+ return styleTextMountedRenderer(component, root, lowered, setup);
413
+ }
414
+ function staticMountedRenderer(component, root, setup = []) {
415
+ const createRoot = uiCreateNodeExpression(root);
416
+ if (!createRoot)
417
+ return null;
418
+ return [
419
+ `inline gea::embedded::ui::NodeHandle ${mountedRendererName(component)}(const gea_cpp_value &store, const std::shared_ptr<NativeDisposer> &disposer) {`,
420
+ ` auto root = ${createRoot};`,
421
+ ...attributeLines('root', root, component.template.slots),
422
+ ...setup,
423
+ ' return root;',
424
+ '}',
425
+ '',
426
+ ];
427
+ }
428
+ function styleTextMountedRenderer(component, root, lowered, setup) {
429
+ const createRoot = uiCreateNodeExpression(root);
430
+ if (!createRoot)
431
+ return null;
432
+ const deps = [...new Set(lowered.deps)];
433
+ const depsList = deps.map((dep) => cppString(dep)).join(', ');
434
+ const applyLambda = [
435
+ `[root, store]() mutable -> void {`,
436
+ ...lowered.fields.map((field) => ` const auto ${storeFieldLocalName(field.fieldName)} = ${mountedFieldReaderName(field)}(store);`),
437
+ ...lowered.lines.map((line) => ` ${line}`),
438
+ ' }',
439
+ ];
440
+ // Compiled-base single-store deps take the FULLY TYPED carrier: the store
441
+ // param is the `std::shared_ptr<Class>` itself (matching the typed global
442
+ // cell callers pass) and the bind registers straight into the SignalHub —
443
+ // no downcast, no boxed fallback. Anything else keeps the boxed param and
444
+ // dynamic registration.
445
+ const hubClasses = new Set(lowered.fields.map((field) => field.storeClass));
446
+ const typedCarrier = storeHubEmissionEnabled() &&
447
+ hubClasses.size === 1 &&
448
+ lowered.fields.every((field) => field.storeRuntimeBase === 'compiled' && !field.storeIsSelfStore)
449
+ ? [...hubClasses][0]
450
+ : null;
451
+ const storeParam = typedCarrier ? `const std::shared_ptr<${typedCarrier}> &store` : 'const gea_cpp_value &store';
452
+ const bindLines = typedCarrier
453
+ ? [
454
+ ` gea_rc_bind_hub_apply(store, disposer, {${depsList}}, std::function<void()>(${applyLambda[0]}`,
455
+ ...applyLambda.slice(1, -1),
456
+ ` ${applyLambda[applyLambda.length - 1]}));`,
457
+ ]
458
+ : [` bindReactiveApply(store, disposer, {${depsList}}, ${applyLambda[0]}`, ...applyLambda.slice(1, -1), ` ${applyLambda[applyLambda.length - 1]});`];
459
+ return [
460
+ `inline gea::embedded::ui::NodeHandle ${mountedRendererName(component)}(${storeParam}, const std::shared_ptr<NativeDisposer> &disposer) {`,
461
+ ` auto root = ${createRoot};`,
462
+ ...attributeLines('root', root, component.template.slots),
463
+ ...setup,
464
+ ...lowered.staticLines.map((line) => ` ${line}`),
465
+ ...bindLines,
466
+ ' return root;',
467
+ '}',
468
+ '',
469
+ ];
470
+ }
471
+ function multiKeyedListMountedRenderer(component, storeArrayFields, constants) {
472
+ const slots = component.template.slots.filter((slot) => slot.kind === 'keyed-list');
473
+ if (slots.length <= 1)
474
+ return null;
475
+ const root = parseHtmlRoot(component.template.html);
476
+ const setup = root ? rootSetupLines('root', component.template.slots, [], [], undefined, root.tag, constants, 'disposer') : null;
477
+ const createRoot = root ? uiCreateNodeExpression(root) : null;
478
+ if (!root || !setup || !createRoot)
479
+ return null;
480
+ const plans = slots.map((slot, slotIndex) => {
481
+ const fieldName = fieldNameForSlot(slot);
482
+ const field = fieldName ? unique(storeArrayFields.filter((candidate) => candidate.fieldName === fieldName)) : null;
483
+ const payload = keyedListPayload(slot);
484
+ const rowSlot = payload?.rowTemplate ? intrinsicImageRowSlot(payload.rowTemplate.html, payload.rowTemplate.slots) : null;
485
+ const source = rowSlot ? mountSlotImageSourceLines('row', rowSlot) : null;
486
+ const styleSlot = rowSlot ? mountSlotStyleSlot(rowSlot) : null;
487
+ const itemName = payload?.itemParam ? sanitizeCppIdentifier(payload.itemParam) : 'item';
488
+ const rowSlots = field && styleSlot ? lowerRowSlots([styleSlot], itemName, field, constants) : null;
489
+ return field && payload?.rowTemplate && rowSlot && source && rowSlots && rowSlots.lines.length > 0
490
+ ? { slotIndex, field, itemName, source, rowSlots }
491
+ : null;
492
+ });
493
+ if (plans.some((plan) => plan === null))
494
+ return null;
495
+ const concretePlans = plans;
496
+ const storeClass = uniqueEqual(concretePlans.map((plan) => plan.field.storeClass));
497
+ if (!storeClass)
498
+ return null;
499
+ const typedCarrier = typedStoreCarrier(concretePlans[0].field);
500
+ const helperNs = `gea_mkl_${sanitizeCppIdentifier(component.exportName)}`;
501
+ const helperLines = [
502
+ `namespace ${helperNs} {`,
503
+ `struct Context {`,
504
+ ` gea::embedded::ui::NodeHandle root;`,
505
+ ` std::shared_ptr<${storeClass}> typed_store;`,
506
+ ...(typedCarrier ? [] : [` gea_cpp_value store;`]),
507
+ ` std::vector<gea::embedded::ui::NodeHandle> rows;`,
508
+ `};`,
509
+ ];
510
+ for (const plan of concretePlans) {
511
+ const fn = `make_row_${plan.slotIndex}`;
512
+ helperLines.push(`inline gea::embedded::ui::NodeHandle ${fn}(const ${plan.field.itemTypeRef} &${plan.itemName}) {`, ` auto row = gea::embedded::ui::Document::instance().createImage();`, ...attributeLines('row', { tag: 'img' }).map((line) => ` ${line}`), ...plan.source.map((line) => ` ${line}`), ...plan.rowSlots.lines.map((line) => ` ${line}`), ` return row;`, `}`);
513
+ }
514
+ helperLines.push(`inline void append_row(Context &ctx, gea::embedded::ui::NodeHandle row) {`, ` ctx.root.appendChild(row);`, ` ctx.rows.push_back(row);`, `}`, `inline void clear_rows(Context &ctx) {`, ` for (const auto &row : ctx.rows) row.remove();`, ` ctx.rows.clear();`, `}`, `inline void apply(Context &ctx) {`, ` clear_rows(ctx);`);
515
+ if (typedCarrier) {
516
+ for (const plan of concretePlans) {
517
+ helperLines.push(` for (const auto &${plan.itemName} : ctx.typed_store->${plan.field.fieldName}) append_row(ctx, make_row_${plan.slotIndex}(${plan.itemName}));`);
518
+ }
519
+ }
520
+ else {
521
+ helperLines.push(` if (ctx.typed_store) {`);
522
+ for (const plan of concretePlans) {
523
+ helperLines.push(` for (const auto &${plan.itemName} : ctx.typed_store->${plan.field.fieldName}) append_row(ctx, make_row_${plan.slotIndex}(${plan.itemName}));`);
524
+ }
525
+ helperLines.push(` return;`, ` }`);
526
+ for (const plan of concretePlans) {
527
+ helperLines.push(` {`, ` auto &__gea_store_unwrapped = (ctx.store.kind == gea_cpp_value::kind_t::proxy && ctx.store.proxy_target) ? *ctx.store.proxy_target : ctx.store;`, ` auto __gea_array_value = __gea_store_unwrapped.record_get_literal(${cppString(plan.field.fieldName)});`, ` const auto &__gea_values = (__gea_array_value.kind == gea_cpp_value::kind_t::proxy && __gea_array_value.proxy_target) ? __gea_array_value.proxy_target->array_ref() : __gea_array_value.array_ref();`, ` for (const auto &__gea_item_value : __gea_values) {`, ` const auto ${plan.itemName} = read_${plan.field.itemType}(__gea_item_value);`, ` append_row(ctx, make_row_${plan.slotIndex}(${plan.itemName}));`, ` }`, ` }`);
528
+ }
529
+ }
530
+ helperLines.push(`}`, `} // namespace ${helperNs}`, ``);
531
+ const deps = concretePlans.map((plan) => plan.field.fieldName);
532
+ return [
533
+ ...helperLines,
534
+ `inline gea::embedded::ui::NodeHandle ${mountedRendererName(component)}(${typedCarrier ? `const std::shared_ptr<${storeClass}> &store` : 'const gea_cpp_value &store'}, const std::shared_ptr<NativeDisposer> &disposer) {`,
535
+ ` auto root = ${createRoot};`,
536
+ ...attributeLines('root', root, component.template.slots),
537
+ ...setup,
538
+ ...(typedCarrier
539
+ ? [` auto __gea_ctx = std::make_shared<${helperNs}::Context>(${helperNs}::Context{root, store, {}});`]
540
+ : [
541
+ ` auto __gea_typed_store = gea_cpp_value_as_shared_ptr<${storeClass}>(store);`,
542
+ ` auto __gea_ctx = std::make_shared<${helperNs}::Context>(${helperNs}::Context{root, std::move(__gea_typed_store), store, {}});`,
543
+ ]),
544
+ ...hubAwareCtxBindLines(concretePlans[0].field, deps.map((dep) => cppString(dep)).join(', '), `[__gea_ctx]() mutable -> void { ${helperNs}::apply(*__gea_ctx); }`),
545
+ ` return root;`,
546
+ `}`,
547
+ ``,
548
+ ];
549
+ }
550
+ // Emit the reactive registration for a keyed-list context. A typed-carrier
551
+ // store (compiled base, not a self-store, hub active) holds the
552
+ // `std::shared_ptr` in the context and registers straight into the typed
553
+ // SignalHub — no runtime fallback; the store param itself is the typed
554
+ // pointer. Everything else keeps the dynamic observe channel.
555
+ function hubAwareCtxBindLines(plan, depsList, applyLambda) {
556
+ if (!typedStoreCarrier(plan))
557
+ return [` bindReactiveApply(store, disposer, {${depsList}}, ${applyLambda});`];
558
+ return [` gea_rc_bind_hub_apply(__gea_ctx->typed_store, disposer, {${depsList}}, std::function<void()>(${applyLambda}));`];
559
+ }
560
+ function keyedListEffectiveRowTemplate(rowTemplate, components, itemName) {
561
+ if (parseHtmlRoot(rowTemplate.html))
562
+ return rowTemplate;
563
+ if (intrinsicImageRowSlot(rowTemplate.html, rowTemplate.slots))
564
+ return rowTemplate;
565
+ const mountSlots = rowTemplate.slots.filter((slot) => slot.kind === 'mount');
566
+ if (mountSlots.length !== 1)
567
+ return null;
568
+ const childTag = mountSlotTag(mountSlots[0]);
569
+ if (!childTag)
570
+ return null;
571
+ const child = components.find((component) => component.exportName === childTag);
572
+ if (!child || !parseHtmlRoot(child.template.html))
573
+ return null;
574
+ const bindings = rowComponentPropBindings(mountSlots[0], itemName);
575
+ if (!bindings)
576
+ return null;
577
+ return {
578
+ html: child.template.html,
579
+ slots: child.template.slots.map((slot) => rewriteRowComponentSlot(slot, bindings)),
580
+ };
581
+ }
582
+ function rowComponentPropBindings(slot, itemName) {
583
+ const attrs = mountSlotAttrs(slot);
584
+ if (attrs.length === 0)
585
+ return null;
586
+ const bindings = new Map();
587
+ let bindsItem = false;
588
+ for (const attr of attrs) {
589
+ const parsed = parseMountAttr(attr);
590
+ if (!parsed)
591
+ return null;
592
+ // `key` belongs to the list reconciler, not to the child component.
593
+ if (parsed.name === 'key')
594
+ continue;
595
+ bindings.set(parsed.name, parsed.expr);
596
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(parsed.expr) && sanitizeCppIdentifier(parsed.expr) === itemName) {
597
+ bindsItem = true;
598
+ }
599
+ }
600
+ return bindsItem ? bindings : null;
601
+ }
602
+ function rewriteRowComponentSlot(slot, bindings) {
603
+ return {
604
+ ...slot,
605
+ ...(slot.expr ? { expr: rewriteRowComponentExpression(slot.expr, bindings) } : {}),
606
+ ...(slot.exprObjectFields
607
+ ? {
608
+ exprObjectFields: slot.exprObjectFields.map((field) => ({
609
+ ...field,
610
+ expr: rewriteRowComponentExpression(field.expr, bindings),
611
+ })),
612
+ }
613
+ : {}),
614
+ };
615
+ }
616
+ function rewriteRowComponentExpression(expr, bindings) {
617
+ let rewritten = expr;
618
+ // Longest names first keeps `props.bookTitle` independent from `props.book`.
619
+ const entries = [...bindings.entries()].sort(([a], [b]) => b.length - a.length);
620
+ for (const [propName, value] of entries) {
621
+ const prop = escapeRegExp(propName);
622
+ const replacement = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value) ? value : `(${value})`;
623
+ rewritten = rewritten
624
+ .replace(new RegExp(`\\bthis\\.props\\.${prop}\\b`, 'g'), replacement)
625
+ .replace(new RegExp(`\\bprops\\.${prop}\\b`, 'g'), replacement);
626
+ }
627
+ return rewritten;
628
+ }
629
+ function keyedListMountedRenderer(component, components, storeFields, storeArrayFields, constants, storeMethods) {
630
+ const slots = component.template.slots.filter((slot) => slot.kind === 'keyed-list');
631
+ if (slots.length !== 1)
632
+ return null;
633
+ const slot = slots[0];
634
+ const fieldName = fieldNameForSlot(slot);
635
+ const field = fieldName ? unique(storeArrayFields.filter((candidate) => candidate.fieldName === fieldName)) : null;
636
+ const payload = keyedListPayload(slot);
637
+ if (!payload)
638
+ return null;
639
+ const itemName = payload.itemParam ? sanitizeCppIdentifier(payload.itemParam) : 'item';
640
+ const rowTemplate = payload.rowTemplate ? keyedListEffectiveRowTemplate(payload.rowTemplate, components, itemName) : null;
641
+ const root = parseHtmlRoot(component.template.html);
642
+ const intrinsicRowSlot = rowTemplate ? intrinsicImageRowSlot(rowTemplate.html, rowTemplate.slots) : null;
643
+ const row = rowTemplate ? (parseHtmlRoot(rowTemplate.html) ?? (intrinsicRowSlot ? { tag: 'img' } : null)) : null;
644
+ if (!field || !rowTemplate || !root || !row)
645
+ return null;
646
+ const rowRootVar = '__gea_row_root';
647
+ // Thread the store plans: without them a root-level event handler on a
648
+ // keyed-list component (`onTouchMove={() => scrollProbe.track()}`) loses
649
+ // the typed direct-call lowering and re-boxes the whole store through the
650
+ // retained proxy + record_get_literal dispatch ON EVERY EVENT.
651
+ const setup = rootSetupLines('root', component.template.slots, storeFields, storeMethods, undefined, root.tag, constants, 'disposer');
652
+ // The row's text / class / event / style slots are all handled by
653
+ // lowerRowSlots (which threads item references + walk-path targeting). Only
654
+ // pass the remaining attr slots through rootSetupLines so it doesn't choke
655
+ // on item-referencing event handlers like `() => store.select(item.id)`.
656
+ const rowSetupSlots = rowTemplate.slots.filter((s) => s.kind !== 'event' &&
657
+ s.kind !== 'class' &&
658
+ s.kind !== 'text' &&
659
+ s.kind !== 'style' &&
660
+ // JSX `key` is reconciler metadata, not a DOM attribute. Passing an
661
+ // item-derived key through rootSetupLines rejects the native renderer.
662
+ !(s.kind === 'attr' && slotAttrName(s) === 'key') &&
663
+ // A dynamic `<img src={item.field}>` is handled by lowerRowSlots via the
664
+ // runtime asset lookup; routing it through rootSetupLines (literal/global
665
+ // only) would reject the whole keyed list.
666
+ !(s.kind === 'attr' && slotAttrName(s) === 'src' && !!s.expr && stringLiteralValue(s.expr) === null));
667
+ const rowSetup = intrinsicRowSlot ? mountSlotImageSourceLines(rowRootVar, intrinsicRowSlot) : rootSetupLines(rowRootVar, rowSetupSlots, [], [], undefined, undefined, constants);
668
+ if (!setup || !rowSetup)
669
+ return null;
670
+ const rowStyleSlot = intrinsicRowSlot ? mountSlotStyleSlot(intrinsicRowSlot) : null;
671
+ // Build the row's nested element tree. Without this, `make_row` only
672
+ // creates the row's root element and every child binding falls through to
673
+ // 0×0 placeholders (visible as static "0" text on screen). The tree
674
+ // walker maps each child element to a named local (`__gea_row_0`, etc.) so
675
+ // the slot lowering below can target reactive bindings to the correct
676
+ // nested element via the slot's IR walk path.
677
+ const rowTreeParsed = intrinsicRowSlot ? null : parseTemplateRoot(rowTemplate.html);
678
+ let rowVarCounter = 0;
679
+ const nextRowVar = () => `__gea_row_${rowVarCounter++}`;
680
+ let rowChildTree = {
681
+ ok: true,
682
+ treeLines: [],
683
+ pathVars: new Map([['', rowRootVar]]),
684
+ elementPaths: new Map(),
685
+ };
686
+ if (rowTreeParsed) {
687
+ rowChildTree = emitRowChildTree(rowTreeParsed, rowRootVar, nextRowVar);
688
+ if (!rowChildTree.ok)
689
+ return null;
690
+ }
691
+ const rowSlots = lowerRowSlots(rowStyleSlot ? [rowStyleSlot] : rowTemplate.slots, itemName, field, constants, rowChildTree.pathVars, storeFields, storeMethods);
692
+ if (rowSlots.lines.length === 0 && rowChildTree.treeLines.length === 0)
693
+ return null;
694
+ const keyExpr = keyedListKeyExpression(payload, itemName, field);
695
+ const keyExprNeedsItem = keyExpr !== 'std::to_string(__gea_index)';
696
+ const createRoot = uiCreateNodeExpression(root);
697
+ const createRow = uiCreateNodeExpression(row);
698
+ if (!createRoot || !createRow)
699
+ return null;
700
+ // Compile-time keyed-list binding: hoist the whole diff body and the
701
+ // three stateless helpers (same_rendered_item, patch_row, make_row)
702
+ // out of the mount function into per-component free functions in a
703
+ // `gea_kl_<Component>` namespace. The mount keeps just the per-instance
704
+ // context (root + rows) on the heap; the bindReactiveApply lambda's
705
+ // capture shrinks to a single shared_ptr, which fits in std::function's
706
+ // small-buffer optimization and skips the per-binding heap alloc that
707
+ // the previous closure-with-everything-captured form forced. Deps are
708
+ // emitted as a `static constexpr std::array<const char*, N>` so the
709
+ // dep list is .rodata, not a per-call temporary.
710
+ const helperNs = `gea_kl_${sanitizeCppIdentifier(component.exportName)}`;
711
+ // Type-use spelling of the row item: `::__gea_type_X` for interface reuse,
712
+ // bare `<Store>_<field>_item` for synthesized structs. The reader fn name
713
+ // keys off the UNQUALIFIED `field.itemType` (`read_<itemType>`) so it never
714
+ // becomes `read_::__gea_type_X`.
715
+ const itemType = field.itemTypeRef;
716
+ const itemReaderFn = `read_${field.itemType}`;
717
+ const typedCarrier = typedStoreCarrier(field);
718
+ const thresholdPatch = detectThresholdClassPatch(rowSlots, itemName, rowRootVar) ?? detectThresholdStylePatch(rowSlots, itemName, rowRootVar);
719
+ const thresholdStoreFields = new Set(thresholdPatch ? [thresholdPatch.storeField.fieldName] : []);
720
+ const fullApplyStoreFields = rowSlots.storeFields.filter((dep) => !thresholdStoreFields.has(dep.fieldName));
721
+ const shouldPatchOnStoreDeps = fullApplyStoreFields.length > 0;
722
+ const afterFullApplyLines = thresholdPatch ? ['rebuild_threshold_order(ctx);', 'sync_threshold_snapshot(ctx);'] : [];
723
+ const thresholdReaderCall = thresholdPatch?.storeField.readerName ? `${thresholdPatch.storeField.readerName}(store)` : null;
724
+ const rewriteThresholdReader = (line) => thresholdReaderCall ? line.replaceAll(thresholdReaderCall, '__gea_threshold') : line;
725
+ // The Context expression that carries the store into patch_row/make_row:
726
+ // typed carrier → the shared_ptr member; boxed → the gea_cpp_value member.
727
+ const ctxStoreExpr = typedCarrier ? 'ctx.typed_store' : 'ctx.store';
728
+ // Body for the typed fast path (or the gea_cpp_value fallback). The two
729
+ // share the same diff/patch logic; they differ only in how they iterate
730
+ // the item collection. Build the body lines once and reuse.
731
+ const diffBodyLines = (itemAccessor, itemReadLine, thresholdExpr = null) => {
732
+ const patchRowArgs = thresholdPatch && thresholdExpr
733
+ ? `entry.row, ${thresholdExpr}, entry.item, ${itemName}, false`
734
+ : `entry.row, ${ctxStoreExpr}, entry.item, ${itemName}, false`;
735
+ const makeRowArgs = thresholdPatch && thresholdExpr
736
+ ? `${thresholdExpr}, ctx.typed_store, ${itemName}`
737
+ : typedCarrier
738
+ ? `ctx.typed_store, ${itemName}`
739
+ : `ctx.store, ctx.typed_store, ${itemName}`;
740
+ const reusedPatchRowArgs = thresholdPatch && thresholdExpr
741
+ ? `row_node, ${thresholdExpr}, previous_item, ${itemName}, !reused_row`
742
+ : `row_node, ${ctxStoreExpr}, previous_item, ${itemName}, !reused_row`;
743
+ return [
744
+ `if (ctx.rows.size() == ${itemAccessor}.size()) {`,
745
+ ` bool keys_stable = true;`,
746
+ ` std::size_t __gea_index = 0;`,
747
+ ...(keyExprNeedsItem
748
+ ? [
749
+ ...(itemReadLine
750
+ ? [` for (const auto &__gea_item_value : ${itemAccessor}) {`, ` ${itemReadLine}`]
751
+ : [` for (const auto &${itemName} : ${itemAccessor}) {`]),
752
+ ` const std::string key = ${keyExpr};`,
753
+ ` if (ctx.rows[__gea_index].key != key) {`,
754
+ ` keys_stable = false;`,
755
+ ` break;`,
756
+ ` }`,
757
+ ` ++__gea_index;`,
758
+ ` }`,
759
+ ]
760
+ : []),
761
+ ` if (keys_stable) {`,
762
+ ` __gea_index = 0;`,
763
+ ...(itemReadLine
764
+ ? [` for (const auto &__gea_item_value : ${itemAccessor}) {`, ` ${itemReadLine}`]
765
+ : [` for (const auto &${itemName} : ${itemAccessor}) {`]),
766
+ ` auto &entry = ctx.rows[__gea_index];`,
767
+ ` if (${shouldPatchOnStoreDeps ? 'true' : `!same_rendered_item(entry.item, ${itemName})`}) patch_row(${patchRowArgs});`,
768
+ ` entry.item = ${itemName};`,
769
+ ` ++__gea_index;`,
770
+ ` }`,
771
+ ...afterFullApplyLines.map((line) => ` ${line}`),
772
+ ` return;`,
773
+ ` }`,
774
+ `}`,
775
+ `auto previous_rows = std::move(ctx.rows);`,
776
+ `ctx.rows.clear();`,
777
+ `ctx.rows.reserve(${itemAccessor}.size());`,
778
+ `std::size_t __gea_index = 0;`,
779
+ ...(itemReadLine
780
+ ? [`for (const auto &__gea_item_value : ${itemAccessor}) {`, ` ${itemReadLine}`]
781
+ : [`for (const auto &${itemName} : ${itemAccessor}) {`]),
782
+ ` const std::string key = ${keyExpr};`,
783
+ ` auto row_node = gea::embedded::ui::NodeHandle();`,
784
+ ` auto previous_item = ${itemType}{};`,
785
+ ` bool reused_row = false;`,
786
+ ` for (auto it = previous_rows.begin(); it != previous_rows.end(); ++it) {`,
787
+ ` if (it->key != key) continue;`,
788
+ ` row_node = it->row;`,
789
+ ` previous_item = it->item;`,
790
+ ` reused_row = true;`,
791
+ ` previous_rows.erase(it);`,
792
+ ` break;`,
793
+ ` }`,
794
+ ` if (!row_node) row_node = make_row(${makeRowArgs});`,
795
+ ` if (!reused_row || ${shouldPatchOnStoreDeps ? 'true' : `!same_rendered_item(previous_item, ${itemName})`}) patch_row(${reusedPatchRowArgs});`,
796
+ ` ctx.root.appendChild(row_node);`,
797
+ ` ctx.rows.push_back({key, row_node, ${itemName}});`,
798
+ ` ++__gea_index;`,
799
+ `}`,
800
+ `for (const auto &entry : previous_rows) entry.row.remove();`,
801
+ ...afterFullApplyLines,
802
+ ];
803
+ };
804
+ // patch_row only receives the row root handle, but the per-item patch
805
+ // lines target nested elements by their make_row local (`__gea_row_N`).
806
+ // Re-resolve each referenced nested handle from `row` by walking child
807
+ // indices (the tree shape is fixed across patches). Only emit resolution
808
+ // for vars that patch lines actually reference.
809
+ const patchedVars = new Set();
810
+ for (const patch of rowSlots.patches) {
811
+ for (const line of patch.lines) {
812
+ for (const match of line.matchAll(/\b(__gea_row_\d+)\b/g))
813
+ patchedVars.add(match[1]);
814
+ }
815
+ }
816
+ for (const line of rowSlots.unconditionalPatches) {
817
+ for (const match of line.matchAll(/\b(__gea_row_\d+)\b/g))
818
+ patchedVars.add(match[1]);
819
+ }
820
+ const patchResolveLines = [];
821
+ for (const varName of patchedVars) {
822
+ const path = rowChildTree.elementPaths.get(varName);
823
+ if (!path)
824
+ continue;
825
+ const initList = path.join(', ');
826
+ patchResolveLines.push(`auto ${varName} = ${helperNs}::resolve_child(${rowRootVar}, {${initList}});`);
827
+ }
828
+ const helperLines = [
829
+ `namespace ${helperNs} {`,
830
+ `inline gea::embedded::ui::NodeHandle resolve_child(gea::embedded::ui::NodeHandle parent, std::initializer_list<int> path) {`,
831
+ ` auto &tree = gea::embedded::ui::Tree::instance();`,
832
+ ` int id = parent.id();`,
833
+ ` for (int idx : path) {`,
834
+ ` if (id < 0 || id >= tree.nodeCount()) return gea::embedded::ui::NodeHandle();`,
835
+ ` int child = tree.node(id).first_child;`,
836
+ ` for (int i = 0; i < idx && child >= 0; ++i) child = tree.node(child).next_sibling;`,
837
+ ` id = child;`,
838
+ ` }`,
839
+ ` return gea::embedded::ui::NodeHandle(id);`,
840
+ `}`,
841
+ `inline bool same_rendered_item(const ${itemType} &a, const ${itemType} &b) {`,
842
+ ...sameItemLines(field, rowSlots.itemFieldNames).map((line) => ` ${line}`),
843
+ `}`,
844
+ thresholdPatch
845
+ ? `inline void patch_row(gea::embedded::ui::NodeHandle ${rowRootVar}, double __gea_threshold, const ${itemType} &previous, const ${itemType} &${itemName}, bool initial) {`
846
+ : typedCarrier
847
+ ? `inline void patch_row(gea::embedded::ui::NodeHandle ${rowRootVar}, const std::shared_ptr<${field.storeClass}> &store, const ${itemType} &previous, const ${itemType} &${itemName}, bool initial) {`
848
+ : `inline void patch_row(gea::embedded::ui::NodeHandle ${rowRootVar}, const gea_cpp_value &store, const ${itemType} &previous, const ${itemType} &${itemName}, bool initial) {`,
849
+ thresholdPatch ? ` (void)__gea_threshold;` : ` (void)store;`,
850
+ ...patchResolveLines.map((line) => ` ${line}`),
851
+ ...rowPatchLines(itemName, rowSlots.patches, rowSlots.unconditionalPatches).map(rewriteThresholdReader).map((line) => ` ${line}`),
852
+ `}`,
853
+ thresholdPatch
854
+ ? `inline gea::embedded::ui::NodeHandle make_row(double __gea_threshold, const std::shared_ptr<${field.storeClass}> &typed_store, const ${itemType} &${itemName}) {`
855
+ : typedCarrier
856
+ ? `inline gea::embedded::ui::NodeHandle make_row(const std::shared_ptr<${field.storeClass}> &store, const ${itemType} &${itemName}) {`
857
+ : `inline gea::embedded::ui::NodeHandle make_row(const gea_cpp_value &store, const std::shared_ptr<${field.storeClass}> &typed_store, const ${itemType} &${itemName}) {`,
858
+ // Row event handlers reference `typed_store`; in the typed flavor the
859
+ // store param IS the typed pointer, so alias it.
860
+ ...(thresholdPatch ? [] : typedCarrier ? [` const auto &typed_store = store;`] : []),
861
+ thresholdPatch ? ` (void)__gea_threshold; (void)typed_store; (void)${itemName};` : ` (void)store; (void)typed_store; (void)${itemName};`,
862
+ ` auto ${rowRootVar} = ${createRow};`,
863
+ ...attributeLines(rowRootVar, row, rowTemplate.slots).map((line) => ` ${line}`),
864
+ ...rowSetup.map((line) => ` ${line}`),
865
+ ...rowChildTree.treeLines,
866
+ ...rowSlots.lines.map(rewriteThresholdReader).map((line) => ` ${line}`),
867
+ ...rowSlots.eventLines.map((line) => ` ${line}`),
868
+ ` return ${rowRootVar};`,
869
+ `}`,
870
+ // The Context now holds a typed `std::shared_ptr<${storeClass}>` to the
871
+ // backing store. The mount fn extracts it once via
872
+ // `gea_cpp_value_as_shared_ptr<${storeClass}>(store)` (an existing
873
+ // runtime helper that walks proxy_target → object_owner). The apply
874
+ // iterates `ctx.typed_store->${fieldName}` directly — a plain
875
+ // `std::vector<${itemType}>` reference. The previous form went through
876
+ // `store.record_get_literal("${fieldName}")` every fire, which calls
877
+ // `gea_cpp_key(const std::vector<${itemType}>&)` and **heap-allocates a
878
+ // gea_cpp_value record per element** to box them into an array_value
879
+ // snapshot, then back-converts each element to typed
880
+ // (`read_${itemType}`) every frame. Direct access skips the entire
881
+ // snapshot dance.
882
+ //
883
+ // Falls back to the gea_cpp_value path when typed extraction returns
884
+ // null — covers the case where the store wasn't a typed-storage
885
+ // candidate, or the proxy/object_owner relationship isn't intact.
886
+ ...(thresholdPatch ? [`struct ThresholdSnapshot { double ${thresholdPatch.storeField.fieldName} = 0.0; bool valid = false; };`] : []),
887
+ `struct Context {`,
888
+ ` gea::embedded::ui::NodeHandle root;`,
889
+ ` std::shared_ptr<${field.storeClass}> typed_store;`,
890
+ ...(typedCarrier ? [] : [` gea_cpp_value store;`]),
891
+ ...(thresholdPatch ? [` ThresholdSnapshot threshold;`] : []),
892
+ ...(thresholdPatch ? [` std::vector<std::size_t> threshold_order;`] : []),
893
+ ` struct RowEntry { std::string key; gea::embedded::ui::NodeHandle row; ${itemType} item; };`,
894
+ ` std::vector<RowEntry> rows;`,
895
+ `};`,
896
+ ...(thresholdPatch ? thresholdPatchHelperLines(thresholdPatch, !!typedCarrier) : []),
897
+ // Typed fast path. The mounted renderer definitions are emitted after
898
+ // geatsc's store classes and typed-array rewrites, so this body can
899
+ // dereference the concrete store class directly in both single-app and
900
+ // application translation units.
901
+ `inline void apply_typed_path(Context &ctx, ${field.storeClass} *typed_store) {`,
902
+ ...(thresholdPatch ? [` const double __gea_threshold = typed_store->${sanitizeCppIdentifier(thresholdPatch.storeField.fieldName)};`] : []),
903
+ // A getter is recomputed by CALLING the zero-arg getter (`name()`); a field
904
+ // reads the stored vector member. Both are `std::vector<${itemType}>` of
905
+ // typed structs (a getter's derived-array element type stays typed — the
906
+ // mutation analyzer ignores Symbol-keyed dirty-bit writes), so the diff body
907
+ // iterates them identically with no per-element conversion.
908
+ ` const auto &__gea_typed_items = typed_store->${field.fieldName}${field.isGetter ? '()' : ''};`,
909
+ ...diffBodyLines('__gea_typed_items', null, thresholdPatch ? '__gea_threshold' : null).map((line) => ` ${line}`),
910
+ `}`,
911
+ // Outer apply: instantiates the typed-fast-path template at the call
912
+ // site if the typed pointer is available, else falls through to the
913
+ // gea_cpp_value snapshot path. The fast path skips
914
+ // `gea_cpp_key(std::vector<${itemType}>&)` — a per-frame allocation of
915
+ // ${itemType.length}-many record entries to box items as gea_cpp_value
916
+ // — and the matching `read_${field.itemType}` round-trip.
917
+ `inline void apply(Context &ctx) {`,
918
+ ...(typedCarrier
919
+ ? [` apply_typed_path(ctx, ctx.typed_store.get());`]
920
+ : [
921
+ ` if (ctx.typed_store) {`,
922
+ ` apply_typed_path(ctx, ctx.typed_store.get());`,
923
+ ` return;`,
924
+ ` }`,
925
+ // A getter is computed, not a stored record field, so there is no
926
+ // `record_get_literal` snapshot to read — a getter-backed list requires the
927
+ // typed store. (In practice a store carrying a getter is always typed.)
928
+ ...(field.isGetter
929
+ ? [` return;`]
930
+ : [
931
+ // Fallback: gea_cpp_value snapshot path. Reads the field via the
932
+ // dynamic record interface and converts each item back to typed via
933
+ // read_${field.itemType}.
934
+ ` auto &__gea_store_unwrapped = (ctx.store.kind == gea_cpp_value::kind_t::proxy && ctx.store.proxy_target) ? *ctx.store.proxy_target : ctx.store;`,
935
+ ` auto __gea_array_value = __gea_store_unwrapped.record_get_literal(${cppString(field.fieldName)});`,
936
+ ` const auto &__gea_values = (__gea_array_value.kind == gea_cpp_value::kind_t::proxy && __gea_array_value.proxy_target) ? __gea_array_value.proxy_target->array_ref() : __gea_array_value.array_ref();`,
937
+ ...(thresholdPatch && thresholdPatch.storeField.readerName
938
+ ? [` const double __gea_threshold = ${thresholdPatch.storeField.readerName}(ctx.store);`]
939
+ : []),
940
+ ...diffBodyLines('__gea_values', `const auto ${itemName} = ${itemReaderFn}(__gea_item_value);`, thresholdPatch ? '__gea_threshold' : null).map((line) => ` ${line}`),
941
+ ]),
942
+ ]),
943
+ `}`,
944
+ `} // namespace ${helperNs}`,
945
+ ``,
946
+ ];
947
+ return [
948
+ ...helperLines,
949
+ `inline gea::embedded::ui::NodeHandle ${mountedRendererName(component)}(${typedCarrier ? `const std::shared_ptr<${field.storeClass}> &store` : 'const gea_cpp_value &store'}, const std::shared_ptr<NativeDisposer> &disposer) {`,
950
+ ` auto root = ${createRoot};`,
951
+ ...attributeLines('root', root, component.template.slots),
952
+ ...setup,
953
+ ...(typedCarrier
954
+ ? [` auto __gea_ctx = std::make_shared<${helperNs}::Context>(${helperNs}::Context{root, store, {}});`]
955
+ : [
956
+ ` auto __gea_typed_store = gea_cpp_value_as_shared_ptr<${field.storeClass}>(store);`,
957
+ ` auto __gea_ctx = std::make_shared<${helperNs}::Context>(${helperNs}::Context{root, std::move(__gea_typed_store), store, {}});`,
958
+ ]),
959
+ // A getter binds to its dependency fields (its `this.<field>` reads); a
960
+ // field binds to itself. Both also bind any extra store fields read by row
961
+ // slots (`fullApplyStoreFields`).
962
+ ...hubAwareCtxBindLines(field, uniqueItemFieldNames([...(field.isGetter ? field.reactiveDeps ?? [] : [field.fieldName]), ...fullApplyStoreFields.map((dep) => dep.fieldName)]).map((dep) => cppString(dep)).join(', '), `[__gea_ctx]() mutable -> void { ${helperNs}::apply(*__gea_ctx); }`),
963
+ ...(thresholdPatch
964
+ ? hubAwareCtxBindLines(field, cppString(thresholdPatch.storeField.fieldName), `[__gea_ctx]() mutable -> void { ${helperNs}::patch_threshold_from_store(*__gea_ctx); }`)
965
+ : []),
966
+ ` return root;`,
967
+ `}`,
968
+ ``,
969
+ ];
970
+ }
971
+ function sameItemLines(field, itemFieldNames = field.itemFields.map((itemField) => sanitizeCppIdentifier(itemField.name))) {
972
+ const comparisons = uniqueItemFieldNames(itemFieldNames)
973
+ .map((name) => field.itemFields.find((itemField) => sanitizeCppIdentifier(itemField.name) === name))
974
+ .filter((itemField) => itemField !== undefined)
975
+ .map((itemField) => sameItemComparison(itemField));
976
+ if (comparisons.some((comparison) => comparison === null) || comparisons.length === 0) {
977
+ return [
978
+ '// TODO(gea-ir): add item comparators for non-literal keyed-list fields so mounted rows can patch only changed items.',
979
+ 'return false;',
980
+ ];
981
+ }
982
+ return [`return ${comparisons.join(' && ')};`];
983
+ }
984
+ // Emits the row's nested element tree. Returns:
985
+ // treeLines — element create + classList + appendChild lines for every
986
+ // child of the row root, run once inside make_row before
987
+ // apply lines. An empty array means the row has no children.
988
+ // pathVars — walk-path → local-var-name map. Slot lowering uses this to
989
+ // target a specific nested element by its IR walk path. The
990
+ // root walk ([]) maps to the row var name supplied by the
991
+ // caller.
992
+ // ok — false if any element couldn't be created (returns early).
993
+ function emitRowChildTree(parsed, rowVarName, nextVar) {
994
+ const treeLines = [];
995
+ const pathVars = new Map();
996
+ const elementPaths = new Map();
997
+ pathVars.set('', rowVarName);
998
+ // parseTemplateRoot wraps the row in a synthetic `#fragment`. The row's
999
+ // own root element is already created by the caller (as `rowVarName` via
1000
+ // `createRow`), so descend into that element's children rather than
1001
+ // re-creating it. If the parse didn't wrap (already the root element), use
1002
+ // it directly.
1003
+ const rowRoot = parsed.tag === '#fragment' && parsed.children.length === 1 && parsed.children[0].kind === 'element'
1004
+ ? parsed.children[0]
1005
+ : parsed;
1006
+ if (!emitRowChildren(rowRoot, rowVarName, [], treeLines, nextVar, pathVars, elementPaths)) {
1007
+ return { ok: false, treeLines: [], pathVars, elementPaths };
1008
+ }
1009
+ return { ok: true, treeLines, pathVars, elementPaths };
1010
+ }
1011
+ function emitRowChildren(parent, parentVar, parentPath, lines, nextVar, pathVars, elementPaths) {
1012
+ for (let index = 0; index < parent.children.length; index += 1) {
1013
+ const child = parent.children[index];
1014
+ const childPath = [...parentPath, index];
1015
+ if (child.kind === 'element') {
1016
+ const createChild = uiCreateNodeExpression(child);
1017
+ if (!createChild)
1018
+ return false;
1019
+ const childVar = nextVar();
1020
+ lines.push(` auto ${childVar} = ${createChild};`);
1021
+ lines.push(` ${childVar}.setTagName(${cppString(child.tag.toLowerCase())});`);
1022
+ if (child.className) {
1023
+ lines.push(` ${childVar}.classList().set(${cppString(child.className)});`);
1024
+ }
1025
+ if (child.attrs) {
1026
+ for (const [name, value] of Object.entries(child.attrs)) {
1027
+ const lower = name.toLowerCase();
1028
+ if (lower === 'class' || lower === 'style')
1029
+ continue;
1030
+ lines.push(` ${childVar}.setAttribute(${cppString(name)}, ${cppString(value)});`);
1031
+ }
1032
+ }
1033
+ lines.push(` ${parentVar}.appendChild(${childVar});`);
1034
+ pathVars.set(childPath.join(','), childVar);
1035
+ elementPaths.set(childVar, childPath);
1036
+ if (!emitRowChildren(child, childVar, childPath, lines, nextVar, pathVars, elementPaths))
1037
+ return false;
1038
+ continue;
1039
+ }
1040
+ if (child.kind === 'text') {
1041
+ const text = renderableTemplateText(child.text);
1042
+ if (!text)
1043
+ continue;
1044
+ // The IR uses '0' as the placeholder for `directText` text slots; the
1045
+ // matching slot lowering will set the real reactive content. Skip
1046
+ // emitting a literal "0" — otherwise the user sees a bare zero on
1047
+ // screen until the first reactive bind fires.
1048
+ if (text === '0') {
1049
+ pathVars.set(childPath.join(','), parentVar);
1050
+ continue;
1051
+ }
1052
+ // Static text that isn't a placeholder: bake it into the parent if that
1053
+ // parent collapses to a single Text node (one run), otherwise create a
1054
+ // sibling Text node. A multi-run text-tag parent (e.g. `<span>{a} / {b}</span>`)
1055
+ // stays a View, so baking via setText would overlap the runs. Same heuristic
1056
+ // emitTemplateChildren in cpp-template-renderer.ts uses.
1057
+ const parentTag = parent.tag.toLowerCase();
1058
+ const parentIsTextNode = (parentTag === 'span' || parentTag === 'p' || /^h[1-6]$/.test(parentTag)) &&
1059
+ spanCollapsesToTextNode(parent.children);
1060
+ if (parentIsTextNode) {
1061
+ lines.push(` ${parentVar}.setText(${cppString(text)});`);
1062
+ pathVars.set(childPath.join(','), parentVar);
1063
+ }
1064
+ else {
1065
+ const textVar = nextVar();
1066
+ lines.push(` auto ${textVar} = gea::embedded::ui::Document::instance().createText();`);
1067
+ lines.push(` ${textVar}.setText(${cppString(text)});`);
1068
+ lines.push(` ${parentVar}.appendChild(${textVar});`);
1069
+ pathVars.set(childPath.join(','), textVar);
1070
+ elementPaths.set(textVar, childPath);
1071
+ }
1072
+ continue;
1073
+ }
1074
+ // Slot placeholder. The matching slot's walk path will be `childPath`;
1075
+ // map it to the parent so reactive bindings can target the right
1076
+ // element. We do NOT create a separate node here — the slot apply takes
1077
+ // care of inserting / setting content on the parent.
1078
+ pathVars.set(childPath.join(','), parentVar);
1079
+ }
1080
+ return true;
1081
+ }
1082
+ function rowPatchLines(itemName, patches, unconditionalPatches = []) {
1083
+ const lines = [];
1084
+ lines.push(...unconditionalPatches);
1085
+ for (const patch of patches) {
1086
+ const fieldName = sanitizeCppIdentifier(patch.itemFieldName);
1087
+ lines.push(`if (initial || previous.${fieldName} != ${itemName}.${fieldName}) {`);
1088
+ lines.push(...patch.lines.map((line) => ` ${line}`));
1089
+ lines.push('}');
1090
+ }
1091
+ return lines;
1092
+ }
1093
+ function detectThresholdClassPatch(rowSlots, itemName, rowRootVar) {
1094
+ const escapedItemName = escapeRegExp(itemName);
1095
+ for (let index = 0; index < rowSlots.unconditionalPatches.length - 1; index += 1) {
1096
+ const declaration = rowSlots.unconditionalPatches[index];
1097
+ const update = rowSlots.unconditionalPatches[index + 1];
1098
+ const match = declaration.match(new RegExp(`^const std::string ([A-Za-z_][A-Za-z0-9_]*) = \\(\\((${escapedItemName})\\.([A-Za-z_][A-Za-z0-9_]*) < ([A-Za-z_][A-Za-z0-9_]*\\(store\\))\\) \\? std::string\\("([^"]*)"\\) : std::string\\("([^"]*)"\\)\\);$`));
1099
+ if (!match)
1100
+ continue;
1101
+ const [, valueVar, , itemFieldName, readerCall, trueValue, falseValue] = match;
1102
+ const updateMatch = update.match(new RegExp(`^if \\(([A-Za-z_][A-Za-z0-9_]*)\\.classList\\(\\)\\.value\\(\\) != ${escapeRegExp(valueVar)}\\) \\1\\.classList\\(\\)\\.set\\(${escapeRegExp(valueVar)}\\);$`));
1103
+ if (!updateMatch)
1104
+ continue;
1105
+ const targetVar = updateMatch[1];
1106
+ if (targetVar !== rowRootVar)
1107
+ continue;
1108
+ const storeField = rowSlots.storeFields.find((dep) => dep.readerName !== null && `${dep.readerName}(store)` === readerCall);
1109
+ if (!storeField || storeField.fieldType !== 'double')
1110
+ continue;
1111
+ return {
1112
+ kind: 'class',
1113
+ valueVar,
1114
+ falseValue,
1115
+ itemFieldName,
1116
+ storeField,
1117
+ targetVar,
1118
+ trueValue,
1119
+ };
1120
+ }
1121
+ return null;
1122
+ }
1123
+ function detectThresholdStylePatch(rowSlots, itemName, rowRootVar) {
1124
+ const escapedItemName = escapeRegExp(itemName);
1125
+ for (const line of rowSlots.unconditionalPatches) {
1126
+ const match = line.match(new RegExp(`^gea::embedded::ui::StyleSheet::instance\\(\\)\\.applyProperty\\(([A-Za-z_][A-Za-z0-9_]*), std::string\\("([^"]+)"\\), \\(\\((${escapedItemName})\\.([A-Za-z_][A-Za-z0-9_]*) < ([A-Za-z_][A-Za-z0-9_]*\\(store\\))\\) \\? std::string\\("([^"]*)"\\) : std::string\\("([^"]*)"\\)\\)\\);$`));
1127
+ if (!match)
1128
+ continue;
1129
+ const [, targetVar, propertyName, , itemFieldName, readerCall, trueValue, falseValue] = match;
1130
+ if (targetVar !== rowRootVar)
1131
+ continue;
1132
+ const storeField = rowSlots.storeFields.find((dep) => dep.readerName !== null && `${dep.readerName}(store)` === readerCall);
1133
+ if (!storeField || storeField.fieldType !== 'double')
1134
+ continue;
1135
+ return {
1136
+ kind: 'style',
1137
+ valueVar: '__gea_next_threshold_style',
1138
+ falseValue,
1139
+ itemFieldName,
1140
+ propertyName,
1141
+ storeField,
1142
+ targetVar,
1143
+ trueValue,
1144
+ };
1145
+ }
1146
+ return null;
1147
+ }
1148
+ function thresholdPatchApplyLines(patch) {
1149
+ if (patch.kind === 'class') {
1150
+ return [` if (entry.row.classList().value() != ${patch.valueVar}) entry.row.classList().set(${patch.valueVar});`];
1151
+ }
1152
+ return [
1153
+ ` gea::embedded::ui::StyleSheet::instance().applyProperty(entry.row, ${cppString(patch.propertyName)}, ${patch.valueVar});`,
1154
+ ];
1155
+ }
1156
+ function thresholdPatchHelperLines(patch, typedCarrier) {
1157
+ const fieldName = sanitizeCppIdentifier(patch.storeField.fieldName);
1158
+ const readerName = patch.storeField.readerName;
1159
+ if (!readerName)
1160
+ return [];
1161
+ return [
1162
+ `inline double read_threshold(Context &ctx) {`,
1163
+ ...(typedCarrier
1164
+ ? [` return ctx.typed_store->${fieldName};`]
1165
+ : [` if (ctx.typed_store) return ctx.typed_store->${fieldName};`, ` return ${readerName}(ctx.store);`]),
1166
+ `}`,
1167
+ `inline void sync_threshold_snapshot(Context &ctx) {`,
1168
+ ` ctx.threshold.${fieldName} = read_threshold(ctx);`,
1169
+ ` ctx.threshold.valid = true;`,
1170
+ `}`,
1171
+ `inline double threshold_item_value(const Context::RowEntry &entry) {`,
1172
+ ` return static_cast<double>(entry.item.${patch.itemFieldName});`,
1173
+ `}`,
1174
+ `inline void rebuild_threshold_order(Context &ctx) {`,
1175
+ ` ctx.threshold_order.clear();`,
1176
+ ` ctx.threshold_order.reserve(ctx.rows.size());`,
1177
+ ` for (std::size_t __gea_index = 0; __gea_index < ctx.rows.size(); ++__gea_index) ctx.threshold_order.push_back(__gea_index);`,
1178
+ ` std::sort(ctx.threshold_order.begin(), ctx.threshold_order.end(), [&ctx](std::size_t a, std::size_t b) {`,
1179
+ ` return threshold_item_value(ctx.rows[a]) < threshold_item_value(ctx.rows[b]);`,
1180
+ ` });`,
1181
+ `}`,
1182
+ `inline std::size_t threshold_lower_bound(Context &ctx, double value) {`,
1183
+ ` std::size_t low = 0;`,
1184
+ ` std::size_t high = ctx.threshold_order.size();`,
1185
+ ` while (low < high) {`,
1186
+ ` const std::size_t mid = low + ((high - low) / 2);`,
1187
+ ` if (threshold_item_value(ctx.rows[ctx.threshold_order[mid]]) < value) low = mid + 1;`,
1188
+ ` else high = mid;`,
1189
+ ` }`,
1190
+ ` return low;`,
1191
+ `}`,
1192
+ `inline void patch_threshold_range(Context &ctx, double previousThreshold, double nextThreshold) {`,
1193
+ ` if (previousThreshold == nextThreshold) {`,
1194
+ ` ctx.threshold.${fieldName} = nextThreshold;`,
1195
+ ` ctx.threshold.valid = true;`,
1196
+ ` return;`,
1197
+ ` }`,
1198
+ ` double low = previousThreshold < nextThreshold ? previousThreshold : nextThreshold;`,
1199
+ ` double high = previousThreshold < nextThreshold ? nextThreshold : previousThreshold;`,
1200
+ ` if (ctx.threshold_order.size() != ctx.rows.size()) rebuild_threshold_order(ctx);`,
1201
+ ` if (ctx.threshold_order.empty()) {`,
1202
+ ` ctx.threshold.${fieldName} = nextThreshold;`,
1203
+ ` ctx.threshold.valid = true;`,
1204
+ ` return;`,
1205
+ ` }`,
1206
+ ` std::size_t start = threshold_lower_bound(ctx, low);`,
1207
+ ` std::size_t end = threshold_lower_bound(ctx, high);`,
1208
+ ` const double threshold = nextThreshold;`,
1209
+ ` for (std::size_t __gea_index = start; __gea_index < end; ++__gea_index) {`,
1210
+ ` auto &entry = ctx.rows[ctx.threshold_order[__gea_index]];`,
1211
+ ` const std::string ${patch.valueVar} = ((entry.item.${patch.itemFieldName} < threshold) ? std::string(${cppString(patch.trueValue)}) : std::string(${cppString(patch.falseValue)}));`,
1212
+ ...thresholdPatchApplyLines(patch),
1213
+ ` }`,
1214
+ ` ctx.threshold.${fieldName} = nextThreshold;`,
1215
+ ` ctx.threshold.valid = true;`,
1216
+ `}`,
1217
+ `inline void patch_threshold_from_store(Context &ctx) {`,
1218
+ ` const double nextThreshold = read_threshold(ctx);`,
1219
+ ` if (!ctx.threshold.valid) {`,
1220
+ ` ctx.threshold.${fieldName} = nextThreshold;`,
1221
+ ` ctx.threshold.valid = true;`,
1222
+ ` return;`,
1223
+ ` }`,
1224
+ ` patch_threshold_range(ctx, ctx.threshold.${fieldName}, nextThreshold);`,
1225
+ `}`,
1226
+ ];
1227
+ }
1228
+ function escapeRegExp(value) {
1229
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1230
+ }
1231
+ function uniqueItemFieldNames(fields) {
1232
+ return [...new Set(fields)];
1233
+ }
1234
+ function uniqueEqual(values) {
1235
+ if (values.length === 0)
1236
+ return null;
1237
+ const [first] = values;
1238
+ return values.every((value) => value === first) ? first : null;
1239
+ }
1240
+ function intrinsicImageRowSlot(html, slots) {
1241
+ if (slots.length !== 1)
1242
+ return null;
1243
+ const slot = slots[0];
1244
+ if (slot.kind !== 'mount' || mountSlotTag(slot) !== 'Image')
1245
+ return null;
1246
+ if (html.trim() === '<!--0-->')
1247
+ return slot;
1248
+ const root = parseTemplateRoot(html);
1249
+ if (!root)
1250
+ return null;
1251
+ const attrs = root.attrs ?? {};
1252
+ const keys = Object.keys(attrs);
1253
+ if (keys.length !== 1 || keys[0] !== 'style' || !/\bdisplay\s*:\s*contents\b/i.test(attrs.style))
1254
+ return null;
1255
+ if (root.children.length !== 1)
1256
+ return null;
1257
+ const child = root.children[0];
1258
+ return child.kind === 'slot' && child.index === slot.index ? slot : null;
1259
+ }
1260
+ // A <span>/<p>/<h*> collapses into a single native Text node only when it holds
1261
+ // exactly ONE text run. With multiple runs (e.g. `<span>{a} / {b}</span>`) it
1262
+ // must stay a View so each run is a separate child text node — otherwise one run
1263
+ // is baked via `setText` on the parent and the rest overlap it at the parent
1264
+ // origin. Mirrors canUseTextNodeForElement() in cpp-template-renderer.ts.
1265
+ function spanCollapsesToTextNode(children) {
1266
+ if (children.some((c) => c.kind === 'element'))
1267
+ return false;
1268
+ let runs = 0;
1269
+ for (const c of children) {
1270
+ if (c.kind === 'text') {
1271
+ if (renderableTemplateText(c.text))
1272
+ runs += 1;
1273
+ }
1274
+ else {
1275
+ runs += 1;
1276
+ }
1277
+ if (runs > 1)
1278
+ return false;
1279
+ }
1280
+ return true;
1281
+ }
1282
+ function uiCreateNodeExpression(root) {
1283
+ const normalized = root.tag.toLowerCase();
1284
+ if (normalized === 'canvas')
1285
+ return 'gea::embedded::ui::Document::instance().createCanvas()';
1286
+ if (normalized === 'camera')
1287
+ return 'gea::embedded::ui::Document::instance().createCamera()';
1288
+ if (normalized === 'audio')
1289
+ return 'gea::embedded::ui::Document::instance().createAudio()';
1290
+ if (normalized === 'img')
1291
+ return 'gea::embedded::ui::Document::instance().createImage()';
1292
+ if (normalized === 'virtual-list')
1293
+ return 'gea::embedded::ui::Document::instance().createVirtualList()';
1294
+ if (normalized === 'input' && root.attrs?.type === 'button')
1295
+ return 'gea::embedded::ui::Document::instance().createButton()';
1296
+ if (normalized === 'button')
1297
+ return 'gea::embedded::ui::Document::instance().createButton()';
1298
+ if (normalized === 'span' || normalized === 'p' || /^h[1-6]$/.test(normalized)) {
1299
+ // children is present for TemplateElement (child path); absent for a bare
1300
+ // HtmlRoot (row root) — default to text node there to preserve prior shape.
1301
+ const children = root.children;
1302
+ if (!children || spanCollapsesToTextNode(children)) {
1303
+ return 'gea::embedded::ui::Document::instance().createText()';
1304
+ }
1305
+ return 'gea::embedded::ui::Document::instance().createView()';
1306
+ }
1307
+ return 'gea::embedded::ui::Document::instance().createView()';
1308
+ }
1309
+ function renderableTemplateText(text) {
1310
+ const collapsed = text.replace(/\s+/g, ' ');
1311
+ return collapsed.trim() ? collapsed : '';
1312
+ }
1313
+ function canUseMountedFieldReaders(lowered) {
1314
+ return lowered.fields.every((field) => field.readerName !== null);
1315
+ }
1316
+ function mountedFieldReaderName(field) {
1317
+ if (field.readerName)
1318
+ return field.readerName;
1319
+ throw new Error(`missing mounted field reader for ${field.storeClass}.${field.fieldName}`);
1320
+ }
1321
+ function sameItemComparison(field) {
1322
+ const shape = fieldShape(field);
1323
+ if (shape?.kind !== 'literal')
1324
+ return null;
1325
+ const name = sanitizeCppIdentifier(field.name);
1326
+ return `a.${name} == b.${name}`;
1327
+ }
1328
+ function fieldShape(field) {
1329
+ return field.shape ?? shapeFromInitializer(field.initializer);
1330
+ }
1331
+ function shapeFromInitializer(initializer) {
1332
+ if (!initializer)
1333
+ return null;
1334
+ const text = initializer.trim();
1335
+ if (/^-?(?:\d+|\d+\.\d+|\.\d+)$/.test(text))
1336
+ return { kind: 'literal', valueType: 'number' };
1337
+ if (text === 'true' || text === 'false')
1338
+ return { kind: 'literal', valueType: 'boolean' };
1339
+ if (text === 'null')
1340
+ return { kind: 'literal', valueType: 'null' };
1341
+ if ((text.startsWith("'") && text.endsWith("'")) || (text.startsWith('"') && text.endsWith('"'))) {
1342
+ return { kind: 'literal', valueType: 'string' };
1343
+ }
1344
+ return null;
1345
+ }
1346
+ export function canMountComponent(component, components, storeFields, storeArrayFields, constants = new Map(), storeMethods = []) {
1347
+ // Reactive self-store components mount ONLY through their typed renderer —
1348
+ // a parent in any mode mounts them as `mount_X(std::make_shared<X>(), …)`.
1349
+ // The boxed template gates below would otherwise approve a mount call whose
1350
+ // `store` argument can't convert to the typed renderer's shared_ptr param.
1351
+ if (component.reactiveState) {
1352
+ return selfStoreMountedRenderer(component, components, storeFields, storeArrayFields, constants, storeMethods) !== null;
1353
+ }
1354
+ const root = parseHtmlRoot(component.template.html);
1355
+ if (!root || !uiCreateNodeExpression(root))
1356
+ return false;
1357
+ const keyed = component.template.slots.filter((slot) => slot.kind === 'keyed-list');
1358
+ const template = canTemplateMountComponent(component, components, storeFields, constants, (child) => child !== component && canMountComponent(child, components, storeFields, storeArrayFields, constants, storeMethods), storeMethods, storeArrayFields);
1359
+ if (template)
1360
+ return true;
1361
+ if (keyed.length === 1 && canUseDedicatedKeyedListRenderer(component, constants)) {
1362
+ return keyedListMountedRenderer(component, components, storeFields, storeArrayFields, constants, storeMethods) !== null;
1363
+ }
1364
+ if (keyed.length > 1 && canUseDedicatedKeyedListRenderer(component, constants)) {
1365
+ return multiKeyedListMountedRenderer(component, storeArrayFields, constants) !== null;
1366
+ }
1367
+ const lowered = lowerSlots(component.template.slots, storeFields, constants);
1368
+ if (!rootSetupSlotsSupported(component.template.slots, storeFields, storeMethods, constants))
1369
+ return false;
1370
+ return (component.template.slots.length === 0 ||
1371
+ component.template.slots.every((slot) => isRootSetupSlot(slot, constants)) ||
1372
+ (canUseStyleTextMountedSlots(component.template.slots) && lowered !== null && canUseMountedFieldReaders(lowered)));
1373
+ }
1374
+ function canUseStyleTextMountedSlots(slots) {
1375
+ return slots.every((slot) => slot.kind === 'style' || slot.kind === 'text' || isRootSetupSlot(slot));
1376
+ }