@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,2235 @@
1
+ import ts from 'typescript';
2
+ import { cppString, cssPropertyName, isPxLengthStylePropertyName, isRecord, isRuntimeNumericConstantIdentifier, nativeStyleColorExpression, opaqueCssHexColor, sanitizeCppIdentifier, styleDeclarationEnumForPropertyName, styleKeywordPropertiesForPropertyName, styleKeywordPropertyValuesForPropertyName, styleOpaqueColorTargetForPropertyName, stylePercentPropertyEnumForPropertyName, styleRawNumberPropertyEnumsForPropertyName, } from './utils.js';
3
+ // Whether the global store cell for `globalName` is the TYPED shared_ptr.
4
+ // geatsc core emits store singleton accessors as `std::shared_ptr<Class>&`
5
+ // for regular Store subclasses regardless of whether their runtime base is
6
+ // compiled or lean. Self-stores are component instances, not exported cells.
7
+ export function storeGlobalIsTyped(globalName, storeFields) {
8
+ return storeFields.some((field) => field.storeGlobalName === globalName && !field.storeIsSelfStore);
9
+ }
10
+ export function attributeLines(varName, root, slots = []) {
11
+ void slots;
12
+ const lines = [];
13
+ lines.push(` ${varName}.setTagName(${cppString(root.tag.toLowerCase())});`);
14
+ if (root.className) {
15
+ lines.push(` ${varName}.classList().set(${cppString(root.className)});`);
16
+ }
17
+ // Forward any other static HTML attributes from the template to the
18
+ // runtime node so framework code (e.g. InputController's momentum opt-in)
19
+ // can read them via getAttribute()/hasAttribute(). Skip `class` and
20
+ // `style` — those have their own dedicated lowering paths.
21
+ const tag = root.tag.toLowerCase();
22
+ if (root.attrs) {
23
+ for (const [name, value] of Object.entries(root.attrs)) {
24
+ const lower = name.toLowerCase();
25
+ if (lower === 'class' || lower === 'style')
26
+ continue;
27
+ // `<img src="face.png">` with a static path: decode the build-embedded
28
+ // asset bytes into an image slot, rather than storing an inert "src"
29
+ // attribute the renderer never decodes.
30
+ if (lower === 'src' && (tag === 'img' || tag === 'image')) {
31
+ lines.push(...imageSrcAssetLines(varName, value));
32
+ continue;
33
+ }
34
+ if (lower === 'fit' && (tag === 'img' || tag === 'image')) {
35
+ lines.push(...imageFitApplyLines(varName, value));
36
+ continue;
37
+ }
38
+ lines.push(` ${varName}.setAttribute(${cppString(name)}, ${cppString(value)});`);
39
+ }
40
+ }
41
+ return lines;
42
+ }
43
+ export function rootSetupLines(varName, slots, storeFields = [], storeMethods = [], fieldAccess, rootTag, constants = new Map(), disposerVar) {
44
+ const lines = [];
45
+ for (const slot of slots) {
46
+ if (slot.kind === 'style') {
47
+ const lowered = lowerStaticRootStyle(varName, slot, constants);
48
+ if (lowered)
49
+ lines.push(...lowered);
50
+ continue;
51
+ }
52
+ if (slot.kind !== 'attr' && slot.kind !== 'event')
53
+ continue;
54
+ if (slot.walk.length !== 0)
55
+ return null;
56
+ if (slot.kind === 'attr') {
57
+ const lowered = attributeSlotLines(varName, slot, constants);
58
+ if (!lowered)
59
+ return null;
60
+ lines.push(...lowered);
61
+ continue;
62
+ }
63
+ const lowered = lowerRootEvent(varName, slot, storeFields, storeMethods, fieldAccess, rootTag, constants, disposerVar);
64
+ if (!lowered)
65
+ return null;
66
+ lines.push(...lowered);
67
+ }
68
+ return lines;
69
+ }
70
+ export function eventSetupLines(varName, slot, storeFields = [], storeMethods = [], fieldAccess, rootTag, constants = new Map(), disposerVar) {
71
+ return slot.kind === 'event' ? lowerRootEvent(varName, slot, storeFields, storeMethods, fieldAccess, rootTag, constants, disposerVar) : null;
72
+ }
73
+ export function rootSetupSlotsSupported(slots, storeFields = [], storeMethods = [], constants = new Map()) {
74
+ return rootSetupLines('root', slots, storeFields, storeMethods, undefined, undefined, constants) !== null;
75
+ }
76
+ export function isRootSetupSlot(slot, constants = new Map()) {
77
+ return ((slot.kind === 'attr' || slot.kind === 'event' || slot.kind === 'ref') && slot.walk.length === 0) || isStaticRootStyleSlot(slot, constants);
78
+ }
79
+ export function childForMount(slot, components) {
80
+ const tag = mountSlotTag(slot);
81
+ return tag ? (components.find((component) => component.exportName === tag) ?? null) : null;
82
+ }
83
+ export function mountSlotTag(slot) {
84
+ const payload = slot.payload;
85
+ if (!payload || typeof payload !== 'object' || !('tag' in payload))
86
+ return null;
87
+ const tag = payload.tag;
88
+ return typeof tag === 'string' ? tag : null;
89
+ }
90
+ export function mountSlotAttrs(slot) {
91
+ const payload = slot.payload;
92
+ if (!payload || typeof payload !== 'object' || !('attrs' in payload))
93
+ return [];
94
+ const attrs = payload.attrs;
95
+ if (!Array.isArray(attrs))
96
+ return [];
97
+ return attrs
98
+ .map((attr) => {
99
+ if (!attr || typeof attr !== 'object' || !('code' in attr))
100
+ return null;
101
+ const code = attr.code;
102
+ return typeof code === 'string' ? code : null;
103
+ })
104
+ .filter((code) => !!code);
105
+ }
106
+ export function parseMountAttr(code) {
107
+ const trimmed = code.trim();
108
+ const stringAttr = trimmed.match(/^([A-Za-z_$][A-Za-z0-9_$]*)=(["'])(.*)\2$/s);
109
+ if (stringAttr)
110
+ return { name: stringAttr[1], expr: `${stringAttr[2]}${stringAttr[3]}${stringAttr[2]}` };
111
+ const expressionAttr = trimmed.match(/^([A-Za-z_$][A-Za-z0-9_$]*)=\{([\s\S]*)\}$/);
112
+ if (expressionAttr)
113
+ return { name: expressionAttr[1], expr: expressionAttr[2].trim() };
114
+ const bareAttr = trimmed.match(/^([A-Za-z_$][A-Za-z0-9_$]*)$/);
115
+ return bareAttr ? { name: bareAttr[1], expr: 'true' } : null;
116
+ }
117
+ export function mountSlotStyleSlot(slot) {
118
+ for (const attr of mountSlotAttrs(slot)) {
119
+ const parsed = parseMountAttr(attr);
120
+ if (!parsed || parsed.name !== 'style')
121
+ continue;
122
+ const fields = parseExpressionObjectFields(parsed.expr);
123
+ if (!fields)
124
+ return null;
125
+ return {
126
+ index: slot.index,
127
+ kind: 'style',
128
+ walk: [],
129
+ expr: parsed.expr,
130
+ exprObjectFields: fields,
131
+ payload: { attrName: 'style' },
132
+ };
133
+ }
134
+ return null;
135
+ }
136
+ export function mountSlotImageSourceLines(varName, slot) {
137
+ if (mountSlotTag(slot) !== 'Image')
138
+ return null;
139
+ for (const attr of mountSlotAttrs(slot)) {
140
+ const parsed = parseMountAttr(attr);
141
+ if (!parsed || parsed.name !== 'src')
142
+ continue;
143
+ const imageGlobal = simpleIdentifierValue(parsed.expr);
144
+ if (imageGlobal)
145
+ return [imageIdApplyLine(varName, imageGlobal)];
146
+ // `<Image src="face.png">` — string-literal path decodes a build-embedded
147
+ // asset. See generate-gea-embedded-assets.mjs.
148
+ const literalPath = stringLiteralValue(parsed.expr);
149
+ if (literalPath !== null) {
150
+ return imageSrcAssetLines(varName, literalPath);
151
+ }
152
+ return null;
153
+ }
154
+ return [];
155
+ }
156
+ export function fieldNameForSlot(slot) {
157
+ if (slot.exprPath && slot.exprPath.length > 1)
158
+ return sanitizeCppIdentifier(slot.exprPath[slot.exprPath.length - 1]);
159
+ const match = slot.expr?.match(/\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
160
+ return match ? sanitizeCppIdentifier(match[1]) : null;
161
+ }
162
+ export function keyedListPayload(slot) {
163
+ return isRecord(slot.payload) ? slot.payload : null;
164
+ }
165
+ export function keyedListKeyExpression(payload, itemName, field) {
166
+ const keyField = keyedListKeyField(payload, itemName, field);
167
+ if (!keyField)
168
+ return 'std::to_string(__gea_index)';
169
+ const value = `${itemName}.${sanitizeCppIdentifier(keyField.name)}`;
170
+ return keyField.shape?.kind === 'literal' && keyField.shape.valueType === 'string' ? value : `gea_cpp_to_string(${value})`;
171
+ }
172
+ export function lowerSlots(slots, storeFields, constants = new Map()) {
173
+ const stateTypes = new Set();
174
+ const deps = [];
175
+ const fields = [];
176
+ const staticLines = [];
177
+ const lines = [];
178
+ const style = lowerStyleSlots(slots, storeFields, constants);
179
+ if (style) {
180
+ stateTypes.add(style.stateType);
181
+ deps.push(...style.deps);
182
+ fields.push(...style.fields);
183
+ staticLines.push(...style.staticLines);
184
+ lines.push(...style.lines);
185
+ }
186
+ const textSlots = slots.filter((slot) => slot.kind === 'text');
187
+ for (const slot of textSlots) {
188
+ if (!slot.directText)
189
+ return null;
190
+ // The `root.setText` emit below is only correct when the text is the
191
+ // ROOT's own direct text child (directText walk = [0]). A longer walk
192
+ // means the text lives on a DESCENDANT — this renderer builds no child
193
+ // structure, so emitting against `root` would drop the subtree and patch
194
+ // the wrong node. Bail instead: nested targets are the template
195
+ // renderer's job (it addresses per-element node vars); anything it can't
196
+ // handle must fall off loudly to the dynamic runtime, not render wrong.
197
+ if (slot.walk.length !== 1)
198
+ return null;
199
+ const text = lowerTextSlot(slot, storeFields);
200
+ if (!text)
201
+ return null;
202
+ stateTypes.add(text.stateType);
203
+ deps.push(...text.deps);
204
+ fields.push(...text.fields);
205
+ lines.push(`root.setText((${text.expr}).c_str());`);
206
+ }
207
+ if (stateTypes.size !== 1 || lines.length === 0)
208
+ return null;
209
+ const uniqueFields = uniqueStoreFields(fields);
210
+ const fieldReadPlan = fieldReadPlanForLoweredSlots([...stateTypes][0], uniqueFields);
211
+ return fieldReadPlan ? { stateType: fieldReadPlan.stateType, deps, fields: uniqueFields, fieldReadPlan, staticLines, lines } : null;
212
+ }
213
+ export function parseHtmlRoot(html) {
214
+ const rawTag = html.match(/^<([^>]*)>/);
215
+ const tag = rawTag?.[1].match(/^([A-Za-z][A-Za-z0-9:-]*)/);
216
+ if (!tag)
217
+ return null;
218
+ const attrs = parseStaticAttrs(rawTag?.[1] ?? '');
219
+ return {
220
+ tag: tag[1],
221
+ ...(attrs.class ? { className: attrs.class } : {}),
222
+ attrs,
223
+ };
224
+ }
225
+ export function lowerRowSlots(slots, itemName, field, constants = new Map(), pathVars = new Map([['', 'row']]), storeFields = [], storeMethods = []) {
226
+ const lines = [];
227
+ const patches = [];
228
+ const unconditionalPatches = [];
229
+ const itemFieldNames = [];
230
+ const rowStoreFields = [];
231
+ const eventLines = [];
232
+ const collectPatch = (lowered, patchLines) => {
233
+ itemFieldNames.push(...lowered.itemFields);
234
+ rowStoreFields.push(...lowered.storeFields);
235
+ if (lowered.storeFields.length > 0) {
236
+ unconditionalPatches.push(...patchLines);
237
+ return;
238
+ }
239
+ for (const itemFieldName of lowered.itemFields)
240
+ patches.push({ itemFieldName, lines: patchLines });
241
+ };
242
+ for (const slot of slots) {
243
+ const target = pathVars.get(slot.walk.join(',')) ?? 'row';
244
+ if (slot.kind === 'style' && slot.exprObjectFields && slot.exprObjectFields.length > 0) {
245
+ for (const styleField of slot.exprObjectFields) {
246
+ const propertyName = cssPropertyName(styleField.name);
247
+ const lowered = lowerRowRotateStyleExpression(styleField.expr, propertyName, itemName, field, constants, storeFields) ??
248
+ lowerRowPxLengthStyleExpression(styleField.expr, propertyName, itemName, field, constants, storeFields) ??
249
+ lowerRowPercentLengthStyleExpression(styleField.expr, propertyName, itemName, field, constants, storeFields) ??
250
+ lowerRowOpaqueColorStyleExpression(styleField.expr, propertyName, itemName, field, constants, storeFields) ??
251
+ lowerRowKeywordStyleExpression(styleField.expr, propertyName, itemName, field, constants, storeFields) ??
252
+ lowerRowStyleExpression(styleField.expr, itemName, field, constants, storeFields);
253
+ if (!lowered)
254
+ continue;
255
+ const patchLines = styleApplyLines(target, propertyName, lowered.expr, lowered.shape, lowered.styleUnit);
256
+ lines.push(...patchLines);
257
+ collectPatch(lowered, patchLines);
258
+ }
259
+ continue;
260
+ }
261
+ if (slot.kind === 'text' && slot.expr) {
262
+ const lowered = lowerRowStyleExpression(slot.expr, itemName, field, constants, storeFields);
263
+ if (!lowered)
264
+ continue;
265
+ const textExpr = lowered.shape?.kind === 'literal' && lowered.shape.valueType === 'string'
266
+ ? lowered.expr
267
+ : `gea_cpp_to_string(${lowered.expr})`;
268
+ const patchLines = [`${target}.setText((${textExpr}).c_str());`];
269
+ lines.push(...patchLines);
270
+ if (lowered.itemFields.length === 0 && lowered.storeFields.length === 0) {
271
+ // Constant text — set once, doesn't need to live in patches.
272
+ }
273
+ else {
274
+ collectPatch(lowered, patchLines);
275
+ }
276
+ continue;
277
+ }
278
+ if (slot.kind === 'class') {
279
+ const classLocal = `__gea_next_class_${slot.index}`;
280
+ // Object form: class={{ 'base': true, 'is-active': cond, 'is-hidden': !x }} —
281
+ // build the class string by conditionally appending each truthy key. Mirrors
282
+ // the style-object handling above so a `.map()` row can use the clean class
283
+ // binding instead of a ternary that re-spells the base class in every branch.
284
+ if (slot.exprObjectFields && slot.exprObjectFields.length > 0) {
285
+ const buildLines = [`std::string ${classLocal};`];
286
+ const combinedItemFields = [];
287
+ const combinedStoreFields = [];
288
+ let anyLowered = false;
289
+ for (const objField of slot.exprObjectFields) {
290
+ const lowered = lowerRowStyleExpression(objField.expr, itemName, field, constants, storeFields);
291
+ if (!lowered)
292
+ continue;
293
+ anyLowered = true;
294
+ combinedItemFields.push(...lowered.itemFields);
295
+ combinedStoreFields.push(...lowered.storeFields);
296
+ buildLines.push(`if (${lowered.expr}) { if (!${classLocal}.empty()) ${classLocal} += ' '; ${classLocal} += ${cppString(objField.name)}; }`);
297
+ }
298
+ if (!anyLowered)
299
+ continue;
300
+ const patchLines = [
301
+ ...buildLines,
302
+ `if (${target}.classList().value() != ${classLocal}) ${target}.classList().set(${classLocal});`,
303
+ ];
304
+ lines.push(...patchLines);
305
+ itemFieldNames.push(...combinedItemFields);
306
+ rowStoreFields.push(...combinedStoreFields);
307
+ if (combinedStoreFields.length > 0) {
308
+ unconditionalPatches.push(...patchLines);
309
+ }
310
+ else {
311
+ for (const itemFieldName of uniqueStrings(combinedItemFields))
312
+ patches.push({ itemFieldName, lines: patchLines });
313
+ }
314
+ continue;
315
+ }
316
+ if (slot.expr) {
317
+ const lowered = lowerRowStyleExpression(slot.expr, itemName, field, constants, storeFields);
318
+ if (!lowered)
319
+ continue;
320
+ const classExpr = lowered.shape?.kind === 'literal' && lowered.shape.valueType === 'string'
321
+ ? lowered.expr
322
+ : `gea_cpp_to_string(${lowered.expr})`;
323
+ const patchLines = [
324
+ `const std::string ${classLocal} = ${classExpr};`,
325
+ `if (${target}.classList().value() != ${classLocal}) ${target}.classList().set(${classLocal});`,
326
+ ];
327
+ lines.push(...patchLines);
328
+ collectPatch(lowered, patchLines);
329
+ continue;
330
+ }
331
+ continue;
332
+ }
333
+ if (slot.kind === 'event' && slot.expr) {
334
+ const eventLine = lowerRowEventSlot(slot, target, itemName, field, storeMethods);
335
+ if (eventLine)
336
+ eventLines.push(...eventLine);
337
+ continue;
338
+ }
339
+ // `<img src={item.icon}>` in a row: the path is a per-row value, so resolve it
340
+ // at patch time through the runtime asset lookup (loadAssetPath) and set the
341
+ // image. (Literal/global srcs are static and handled by the row's setup pass;
342
+ // a dynamic src reaching the row setup would reject the keyed list entirely.)
343
+ if (slot.kind === 'attr' && slotAttrName(slot) === 'src' && slot.expr && stringLiteralValue(slot.expr) === null) {
344
+ const lowered = lowerRowStyleExpression(slot.expr, itemName, field, constants, storeFields);
345
+ if (!lowered)
346
+ continue;
347
+ const patchLines = [
348
+ `gea::embedded::ui::ImageElement(${target}.id()).imageId(static_cast<int>(gea::host::image.loadAssetPath((${lowered.expr}).c_str())));`,
349
+ ];
350
+ lines.push(...patchLines);
351
+ collectPatch(lowered, patchLines);
352
+ continue;
353
+ }
354
+ }
355
+ return {
356
+ lines,
357
+ patches,
358
+ unconditionalPatches: uniqueStrings(unconditionalPatches),
359
+ itemFieldNames: uniqueItemFieldNames(itemFieldNames),
360
+ storeFields: uniqueStoreFields(rowStoreFields),
361
+ treeLines: [],
362
+ eventLines,
363
+ };
364
+ }
365
+ function lowerRowEventSlot(slot, target, itemName, field, storeMethods = []) {
366
+ const attrName = slotAttrName(slot);
367
+ const eventType = attrName ? eventTypeFromAttr(attrName) : null;
368
+ if (!eventType || !slot.expr)
369
+ return null;
370
+ const arrow = parseArrowFunction(slot.expr);
371
+ if (!arrow)
372
+ return null;
373
+ // Row handlers usually call a store method, optionally passing item fields
374
+ // (e.g. `() => store.selectNote(note.id)`). The item value must be captured
375
+ // at make_row time because the handler fires asynchronously. Walk each
376
+ // statement, capture every `item.field` argument into a per-handler local,
377
+ // and substitute the capture name into the lowered call.
378
+ const captures = [];
379
+ const captureNames = [];
380
+ const bodyLines = [];
381
+ let usesTypedStore = false;
382
+ for (let index = 0; index < arrow.body.length; index += 1) {
383
+ const lowered = lowerRowEventStatement(arrow.body[index], arrow.params, itemName, field, slot.index, index, captures, captureNames, storeMethods);
384
+ if (!lowered)
385
+ return null;
386
+ if (lowered.usesTypedStore)
387
+ usesTypedStore = true;
388
+ bodyLines.push(...lowered.lines);
389
+ }
390
+ if (bodyLines.length === 0)
391
+ return null;
392
+ const needsDynamicStore = bodyLines.some((line) => /\bstore\b/.test(line));
393
+ const captureList = [
394
+ ...(needsDynamicStore ? ['store'] : []),
395
+ ...(usesTypedStore ? ['typed_store'] : []),
396
+ ...captureNames,
397
+ ].join(', ');
398
+ // Store the handler on the row NODE's own listener slot — the embedded mirror
399
+ // of gea's DOM delegation, where the handler is an expando on the element
400
+ // (`el.__on_click = h`) rather than a per-row listener on a shared ancestor.
401
+ // Tree::dispatchEvent is the single delegated dispatcher: it walks
402
+ // target -> ancestors, sets event.currentTarget/eventPhase per node, and fires
403
+ // each node's slot — so no body-level containsNode guard or manual currentTarget
404
+ // juggling is needed here. Crucially the handler is reclaimed when the row node
405
+ // is removed (removeNode clears its slot), instead of leaking forever onto body's
406
+ // chained click slot (where a removed row's stale capture would keep firing once
407
+ // its node id was recycled onto a live row).
408
+ return [
409
+ ...captures,
410
+ `${target}.addEventListener(${cppString(eventType)}, [${captureList}](gea::framework::events::PointerEvent &event) mutable {`,
411
+ ...bodyLines.map((line) => ` ${line}`),
412
+ '});',
413
+ ];
414
+ }
415
+ function lowerRowEventStatement(statement, params, itemName, field, slotIndex, statementIndex, captures, captureNames, storeMethods) {
416
+ const call = statement.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.([A-Za-z_$][A-Za-z0-9_$]*)\((.*)\)$/s);
417
+ if (!call)
418
+ return null;
419
+ const [, receiver, method, rawArgs] = call;
420
+ const args = splitTopLevelComma(rawArgs).filter((arg) => arg !== '');
421
+ if (params.includes(receiver) && (method === 'preventDefault' || method === 'stopPropagation')) {
422
+ return args.length > 0 ? null : { lines: [`event.${method}();`], usesTypedStore: false };
423
+ }
424
+ if (params.includes(receiver))
425
+ return null;
426
+ const loweredArgs = [];
427
+ for (const arg of args) {
428
+ const number = numericLiteralValue(arg);
429
+ if (number !== null) {
430
+ const direct = `static_cast<double>(${number})`;
431
+ loweredArgs.push(eventArg(`gea_cpp_value(${direct})`, direct, 'number'));
432
+ continue;
433
+ }
434
+ const string = stringLiteralValue(arg);
435
+ if (string !== null) {
436
+ const direct = `std::string(${cppString(string)})`;
437
+ loweredArgs.push(eventArg(`gea_cpp_value(${direct})`, direct, 'string'));
438
+ continue;
439
+ }
440
+ // `event.<field>` — a native scalar field of the framework PointerEvent
441
+ // (clientX/clientY/x/y/…), read at dispatch time (NOT captured at make_row).
442
+ // Without this, a row handler like `event => store.sliderDrag(event.clientX)`
443
+ // (a drag slider inside a keyed list) was dropped entirely, so the touch
444
+ // never reached the store.
445
+ const dottedMatch = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
446
+ if (dottedMatch && params.includes(dottedMatch[1])) {
447
+ const prop = dottedMatch[2];
448
+ const pointerScalarFields = new Set([
449
+ 'clientX', 'clientY', 'x', 'y', 'pageX', 'pageY', 'screenX', 'screenY', 'pointerId',
450
+ ]);
451
+ if (!pointerScalarFields.has(prop))
452
+ return null;
453
+ const direct = `static_cast<double>(event.${prop})`;
454
+ loweredArgs.push(eventArg(`gea_cpp_value(${direct})`, direct, 'number'));
455
+ continue;
456
+ }
457
+ // `item.field` — capture the field value at make_row time so the handler
458
+ // closes over a stable copy. Captured as gea_cpp_value so the store
459
+ // method's dynamic-call boundary accepts it uniformly.
460
+ const itemFieldMatch = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
461
+ if (itemFieldMatch && itemFieldMatch[1] === itemName) {
462
+ const fieldName = sanitizeCppIdentifier(itemFieldMatch[2]);
463
+ const itemField = field.itemFields.find((candidate) => sanitizeCppIdentifier(candidate.name) === fieldName);
464
+ if (!itemField)
465
+ return null;
466
+ // Unique across all handlers in the row (slotIndex) — two onClick handlers
467
+ // on sibling row elements both capturing item.id would otherwise both emit
468
+ // `__gea_cap_0_0` into the same make_row scope and conflict.
469
+ const captureName = `__gea_cap_${slotIndex}_${statementIndex}_${captureNames.length}`;
470
+ const direct = `${itemName}.${fieldName}`;
471
+ const valueType = shapeValueType(itemField.shape);
472
+ captures.push(` auto ${captureName} = ${direct};`);
473
+ captureNames.push(captureName);
474
+ loweredArgs.push(eventArg(`gea_cpp_key(${captureName})`, captureName, valueType));
475
+ continue;
476
+ }
477
+ return null;
478
+ }
479
+ const directMethod = storeMethodByReceiver(receiver, method, storeMethods);
480
+ const directArgs = directMethod ? directCallArguments(directMethod, loweredArgs) : null;
481
+ if (directMethod && directArgs && directMethod.storeClass === field.storeClass) {
482
+ return {
483
+ lines: [
484
+ `if (typed_store) {`,
485
+ ` (void)typed_store->${directMethod.methodName}(${directArgs.join(', ')});`,
486
+ `}`,
487
+ ],
488
+ usesTypedStore: true,
489
+ };
490
+ }
491
+ if (directMethod && directArgs && receiver !== 'this') {
492
+ const receiverExpr = `__gea_global_${sanitizeCppIdentifier(receiver)}()`;
493
+ if (directMethod.globalAccess === 'reference') {
494
+ return {
495
+ lines: [`(void)${receiverExpr}.${directMethod.methodName}(${directArgs.join(', ')});`],
496
+ usesTypedStore: false,
497
+ };
498
+ }
499
+ const storeLocal = `__gea_event_store_${slotIndex}_${statementIndex}`;
500
+ return {
501
+ lines: [
502
+ `auto ${storeLocal} = ${receiverExpr};`,
503
+ `if (${storeLocal}) {`,
504
+ ` (void)${storeLocal}->${directMethod.methodName}(${directArgs.join(', ')});`,
505
+ `}`,
506
+ ],
507
+ usesTypedStore: false,
508
+ };
509
+ }
510
+ const receiverExpr = receiver === 'this' ? 'store' : `__gea_global_${sanitizeCppIdentifier(receiver)}()`;
511
+ const methodVar = `__gea_method_${statementIndex}`;
512
+ // gea_cpp_key boxes a typed global cell for this dynamic lookup (identity
513
+ // for boxed receivers).
514
+ return { lines: [
515
+ `auto ${methodVar} = gea_cpp_key(gea_cpp_key(${receiverExpr}).record_get_literal(${cppString(method)}));`,
516
+ `if (gea::runtime::coerce::to_boolean(${methodVar})) (void)${methodVar}(${loweredArgs.map((arg) => arg.dynamic).join(', ')});`,
517
+ ], usesTypedStore: false };
518
+ }
519
+ export function parseExpressionObjectFields(expr) {
520
+ const text = stripOuterParens(expr.trim());
521
+ if (!text.startsWith('{') || !text.endsWith('}'))
522
+ return null;
523
+ const inner = text.slice(1, -1).trim();
524
+ if (!inner)
525
+ return [];
526
+ const fields = [];
527
+ for (const part of splitTopLevelComma(inner)) {
528
+ if (!part || part.startsWith('...'))
529
+ return null;
530
+ const colon = findTopLevelOperator(part, ':');
531
+ if (colon < 0)
532
+ return null;
533
+ const rawName = part.slice(0, colon).trim();
534
+ const name = objectKeyName(rawName);
535
+ if (!name)
536
+ return null;
537
+ fields.push({ name, expr: part.slice(colon + 1).trim() });
538
+ }
539
+ return fields;
540
+ }
541
+ export function constantExpression(name, constants) {
542
+ const constant = constants.get(name);
543
+ if (!constant)
544
+ return null;
545
+ if (constant.valueType === 'object-array')
546
+ return null;
547
+ if (constant.valueType === 'number') {
548
+ return { expr: `static_cast<double>(${constant.value})`, shape: { kind: 'literal', valueType: 'number' } };
549
+ }
550
+ if (constant.valueType === 'string') {
551
+ return { expr: `std::string(${cppString(constant.value)})`, shape: { kind: 'literal', valueType: 'string' } };
552
+ }
553
+ if (constant.valueType === 'boolean') {
554
+ return { expr: constant.value, shape: { kind: 'literal', valueType: 'boolean' } };
555
+ }
556
+ return { expr: 'gea_cpp_value::null_v()', shape: { kind: 'literal', valueType: 'null' } };
557
+ }
558
+ export function objectArrayConstant(name, constants) {
559
+ if (!name || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name.trim()))
560
+ return null;
561
+ const constant = constants.get(name.trim());
562
+ if (!constant || constant.valueType !== 'object-array' || !constant.items)
563
+ return null;
564
+ return constant.items;
565
+ }
566
+ function lowerRowStyleExpression(expr, itemName, field, constants, storeFields) {
567
+ const source = ts.createSourceFile('row-style.ts', `(${expr});`, ts.ScriptTarget.Latest, false);
568
+ const stmt = source.statements[0];
569
+ if (!stmt || !ts.isExpressionStatement(stmt))
570
+ return null;
571
+ return lowerRowExpressionNode(stmt.expression, itemName, field, constants, storeFields);
572
+ }
573
+ function lowerRowPxLengthStyleExpression(expr, propertyName, itemName, field, constants, storeFields) {
574
+ if (!isPxLengthStylePropertyName(propertyName))
575
+ return null;
576
+ const source = ts.createSourceFile('row-style.ts', `(${expr});`, ts.ScriptTarget.Latest, false);
577
+ const stmt = source.statements[0];
578
+ if (!stmt || !ts.isExpressionStatement(stmt))
579
+ return null;
580
+ const node = unwrapExpressionNode(stmt.expression);
581
+ if (!ts.isTemplateExpression(node))
582
+ return null;
583
+ if (node.head.text !== '' || node.templateSpans.length !== 1)
584
+ return null;
585
+ const span = node.templateSpans[0];
586
+ if (span.literal.text !== 'px')
587
+ return null;
588
+ const lowered = lowerRowExpressionNode(span.expression, itemName, field, constants, storeFields);
589
+ if (!lowered)
590
+ return null;
591
+ return {
592
+ expr: loweredRowAsNumber(lowered),
593
+ shape: { kind: 'literal', valueType: 'number' },
594
+ itemFields: lowered.itemFields,
595
+ storeFields: lowered.storeFields,
596
+ };
597
+ }
598
+ function lowerRowPercentLengthStyleExpression(expr, propertyName, itemName, field, constants, storeFields) {
599
+ if (!stylePercentPropertyEnumForPropertyName(propertyName))
600
+ return null;
601
+ const source = ts.createSourceFile('row-style.ts', `(${expr});`, ts.ScriptTarget.Latest, false);
602
+ const stmt = source.statements[0];
603
+ if (!stmt || !ts.isExpressionStatement(stmt))
604
+ return null;
605
+ const node = unwrapExpressionNode(stmt.expression);
606
+ if (!ts.isTemplateExpression(node))
607
+ return null;
608
+ if (node.head.text !== '' || node.templateSpans.length !== 1)
609
+ return null;
610
+ const span = node.templateSpans[0];
611
+ if (span.literal.text !== '%')
612
+ return null;
613
+ const lowered = lowerRowExpressionNode(span.expression, itemName, field, constants, storeFields);
614
+ if (!lowered)
615
+ return null;
616
+ return {
617
+ expr: loweredRowAsNumber(lowered),
618
+ shape: { kind: 'literal', valueType: 'number' },
619
+ itemFields: lowered.itemFields,
620
+ storeFields: lowered.storeFields,
621
+ styleUnit: 'percent',
622
+ };
623
+ }
624
+ function lowerRowRotateStyleExpression(expr, propertyName, itemName, field, constants, storeFields) {
625
+ if (!isRotateTransformPropertyName(propertyName))
626
+ return null;
627
+ const source = ts.createSourceFile('row-style.ts', `(${expr});`, ts.ScriptTarget.Latest, false);
628
+ const stmt = source.statements[0];
629
+ if (!stmt || !ts.isExpressionStatement(stmt))
630
+ return null;
631
+ const node = unwrapExpressionNode(stmt.expression);
632
+ if (!ts.isTemplateExpression(node))
633
+ return null;
634
+ const degrees = rotateDegreesTemplateExpression(node, propertyName);
635
+ if (!degrees)
636
+ return null;
637
+ const lowered = lowerRowExpressionNode(degrees, itemName, field, constants, storeFields);
638
+ if (!lowered)
639
+ return null;
640
+ return {
641
+ expr: loweredRowAsNumber(lowered),
642
+ shape: { kind: 'literal', valueType: 'number' },
643
+ itemFields: lowered.itemFields,
644
+ storeFields: lowered.storeFields,
645
+ };
646
+ }
647
+ function lowerRowOpaqueColorStyleExpression(expr, propertyName, itemName, field, constants, storeFields) {
648
+ if (!styleOpaqueColorTargetForPropertyName(propertyName))
649
+ return null;
650
+ const source = ts.createSourceFile('row-style.ts', `(${expr});`, ts.ScriptTarget.Latest, false);
651
+ const stmt = source.statements[0];
652
+ if (!stmt || !ts.isExpressionStatement(stmt))
653
+ return null;
654
+ return lowerRowOpaqueColorStyleExpressionNode(unwrapExpressionNode(stmt.expression), itemName, field, constants, storeFields);
655
+ }
656
+ function lowerRowOpaqueColorStyleExpressionNode(node, itemName, field, constants, storeFields) {
657
+ const literal = opaqueHexColorExpressionForNode(node, constants);
658
+ if (literal) {
659
+ return {
660
+ expr: literal,
661
+ shape: { kind: 'literal', valueType: 'number' },
662
+ itemFields: [],
663
+ storeFields: [],
664
+ styleUnit: 'color',
665
+ };
666
+ }
667
+ if (!ts.isConditionalExpression(node))
668
+ return null;
669
+ const test = lowerRowExpressionNode(node.condition, itemName, field, constants, storeFields);
670
+ const consequent = opaqueHexColorExpressionForNode(node.whenTrue, constants);
671
+ const alternate = opaqueHexColorExpressionForNode(node.whenFalse, constants);
672
+ if (!test || !consequent || !alternate)
673
+ return null;
674
+ return {
675
+ expr: `(${loweredRowAsBoolean(test)} ? ${consequent} : ${alternate})`,
676
+ shape: { kind: 'literal', valueType: 'number' },
677
+ itemFields: test.itemFields,
678
+ storeFields: test.storeFields,
679
+ styleUnit: 'color',
680
+ };
681
+ }
682
+ function lowerRowKeywordStyleExpression(expr, propertyName, itemName, field, constants, storeFields) {
683
+ if (!styleKeywordPropertiesForPropertyName(propertyName))
684
+ return null;
685
+ const source = ts.createSourceFile('row-style.ts', `(${expr});`, ts.ScriptTarget.Latest, false);
686
+ const stmt = source.statements[0];
687
+ if (!stmt || !ts.isExpressionStatement(stmt))
688
+ return null;
689
+ return lowerRowKeywordStyleExpressionNode(unwrapExpressionNode(stmt.expression), propertyName, itemName, field, constants, storeFields);
690
+ }
691
+ function lowerRowKeywordStyleExpressionNode(node, propertyName, itemName, field, constants, storeFields) {
692
+ const literal = keywordCommonValue(keywordEntriesForNode(propertyName, node, constants));
693
+ if (literal !== null) {
694
+ return {
695
+ expr: String(literal),
696
+ shape: { kind: 'literal', valueType: 'number' },
697
+ itemFields: [],
698
+ storeFields: [],
699
+ styleUnit: 'keyword',
700
+ };
701
+ }
702
+ if (!ts.isConditionalExpression(node))
703
+ return null;
704
+ const test = lowerRowExpressionNode(node.condition, itemName, field, constants, storeFields);
705
+ const consequent = keywordEntriesForNode(propertyName, node.whenTrue, constants);
706
+ const alternate = keywordEntriesForNode(propertyName, node.whenFalse, constants);
707
+ const consequentValue = keywordCommonValue(consequent);
708
+ const alternateValue = keywordCommonValue(alternate);
709
+ if (!test || consequentValue === null || alternateValue === null || !keywordEntriesCompatible(consequent, alternate))
710
+ return null;
711
+ return {
712
+ expr: `(${loweredRowAsBoolean(test)} ? ${consequentValue} : ${alternateValue})`,
713
+ shape: { kind: 'literal', valueType: 'number' },
714
+ itemFields: test.itemFields,
715
+ storeFields: test.storeFields,
716
+ styleUnit: 'keyword',
717
+ };
718
+ }
719
+ function unwrapExpressionNode(node) {
720
+ let current = node;
721
+ while (ts.isParenthesizedExpression(current) ||
722
+ ts.isAsExpression(current) ||
723
+ ts.isTypeAssertionExpression(current) ||
724
+ ts.isNonNullExpression(current) ||
725
+ ts.isSatisfiesExpression(current)) {
726
+ current = current.expression;
727
+ }
728
+ return current;
729
+ }
730
+ function lowerRowExpressionNode(node, itemName, field, constants, storeFields) {
731
+ if (ts.isParenthesizedExpression(node))
732
+ return lowerRowExpressionNode(node.expression, itemName, field, constants, storeFields);
733
+ if (ts.isAsExpression(node) ||
734
+ ts.isTypeAssertionExpression(node) ||
735
+ ts.isNonNullExpression(node) ||
736
+ ts.isSatisfiesExpression(node)) {
737
+ return lowerRowExpressionNode(node.expression, itemName, field, constants, storeFields);
738
+ }
739
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
740
+ return { expr: `std::string(${cppString(node.text)})`, shape: { kind: 'literal', valueType: 'string' }, itemFields: [], storeFields: [] };
741
+ }
742
+ // Template literal with substitutions inside a `.map()` row, e.g.
743
+ // `{`${row.ms} ms`}`. Without this case the slot lowered to null and was
744
+ // silently dropped (no setText emitted) — the row's text rendered empty. Lower
745
+ // to a std::string concatenation of head + coerced spans + tails; the leading
746
+ // std::string makes the `+` chain well-typed even when the head is empty.
747
+ if (ts.isTemplateExpression(node)) {
748
+ const itemFields = [];
749
+ const spanStoreFields = [];
750
+ const parts = [`std::string(${cppString(node.head.text)})`];
751
+ for (const span of node.templateSpans) {
752
+ const part = lowerRowExpressionNode(span.expression, itemName, field, constants, storeFields);
753
+ if (!part)
754
+ return null;
755
+ itemFields.push(...part.itemFields);
756
+ spanStoreFields.push(...part.storeFields);
757
+ parts.push(loweredRowAsString(part));
758
+ if (span.literal.text.length > 0)
759
+ parts.push(`std::string(${cppString(span.literal.text)})`);
760
+ }
761
+ return {
762
+ expr: `(${parts.join(' + ')})`,
763
+ shape: { kind: 'literal', valueType: 'string' },
764
+ itemFields: uniqueItemFieldNames(itemFields),
765
+ storeFields: uniqueStoreFields(spanStoreFields),
766
+ };
767
+ }
768
+ if (ts.isNumericLiteral(node)) {
769
+ return { expr: `static_cast<double>(${node.text})`, shape: { kind: 'literal', valueType: 'number' }, itemFields: [], storeFields: [] };
770
+ }
771
+ if (node.kind === ts.SyntaxKind.TrueKeyword)
772
+ return { expr: 'true', shape: { kind: 'literal', valueType: 'boolean' }, itemFields: [], storeFields: [] };
773
+ if (node.kind === ts.SyntaxKind.FalseKeyword)
774
+ return { expr: 'false', shape: { kind: 'literal', valueType: 'boolean' }, itemFields: [], storeFields: [] };
775
+ if (ts.isIdentifier(node)) {
776
+ const constant = constantExpression(node.text, constants);
777
+ if (constant)
778
+ return { ...constant, itemFields: [], storeFields: [] };
779
+ // SCREAMING_SNAKE_CASE module constants (e.g. BLOCK_SIZE) are assigned once
780
+ // at module init and emitted as in-scope C++ globals. The non-keyed path
781
+ // (attributeValueExpression) already references them directly; mirror that
782
+ // here so constant inline-style props on `.map`'d rows — e.g.
783
+ // `width: BLOCK_SIZE` in button-tetris — are emitted instead of dropped,
784
+ // which previously left mapped rows with no width/height.
785
+ if (isRuntimeNumericConstantIdentifier(node.text)) {
786
+ return {
787
+ expr: `static_cast<double>(${node.text})`,
788
+ shape: { kind: 'literal', valueType: 'number' },
789
+ itemFields: [],
790
+ storeFields: [],
791
+ };
792
+ }
793
+ return null;
794
+ }
795
+ if (ts.isPropertyAccessExpression(node)) {
796
+ if (!ts.isIdentifier(node.expression))
797
+ return null;
798
+ const receiver = node.expression.text;
799
+ if (receiver !== itemName) {
800
+ const storeField = storeFieldByReceiver(receiver, node.name.text, storeFields);
801
+ if (!storeField?.readerName || storeField.storeClass !== field.storeClass)
802
+ return null;
803
+ return {
804
+ expr: `${storeField.readerName}(store)`,
805
+ shape: shapeForStoreFieldPlan(storeField),
806
+ itemFields: [],
807
+ storeFields: [storeField],
808
+ };
809
+ }
810
+ const itemFieldName = sanitizeCppIdentifier(node.name.text);
811
+ const itemField = field.itemFields.find((candidate) => sanitizeCppIdentifier(candidate.name) === itemFieldName);
812
+ return {
813
+ expr: `${itemName}.${itemFieldName}`,
814
+ shape: valueShapeForStoreField(itemField),
815
+ itemFields: [itemFieldName],
816
+ storeFields: [],
817
+ };
818
+ }
819
+ if (ts.isPrefixUnaryExpression(node)) {
820
+ const operand = lowerRowExpressionNode(node.operand, itemName, field, constants, storeFields);
821
+ if (!operand)
822
+ return null;
823
+ if (node.operator === ts.SyntaxKind.MinusToken) {
824
+ return { expr: `(-${loweredRowAsNumber(operand)})`, shape: { kind: 'literal', valueType: 'number' }, itemFields: operand.itemFields, storeFields: operand.storeFields };
825
+ }
826
+ if (node.operator === ts.SyntaxKind.PlusToken) {
827
+ return { expr: `(+${loweredRowAsNumber(operand)})`, shape: { kind: 'literal', valueType: 'number' }, itemFields: operand.itemFields, storeFields: operand.storeFields };
828
+ }
829
+ if (node.operator === ts.SyntaxKind.ExclamationToken) {
830
+ return { expr: `(!${loweredRowAsBoolean(operand)})`, shape: { kind: 'literal', valueType: 'boolean' }, itemFields: operand.itemFields, storeFields: operand.storeFields };
831
+ }
832
+ return null;
833
+ }
834
+ if (ts.isConditionalExpression(node)) {
835
+ const test = lowerRowExpressionNode(node.condition, itemName, field, constants, storeFields);
836
+ const consequent = lowerRowExpressionNode(node.whenTrue, itemName, field, constants, storeFields);
837
+ const alternate = lowerRowExpressionNode(node.whenFalse, itemName, field, constants, storeFields);
838
+ if (!test || !consequent || !alternate)
839
+ return null;
840
+ const kind = resultKindFor(consequent, alternate);
841
+ return {
842
+ expr: `(${loweredRowAsBoolean(test)} ? ${loweredRowAsKind(consequent, kind)} : ${loweredRowAsKind(alternate, kind)})`,
843
+ shape: { kind: 'literal', valueType: kind },
844
+ itemFields: uniqueItemFieldNames([...test.itemFields, ...consequent.itemFields, ...alternate.itemFields]),
845
+ storeFields: uniqueStoreFields([...test.storeFields, ...consequent.storeFields, ...alternate.storeFields]),
846
+ };
847
+ }
848
+ if (ts.isBinaryExpression(node)) {
849
+ return lowerRowBinaryExpression(node, itemName, field, constants, storeFields);
850
+ }
851
+ if (ts.isCallExpression(node)) {
852
+ return lowerRowCallExpression(node, itemName, field, constants, storeFields);
853
+ }
854
+ return null;
855
+ }
856
+ function lowerRowBinaryExpression(node, itemName, field, constants, storeFields) {
857
+ const op = node.operatorToken.kind;
858
+ const left = lowerRowExpressionNode(node.left, itemName, field, constants, storeFields);
859
+ const right = lowerRowExpressionNode(node.right, itemName, field, constants, storeFields);
860
+ if (!left || !right)
861
+ return null;
862
+ const itemFields = uniqueItemFieldNames([...left.itemFields, ...right.itemFields]);
863
+ const deps = uniqueStoreFields([...left.storeFields, ...right.storeFields]);
864
+ const boolean = { kind: 'literal', valueType: 'boolean' };
865
+ const number = { kind: 'literal', valueType: 'number' };
866
+ const string = { kind: 'literal', valueType: 'string' };
867
+ switch (op) {
868
+ case ts.SyntaxKind.EqualsEqualsEqualsToken:
869
+ return { expr: loweredRowEqualityExpression(left, right, '===', false), shape: boolean, itemFields, storeFields: deps };
870
+ case ts.SyntaxKind.EqualsEqualsToken:
871
+ return { expr: loweredRowEqualityExpression(left, right, '==', false), shape: boolean, itemFields, storeFields: deps };
872
+ case ts.SyntaxKind.ExclamationEqualsEqualsToken:
873
+ return { expr: loweredRowEqualityExpression(left, right, '===', true), shape: boolean, itemFields, storeFields: deps };
874
+ case ts.SyntaxKind.ExclamationEqualsToken:
875
+ return { expr: loweredRowEqualityExpression(left, right, '==', true), shape: boolean, itemFields, storeFields: deps };
876
+ case ts.SyntaxKind.LessThanToken:
877
+ return { expr: `(${loweredRowAsNumber(left)} < ${loweredRowAsNumber(right)})`, shape: boolean, itemFields, storeFields: deps };
878
+ case ts.SyntaxKind.LessThanEqualsToken:
879
+ return { expr: `(${loweredRowAsNumber(left)} <= ${loweredRowAsNumber(right)})`, shape: boolean, itemFields, storeFields: deps };
880
+ case ts.SyntaxKind.GreaterThanToken:
881
+ return { expr: `(${loweredRowAsNumber(left)} > ${loweredRowAsNumber(right)})`, shape: boolean, itemFields, storeFields: deps };
882
+ case ts.SyntaxKind.GreaterThanEqualsToken:
883
+ return { expr: `(${loweredRowAsNumber(left)} >= ${loweredRowAsNumber(right)})`, shape: boolean, itemFields, storeFields: deps };
884
+ case ts.SyntaxKind.AmpersandAmpersandToken:
885
+ return { expr: `(${loweredRowAsBoolean(left)} && ${loweredRowAsBoolean(right)})`, shape: boolean, itemFields, storeFields: deps };
886
+ case ts.SyntaxKind.BarBarToken:
887
+ return { expr: `(${loweredRowAsBoolean(left)} || ${loweredRowAsBoolean(right)})`, shape: boolean, itemFields, storeFields: deps };
888
+ case ts.SyntaxKind.PlusToken: {
889
+ const leftIsString = left.shape?.kind === 'literal' && left.shape.valueType === 'string';
890
+ const rightIsString = right.shape?.kind === 'literal' && right.shape.valueType === 'string';
891
+ if (leftIsString || rightIsString) {
892
+ return { expr: `(${loweredRowAsString(left)} + ${loweredRowAsString(right)})`, shape: string, itemFields, storeFields: deps };
893
+ }
894
+ return { expr: `(${loweredRowAsNumber(left)} + ${loweredRowAsNumber(right)})`, shape: number, itemFields, storeFields: deps };
895
+ }
896
+ case ts.SyntaxKind.MinusToken:
897
+ return { expr: `(${loweredRowAsNumber(left)} - ${loweredRowAsNumber(right)})`, shape: number, itemFields, storeFields: deps };
898
+ case ts.SyntaxKind.AsteriskToken:
899
+ return { expr: `(${loweredRowAsNumber(left)} * ${loweredRowAsNumber(right)})`, shape: number, itemFields, storeFields: deps };
900
+ case ts.SyntaxKind.SlashToken:
901
+ return { expr: `(${loweredRowAsNumber(left)} / ${loweredRowAsNumber(right)})`, shape: number, itemFields, storeFields: deps };
902
+ case ts.SyntaxKind.PercentToken:
903
+ return { expr: `std::fmod(${loweredRowAsNumber(left)}, ${loweredRowAsNumber(right)})`, shape: number, itemFields, storeFields: deps };
904
+ default:
905
+ return null;
906
+ }
907
+ }
908
+ function loweredRowEqualityExpression(left, right, mode, negate) {
909
+ const leftKind = primitiveLiteralKind(left);
910
+ const rightKind = primitiveLiteralKind(right);
911
+ if (leftKind && leftKind === rightKind) {
912
+ const op = negate ? '!=' : '==';
913
+ return `(${loweredRowAsKind(left, leftKind)} ${op} ${loweredRowAsKind(right, rightKind)})`;
914
+ }
915
+ const fn = mode === '===' ? 'gea_cpp_strict_equals' : 'gea_cpp_loose_equals';
916
+ const expr = `${fn}(gea_cpp_key(${left.expr}), gea_cpp_key(${right.expr}))`;
917
+ return negate ? `(!${expr})` : expr;
918
+ }
919
+ function primitiveLiteralKind(lowered) {
920
+ if (lowered.shape?.kind !== 'literal')
921
+ return null;
922
+ if (lowered.shape.valueType === 'string' || lowered.shape.valueType === 'number' || lowered.shape.valueType === 'boolean') {
923
+ return lowered.shape.valueType;
924
+ }
925
+ return null;
926
+ }
927
+ function lowerRowCallExpression(node, itemName, field, constants, storeFields) {
928
+ if (!ts.isPropertyAccessExpression(node.expression))
929
+ return null;
930
+ if (!ts.isIdentifier(node.expression.expression) || node.expression.expression.text !== 'Math')
931
+ return null;
932
+ const method = node.expression.name.text;
933
+ const args = node.arguments.map((arg) => lowerRowExpressionNode(arg, itemName, field, constants, storeFields));
934
+ if (args.some((arg) => arg === null))
935
+ return null;
936
+ const lowered = args;
937
+ const itemFields = uniqueItemFieldNames(lowered.flatMap((arg) => arg.itemFields));
938
+ const deps = uniqueStoreFields(lowered.flatMap((arg) => arg.storeFields));
939
+ const number = { kind: 'literal', valueType: 'number' };
940
+ if ((method === 'abs' || method === 'floor' || method === 'ceil' || method === 'round') && lowered.length === 1) {
941
+ const fn = method === 'abs' ? 'std::abs' : method === 'floor' ? 'std::floor' : method === 'ceil' ? 'std::ceil' : 'std::round';
942
+ return { expr: `${fn}(${loweredRowAsNumber(lowered[0])})`, shape: number, itemFields, storeFields: deps };
943
+ }
944
+ if ((method === 'min' || method === 'max') && lowered.length >= 2) {
945
+ const fn = method === 'min' ? 'std::min' : 'std::max';
946
+ let expr = loweredRowAsNumber(lowered[0]);
947
+ for (let i = 1; i < lowered.length; i += 1)
948
+ expr = `${fn}(${expr}, ${loweredRowAsNumber(lowered[i])})`;
949
+ return { expr, shape: number, itemFields, storeFields: deps };
950
+ }
951
+ return null;
952
+ }
953
+ function loweredRowAsNumber(lowered) {
954
+ if (lowered.shape?.kind === 'literal' && lowered.shape.valueType === 'number')
955
+ return lowered.expr;
956
+ return `gea::runtime::coerce::to_number(gea_cpp_key(${lowered.expr}))`;
957
+ }
958
+ function loweredRowAsBoolean(lowered) {
959
+ if (lowered.shape?.kind === 'literal' && lowered.shape.valueType === 'boolean')
960
+ return lowered.expr;
961
+ if (lowered.shape?.kind === 'literal' && lowered.shape.valueType === 'number')
962
+ return `(${lowered.expr} != static_cast<double>(0))`;
963
+ if (lowered.shape?.kind === 'literal' && lowered.shape.valueType === 'string')
964
+ return `(!${lowered.expr}.empty())`;
965
+ return `gea::runtime::coerce::to_boolean(gea_cpp_key(${lowered.expr}))`;
966
+ }
967
+ function loweredRowAsString(lowered) {
968
+ if (lowered.shape?.kind === 'literal' && lowered.shape.valueType === 'string')
969
+ return lowered.expr;
970
+ if (lowered.shape?.kind === 'literal' && lowered.shape.valueType === 'number')
971
+ return `gea_cpp_to_string(${lowered.expr})`;
972
+ if (lowered.shape?.kind === 'literal' && lowered.shape.valueType === 'boolean')
973
+ return `gea_cpp_to_string(${lowered.expr})`;
974
+ return `gea_cpp_to_string(gea_cpp_key(${lowered.expr}))`;
975
+ }
976
+ function loweredRowAsKind(lowered, kind) {
977
+ if (kind === 'string')
978
+ return loweredRowAsString(lowered);
979
+ if (kind === 'number')
980
+ return loweredRowAsNumber(lowered);
981
+ return loweredRowAsBoolean(lowered);
982
+ }
983
+ function resultKindFor(a, b) {
984
+ const aType = a.shape?.kind === 'literal' ? a.shape.valueType : null;
985
+ const bType = b.shape?.kind === 'literal' ? b.shape.valueType : null;
986
+ if (aType === 'string' || bType === 'string')
987
+ return 'string';
988
+ if (aType === 'number' || bType === 'number')
989
+ return 'number';
990
+ if (aType === 'boolean' && bType === 'boolean')
991
+ return 'boolean';
992
+ return 'string';
993
+ }
994
+ // Image globals are native `gea::host::GeaEmbeddedImage&` accessors (loadImage
995
+ // returns the concrete struct), so the slot id is a plain `.id` field read — no
996
+ // gea_cpp_value boxing. mountedRendererGlobalAccessorDeclarations keys off the
997
+ // `().id` shape to forward-declare these with the image type.
998
+ function imageIdApplyLine(varName, imageGlobal) {
999
+ return ` gea::embedded::ui::ImageElement(${varName}.id()).imageId(__gea_global_${sanitizeCppIdentifier(imageGlobal)}().id);`;
1000
+ }
1001
+ function imageFitValue(fit) {
1002
+ switch (fit) {
1003
+ case 'fill':
1004
+ return 0;
1005
+ case 'contain':
1006
+ return 1;
1007
+ case 'cover':
1008
+ return 2;
1009
+ case 'none':
1010
+ return 3;
1011
+ case 'scale-down':
1012
+ return 4;
1013
+ default:
1014
+ return null;
1015
+ }
1016
+ }
1017
+ function imageFitApplyLines(varName, fit) {
1018
+ const value = imageFitValue(fit);
1019
+ if (value === null)
1020
+ return [` ${varName}.setAttribute("fit", ${cppString(fit)});`];
1021
+ return [` gea::embedded::ui::ImageElement(${varName}.id()).fit(${value});`];
1022
+ }
1023
+ // Keep identical to canonicalAssetPath() / assetSymbol() in
1024
+ // scripts/generate-gea-embedded-assets.mjs.
1025
+ function canonicalAssetPath(relPath) {
1026
+ const normalized = relPath.startsWith('/') ? relPath.slice(1) : relPath;
1027
+ return normalized.startsWith('public/') ? normalized.slice('public/'.length) : normalized;
1028
+ }
1029
+ function assetSymbol(relPath) {
1030
+ return `gea_asset_${canonicalAssetPath(relPath).replace(/[^A-Za-z0-9]/g, '_')}`;
1031
+ }
1032
+ // `<img src="path">` (string-literal path) → decode the build-embedded asset
1033
+ // bytes into the image slot. The codegen references the generated
1034
+ // `gea_asset_<path>` symbol directly; that reference is what keeps the asset
1035
+ // object in the link (a static-init registry gets dropped from ESP-IDF's
1036
+ // archive link). The symbol is `extern "C"` (defined in
1037
+ // scripts/generate-gea-embedded-assets.mjs) and forward-declared at namespace
1038
+ // scope by mountedRendererAssetDeclarations() in cpp-ir.ts — `extern "C"`
1039
+ // makes it resolve identically whether the enclosing `gea_ir` is global or
1040
+ // (in an isolated multi-program link) wrapped in an anonymous namespace. A plain C++
1041
+ // block-scope `extern` here would instead bind to `(anonymous
1042
+ // namespace)::gea_ir::gea_asset_<path>` and fail to link.
1043
+ export function imageSrcAssetIdExpression(relPath) {
1044
+ const sym = assetSymbol(relPath);
1045
+ return `gea::host::image.loadBytesPtr(${sym}, static_cast<std::size_t>(${sym}_len))`;
1046
+ }
1047
+ function imageSrcAssetLines(varName, relPath) {
1048
+ return [
1049
+ ` gea::embedded::ui::ImageElement(${varName}.id()).imageId(static_cast<int>(${imageSrcAssetIdExpression(relPath)}));`,
1050
+ ];
1051
+ }
1052
+ export function unique(values) {
1053
+ return values.length === 1 ? values[0] : null;
1054
+ }
1055
+ export function fieldReadPlanForLoweredSlots(stateType, fields) {
1056
+ const reads = [];
1057
+ for (const field of fields) {
1058
+ if (!field.readerName)
1059
+ return null;
1060
+ reads.push({
1061
+ fieldName: field.fieldName,
1062
+ fieldType: field.fieldType,
1063
+ localName: storeFieldLocalName(field.fieldName),
1064
+ readerName: field.readerName,
1065
+ });
1066
+ }
1067
+ return reads.length > 0 ? { stateType, fields: reads } : null;
1068
+ }
1069
+ export function fieldReadLines(plan, storeExpression = 'store') {
1070
+ return plan.fields.map((field) => `const auto ${field.localName} = ${field.readerName}(${storeExpression});`);
1071
+ }
1072
+ function lowerStyleSlots(slots, storeFields, constants) {
1073
+ const stateTypes = new Set();
1074
+ const deps = [];
1075
+ const fields = [];
1076
+ const staticLines = [];
1077
+ const lines = [];
1078
+ for (const slot of slots) {
1079
+ if (slot.kind !== 'style' || !slot.exprObjectFields)
1080
+ continue;
1081
+ // Reactive style slots are applied to `root` below; a non-empty walk
1082
+ // means the slot styles a DESCENDANT element this renderer never builds.
1083
+ // Bail so the component falls off this root-only fast path instead of
1084
+ // restyling the wrong node (the template renderer handles nested slots).
1085
+ if (slot.walk.length !== 0)
1086
+ return null;
1087
+ for (const field of slot.exprObjectFields) {
1088
+ const propertyName = cssPropertyName(field.name);
1089
+ const staticFieldLines = staticRootStyleApplyLines('root', propertyName, field.expr, constants);
1090
+ if (staticFieldLines) {
1091
+ staticLines.push(...staticFieldLines);
1092
+ continue;
1093
+ }
1094
+ const lowered = lowerStoreRotateStyleExpression(field, propertyName, storeFields) ??
1095
+ lowerStorePxLengthStyleExpression(field, propertyName, storeFields) ??
1096
+ lowerStorePercentLengthStyleExpression(field, propertyName, storeFields) ??
1097
+ lowerStoreOpaqueColorStyleExpression(field, propertyName, storeFields, constants) ??
1098
+ lowerStoreKeywordStyleExpression(field, propertyName, storeFields, constants) ??
1099
+ lowerStoreExpression(field, storeFields);
1100
+ if (!lowered)
1101
+ return null;
1102
+ stateTypes.add(lowered.store.stateType);
1103
+ deps.push(lowered.store.fieldName);
1104
+ fields.push(lowered.store);
1105
+ lines.push(...styleApplyLines('root', propertyName, lowered.expr, lowered.shape ?? shapeForStoreFieldPlan(lowered.store), lowered.styleUnit));
1106
+ }
1107
+ }
1108
+ if (stateTypes.size !== 1 || lines.length === 0)
1109
+ return null;
1110
+ return { stateType: [...stateTypes][0], deps, fields: uniqueStoreFields(fields), staticLines, lines };
1111
+ }
1112
+ export function attributeSlotLines(varName, slot, constants = new Map()) {
1113
+ const attrName = slotAttrName(slot);
1114
+ if (!attrName || slot.expr === undefined)
1115
+ return null;
1116
+ const number = numericLiteralValue(slot.expr);
1117
+ if (attrName === 'pressId')
1118
+ return number === null ? null : [` ${varName}.setPressId(${number});`];
1119
+ if (attrName === 'pressValue')
1120
+ return number === null ? null : [` ${varName}.setPressValue(${number});`];
1121
+ if (attrName === 'src') {
1122
+ const imageGlobal = simpleIdentifierValue(slot.expr);
1123
+ if (imageGlobal) {
1124
+ return [imageIdApplyLine(varName, imageGlobal)];
1125
+ }
1126
+ // `<img src="face.png">` — a string-literal path decodes a build-embedded
1127
+ // asset straight into an image slot. No byte array in the bundle; the bytes
1128
+ // are `.rodata` in the app binary. See generate-gea-embedded-assets.mjs.
1129
+ const literalPath = stringLiteralValue(slot.expr);
1130
+ if (literalPath !== null) {
1131
+ return imageSrcAssetLines(varName, literalPath);
1132
+ }
1133
+ }
1134
+ if (attrName === 'fit') {
1135
+ const literalFit = stringLiteralValue(slot.expr);
1136
+ if (literalFit !== null)
1137
+ return imageFitApplyLines(varName, literalFit);
1138
+ }
1139
+ const value = attributeValueExpression(slot.expr, constants);
1140
+ if (!value)
1141
+ return null;
1142
+ return [` ${varName}.setAttribute(${cppString(attrName)}, ${value});`];
1143
+ }
1144
+ function lowerStaticRootStyle(varName, slot, constants) {
1145
+ if (!isStaticRootStyleSlot(slot, constants) || !slot.exprObjectFields)
1146
+ return null;
1147
+ const lines = [];
1148
+ for (const field of slot.exprObjectFields) {
1149
+ const propertyName = cssPropertyName(field.name);
1150
+ const lowered = staticRootStyleApplyLines(varName, propertyName, field.expr, constants);
1151
+ if (!lowered)
1152
+ return null;
1153
+ lines.push(...lowered.map((line) => ` ${line}`));
1154
+ }
1155
+ return lines;
1156
+ }
1157
+ function staticRootStyleApplyLines(varName, propertyName, expr, constants) {
1158
+ const number = staticRootStyleNumberExpression(expr, constants);
1159
+ if (number !== null) {
1160
+ const direct = directNumberStyleApplyLine(varName, propertyName, number);
1161
+ return [
1162
+ direct ??
1163
+ `gea::embedded::ui::StyleSheet::instance().applyNumberProperty(${varName}, ${stylePropertyArgument(propertyName)}, static_cast<double>(${number}));`,
1164
+ ];
1165
+ }
1166
+ const string = staticRootStyleStringValue(expr, constants);
1167
+ if (string !== null) {
1168
+ const direct = directStringStyleApplyLines(varName, propertyName, string);
1169
+ return direct ?? [
1170
+ `gea::embedded::ui::StyleSheet::instance().applyProperty(${varName}, ${cppString(propertyName)}, std::string(${cppString(string)}));`,
1171
+ ];
1172
+ }
1173
+ return null;
1174
+ }
1175
+ function isStaticRootStyleSlot(slot, constants) {
1176
+ if (slot.kind !== 'style' || slot.walk.length !== 0 || !slot.exprObjectFields || slot.exprObjectFields.length === 0)
1177
+ return false;
1178
+ return slot.exprObjectFields.every((field) => staticRootStyleNumberExpression(field.expr, constants) !== null ||
1179
+ staticRootStyleStringValue(field.expr, constants) !== null);
1180
+ }
1181
+ function staticRootStyleNumberExpression(expr, constants) {
1182
+ const text = stripOuterParens(expr.trim());
1183
+ const literal = numericLiteralValue(text);
1184
+ if (literal !== null)
1185
+ return literal;
1186
+ const ident = simpleIdentifierValue(text);
1187
+ const constant = ident ? constants.get(ident) : null;
1188
+ return constant?.valueType === 'number' ? constant.value : null;
1189
+ }
1190
+ function staticRootStyleStringValue(expr, constants) {
1191
+ const text = stripOuterParens(expr.trim());
1192
+ const literal = stringLiteralValue(text);
1193
+ if (literal !== null)
1194
+ return literal;
1195
+ const ident = simpleIdentifierValue(text);
1196
+ const constant = ident ? constants.get(ident) : null;
1197
+ return constant?.valueType === 'string' ? constant.value : null;
1198
+ }
1199
+ function lowerRootEvent(varName, slot, storeFields = [], storeMethods = [], fieldAccess, rootTag, constants = new Map(), disposerVar) {
1200
+ const attrName = slotAttrName(slot);
1201
+ const eventType = attrName ? eventTypeFromAttr(attrName) : null;
1202
+ const handler = lowerEventHandler(slot.expr, eventType, storeFields, storeMethods, fieldAccess, constants);
1203
+ if (!eventType || !handler)
1204
+ return null;
1205
+ const hoisted = hoistDirectRootEventStores(handler, varName, slot.index);
1206
+ // Document-level events have no element target. `rotary` (the encoder dial) is
1207
+ // always document-level. `keydown` is document-level only when we know it's
1208
+ // bound on a non-<input> element (an <input> keeps its per-node keydown
1209
+ // listener; when the tag is unknown — e.g. a nested child — we conservatively
1210
+ // keep keydown per-node). Document-level handlers register directly on
1211
+ // `document` (no body delegation, no containsNode/currentTarget bookkeeping)
1212
+ // and the runtime dispatches them off-tree.
1213
+ const isDocumentLevel = eventType === 'rotary' ||
1214
+ (eventType === 'keydown' && rootTag !== undefined && rootTag.toLowerCase() !== 'input');
1215
+ if (isDocumentLevel) {
1216
+ const docCaptures = [
1217
+ ...(hoisted.handler.some((line) => new RegExp(`\\b${varName}\\b`).test(line)) ? [varName] : []),
1218
+ ...hoisted.captures,
1219
+ ...(hoisted.handler.some((line) => /\bstore\b/.test(line)) ? ['store'] : []),
1220
+ ].join(', ');
1221
+ return [
1222
+ ...hoisted.setup.map((line) => ` ${line}`),
1223
+ ` gea::embedded::ui::Document::instance().addEventListener(${cppString(eventType)}, [${docCaptures}](gea::framework::events::PointerEvent &event) mutable {`,
1224
+ ...hoisted.handler.map((line) => ` ${line}`),
1225
+ ' });',
1226
+ ];
1227
+ }
1228
+ const captureList = [
1229
+ varName,
1230
+ ...hoisted.captures,
1231
+ ...(hoisted.handler.some((line) => /\bstore\b/.test(line)) ? ['store'] : []),
1232
+ ].join(', ');
1233
+ const listenerToken = `__gea_event_listener_${sanitizeCppIdentifier(varName)}_${slot.index}`;
1234
+ const lines = [
1235
+ ...hoisted.setup.map((line) => ` ${line}`),
1236
+ ` auto ${listenerToken} = gea::embedded::ui::Document::instance().body().addEventListener(${cppString(eventType)}, [${captureList}](gea::framework::events::PointerEvent &event) mutable {`,
1237
+ ` if (!gea::embedded::ui::Tree::instance().containsNode(${varName}.id(), event.targetId)) return;`,
1238
+ ' const auto __gea_prev_current_target = event.currentTarget;',
1239
+ ' const auto __gea_prev_current_target_id = event.currentTargetId;',
1240
+ ' const auto __gea_prev_event_phase = event.eventPhase;',
1241
+ ` event.currentTarget = gea::framework::events::EventTarget(${varName}.id());`,
1242
+ ` event.currentTargetId = ${varName}.id();`,
1243
+ ` event.eventPhase = event.targetId == ${varName}.id() ? gea::framework::events::EventPhase::AtTarget : gea::framework::events::EventPhase::Bubbling;`,
1244
+ ...hoisted.handler.map((line) => ` ${line}`),
1245
+ ' event.currentTarget = __gea_prev_current_target;',
1246
+ ' event.currentTargetId = __gea_prev_current_target_id;',
1247
+ ' event.eventPhase = __gea_prev_event_phase;',
1248
+ ' });',
1249
+ ];
1250
+ if (disposerVar) {
1251
+ lines.push(` if (${disposerVar}) {`);
1252
+ lines.push(` ${disposerVar}->add([${listenerToken}]() -> void {`);
1253
+ lines.push(` gea::embedded::ui::Document::instance().body().removeEventListener(${cppString(eventType)}, ${listenerToken});`);
1254
+ lines.push(' });');
1255
+ lines.push(' }');
1256
+ }
1257
+ return lines;
1258
+ }
1259
+ function hoistDirectRootEventStores(handler, varName, slotIndex) {
1260
+ const captures = [];
1261
+ const setup = [];
1262
+ const replacements = new Map();
1263
+ // The hoisted capture lands at the enclosing mount-function scope alongside
1264
+ // every other event handler in the same component. `slotIndex` is reused
1265
+ // across elements (each element's event slots restart their numbering), so
1266
+ // it alone is not unique within the function — two handlers on different
1267
+ // elements can share a slotIndex and collide (redefinition). `varName` is
1268
+ // the per-element node variable (`__gea_node_N`/`root`), unique within the
1269
+ // function, so prefixing with it makes the capture name unique per emission
1270
+ // site while staying deterministic across builds.
1271
+ const scopePrefix = sanitizeCppIdentifier(varName);
1272
+ const rewritten = handler.map((line) => {
1273
+ const match = line.match(/^(\s*)if \(auto ([A-Za-z_][A-Za-z0-9_]*) = gea_cpp_value_as_shared_ptr<([^>]+)>\((.+)\)\) \{$/);
1274
+ if (match) {
1275
+ const [, indent, localName, storeClass, receiverExpr] = match;
1276
+ const captureName = `__gea_event_store_${scopePrefix}_${slotIndex}_${captures.length}`;
1277
+ captures.push(captureName);
1278
+ setup.push(`auto ${captureName} = gea_cpp_value_as_shared_ptr<${storeClass}>(${receiverExpr});`);
1279
+ replacements.set(localName, captureName);
1280
+ return `${indent}if (${captureName}) {`;
1281
+ }
1282
+ let next = line;
1283
+ for (const [from, to] of replacements) {
1284
+ next = next.replace(new RegExp(`\\b${from}\\b`, 'g'), to);
1285
+ }
1286
+ return next;
1287
+ });
1288
+ return { captures, handler: rewritten, setup };
1289
+ }
1290
+ function lowerEventHandler(expr, eventType, storeFields, storeMethods, fieldAccess, constants = new Map()) {
1291
+ if (!expr || !eventType)
1292
+ return null;
1293
+ const arrow = parseArrowFunction(expr);
1294
+ if (!arrow)
1295
+ return null;
1296
+ const lines = [];
1297
+ for (let index = 0; index < arrow.body.length; index += 1) {
1298
+ const lowered = lowerEventStatement(arrow.body[index], arrow.params, eventType, index, storeFields, storeMethods, fieldAccess, constants);
1299
+ if (!lowered)
1300
+ return null;
1301
+ lines.push(...lowered);
1302
+ }
1303
+ return lines.length > 0 ? lines : null;
1304
+ }
1305
+ function lowerEventStatement(statement, params, eventType, statementIndex, storeFields, storeMethods, fieldAccess, constants = new Map()) {
1306
+ const guarded = statement.match(/^if\s*\(([\s\S]+?)\)\s*([\s\S]+)$/);
1307
+ if (guarded) {
1308
+ const condition = lowerEventCondition(guarded[1].trim(), params);
1309
+ const consequent = guarded[2].trim().replace(/;$/, '');
1310
+ const body = condition ? lowerEventStatement(consequent, params, eventType, statementIndex, storeFields, storeMethods, fieldAccess, constants) : null;
1311
+ if (!condition || !body || body.length === 0)
1312
+ return null;
1313
+ return [`if (${condition}) {`, ...body.map((line) => ` ${line}`), '}'];
1314
+ }
1315
+ const freeCall = statement.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\((.*)\)$/s);
1316
+ if (freeCall) {
1317
+ const [, fnName, rawArgs] = freeCall;
1318
+ const args = splitTopLevelComma(rawArgs).filter((arg) => arg !== '');
1319
+ const loweredArgs = [];
1320
+ for (const arg of args) {
1321
+ const lowered = lowerEventArgument(arg, params, eventType, storeFields, constants);
1322
+ if (!lowered)
1323
+ return null;
1324
+ loweredArgs.push(lowered);
1325
+ }
1326
+ return [`(void)fn_${sanitizeCppIdentifier(fnName)}(${loweredArgs.map((arg) => arg.direct).join(', ')});`];
1327
+ }
1328
+ const call = statement.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.([A-Za-z_$][A-Za-z0-9_$]*)\((.*)\)$/s);
1329
+ if (!call)
1330
+ return null;
1331
+ const [, receiver, method, rawArgs] = call;
1332
+ const args = splitTopLevelComma(rawArgs).filter((arg) => arg !== '');
1333
+ if (params.includes(receiver) && (method === 'preventDefault' || method === 'stopPropagation')) {
1334
+ if (args.length > 0)
1335
+ return null;
1336
+ return [`event.${method}();`];
1337
+ }
1338
+ if (params.includes(receiver))
1339
+ return null;
1340
+ const loweredArgs = [];
1341
+ for (const arg of args) {
1342
+ const lowered = lowerEventArgument(arg, params, eventType, storeFields, constants);
1343
+ if (!lowered)
1344
+ return null;
1345
+ loweredArgs.push(lowered);
1346
+ }
1347
+ const directMethod = storeMethodByReceiver(receiver, method, storeMethods);
1348
+ const directArgs = directMethod ? directCallArguments(directMethod, loweredArgs) : null;
1349
+ if (directMethod && directArgs) {
1350
+ // TypedSelf self-store: `store` IS the typed instance — call directly, no
1351
+ // gea_cpp_value unbox.
1352
+ if (fieldAccess?.typed && receiver === 'this') {
1353
+ return [`(void)${fieldAccess.callOwnMethod(directMethod.methodName, directArgs)};`];
1354
+ }
1355
+ const receiverExpr = receiver === 'this' ? 'store' : `__gea_global_${sanitizeCppIdentifier(receiver)}()`;
1356
+ // Typed global cells: Store singletons return shared_ptr; ordinary
1357
+ // exported singleton classes return references. Call both directly and
1358
+ // never box the receiver into gea_cpp_value.
1359
+ if (receiver !== 'this' && directMethod.globalAccess === 'reference') {
1360
+ return [`(void)${receiverExpr}.${directMethod.methodName}(${directArgs.join(', ')});`];
1361
+ }
1362
+ if (receiver !== 'this' && (directMethod.globalAccess === 'shared_ptr' || storeGlobalIsTyped(receiver, storeFields))) {
1363
+ return [`if (${receiverExpr}) (void)${receiverExpr}->${directMethod.methodName}(${directArgs.join(', ')});`];
1364
+ }
1365
+ const storeVar = `__gea_store_${statementIndex}`;
1366
+ return [
1367
+ `if (auto ${storeVar} = gea_cpp_value_as_shared_ptr<${directMethod.storeClass}>(${receiverExpr})) {`,
1368
+ ` (void)${storeVar}->${directMethod.methodName}(${directArgs.join(', ')});`,
1369
+ `}`,
1370
+ ];
1371
+ }
1372
+ const callArgs = loweredArgs.map((arg) => arg.dynamic).join(', ');
1373
+ if ((receiver === 'Apps' || receiver === 'apps') && method === 'launch' && loweredArgs.length === 1) {
1374
+ return [`(void)gea::host::apps.launch(gea_cpp_to_string(${loweredArgs[0].dynamic}));`];
1375
+ }
1376
+ const methodVar = `__gea_method_${statementIndex}`;
1377
+ // Resolve the actual receiver rather than blindly using the component's
1378
+ // `store` parameter. The previous implementation always looked the method
1379
+ // up on `store`, which silently worked only when the receiver happened to
1380
+ // match the inferred store (e.g. `launcher.tick()` in a component whose
1381
+ // refs already pulled in the launcher store). For multi-store components
1382
+ // — e.g. App's touch handlers calling `Settings.handleSwipe*()` while its
1383
+ // children refer to `launcher` — that ignored-receiver behaviour calls the
1384
+ // wrong store at runtime. Using `__gea_global_<receiver>()` resolves the
1385
+ // call to the real global, so components can import and call any number of
1386
+ // stores without being constrained to a single "event store". `this.method`
1387
+ // (class-component self calls) still routes through `store` since that's
1388
+ // the legacy contract the class lowering relies on.
1389
+ // TypedSelf self-store: `store` is the typed instance (no record_get_literal).
1390
+ if (fieldAccess?.typed && receiver === 'this') {
1391
+ return [`(void)${fieldAccess.callOwnMethod(method, loweredArgs.map((arg) => arg.direct))};`];
1392
+ }
1393
+ const receiverExpr = receiver === 'this' ? 'store' : `__gea_global_${sanitizeCppIdentifier(receiver)}()`;
1394
+ // gea_cpp_key boxes a typed global cell for this dynamic lookup (identity
1395
+ // for boxed receivers).
1396
+ return [
1397
+ `auto ${methodVar} = gea_cpp_key(gea_cpp_key(${receiverExpr}).record_get_literal(${cppString(method)}));`,
1398
+ `if (gea::runtime::coerce::to_boolean(${methodVar})) (void)${methodVar}(${callArgs});`,
1399
+ ];
1400
+ }
1401
+ function lowerEventCondition(expr, params) {
1402
+ const keyCode = expr.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(keyCode|which|charCode)\s*(===|==|!==|!=)\s*(-?(?:\d+|\d+\.\d+|\.\d+))$/);
1403
+ if (keyCode && params.includes(keyCode[1])) {
1404
+ const op = keyCode[3] === '===' ? '==' : keyCode[3] === '!==' ? '!=' : keyCode[3];
1405
+ return `event.keyCode ${op} ${keyCode[4]}`;
1406
+ }
1407
+ return null;
1408
+ }
1409
+ function eventArg(dynamic, direct, valueType) {
1410
+ return { dynamic, direct, valueType };
1411
+ }
1412
+ function lowerEventArgument(arg, params, eventType, storeFields, constants = new Map()) {
1413
+ const number = numericLiteralValue(arg);
1414
+ if (number !== null) {
1415
+ const direct = `static_cast<double>(${number})`;
1416
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'number');
1417
+ }
1418
+ const string = stringLiteralValue(arg);
1419
+ if (string !== null) {
1420
+ const direct = `std::string(${cppString(string)})`;
1421
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'string');
1422
+ }
1423
+ const identifier = simpleIdentifierValue(arg);
1424
+ const constant = identifier ? constantExpression(identifier, constants) : null;
1425
+ if (constant?.shape.kind === 'literal') {
1426
+ if (constant.shape.valueType === 'number') {
1427
+ return eventArg(`gea_cpp_value(${constant.expr})`, constant.expr, 'number');
1428
+ }
1429
+ if (constant.shape.valueType === 'string') {
1430
+ return eventArg(`gea_cpp_value(${constant.expr})`, constant.expr, 'string');
1431
+ }
1432
+ if (constant.shape.valueType === 'boolean') {
1433
+ return eventArg(`gea_cpp_value(${constant.expr})`, constant.expr, 'boolean');
1434
+ }
1435
+ }
1436
+ if (params.length === 1 && arg === params[0] && eventType === 'click') {
1437
+ const direct = 'static_cast<double>(event.pressValue >= 0 ? event.pressValue : event.pressId)';
1438
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'number');
1439
+ }
1440
+ if (params.length === 1 && arg === params[0])
1441
+ return eventArg('gea_ir::pointerEventValue(event)', 'gea_ir::pointerEventValue(event)', 'any');
1442
+ // Native scalar fields of the framework PointerEvent. `pointerId` joins the
1443
+ // coordinate set so multi-touch handlers can route by finger
1444
+ // (`e => store.move(e.pointerId, e.clientX, e.clientY)`) and lower to a native
1445
+ // `store->move(double, double, double)` call with no gea_cpp_value boxing.
1446
+ const coord = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(x|y|clientX|clientY|pageX|pageY|screenX|screenY|pointerId)$/);
1447
+ if (coord && params.includes(coord[1])) {
1448
+ const direct = `static_cast<double>(event.${coord[2]})`;
1449
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'number');
1450
+ }
1451
+ const firstTouchCoord = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(touches|targetTouches|changedTouches)\[0\]\.(clientX|clientY|pageX|pageY|screenX|screenY)$/);
1452
+ if (firstTouchCoord && params.includes(firstTouchCoord[1])) {
1453
+ const direct = `static_cast<double>(event.${firstTouchCoord[2]}[0].${firstTouchCoord[3]})`;
1454
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'number');
1455
+ }
1456
+ const attr = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(currentTarget|target)\.getAttribute\((['"])([^'"]+)\3\)$/);
1457
+ if (attr && params.includes(attr[1])) {
1458
+ const target = attr[2] === 'currentTarget' ? 'currentTarget' : 'target';
1459
+ const direct = `std::string(event.${target}.getAttribute(${cppString(attr[4])}))`;
1460
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'string');
1461
+ }
1462
+ const dataset = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(currentTarget|target)\.dataset\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
1463
+ if (dataset && params.includes(dataset[1])) {
1464
+ const target = dataset[2] === 'currentTarget' ? 'currentTarget' : 'target';
1465
+ const direct = `std::string(event.${target}.dataset(${cppString(dataset[3])}))`;
1466
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'string');
1467
+ }
1468
+ // `event.currentTarget.value` (or `event.target.value`) — read the
1469
+ // input element's current text. The native side mirrors NSTextField's
1470
+ // stringValue into the node's `value` attribute on every change (see
1471
+ // GeaInputField::controlTextDidChange in targets/macos), so we lower
1472
+ // this to the same getAttribute path the dataset / getAttribute cases
1473
+ // already use.
1474
+ const inputValue = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(currentTarget|target)\.value$/);
1475
+ if (inputValue && params.includes(inputValue[1])) {
1476
+ const target = inputValue[2] === 'currentTarget' ? 'currentTarget' : 'target';
1477
+ const direct = `std::string(event.${target}.getAttribute("value"))`;
1478
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'string');
1479
+ }
1480
+ // `event.keyCode` / `event.which` (and `.charCode` for legacy callers)
1481
+ // — keyboard events. The framework's PointerEvent carries the integer
1482
+ // code in `event.keyCode`; both DOM aliases collapse to the same field.
1483
+ const keyCode = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(keyCode|which|charCode)$/);
1484
+ if (keyCode && params.includes(keyCode[1])) {
1485
+ const direct = 'static_cast<double>(event.keyCode)';
1486
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'number');
1487
+ }
1488
+ const delta = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.delta$/);
1489
+ if (delta && params.includes(delta[1])) {
1490
+ const direct = 'static_cast<double>(event.delta)';
1491
+ return eventArg(`gea_cpp_value(${direct})`, direct, 'number');
1492
+ }
1493
+ const storeField = arg.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
1494
+ if (storeField) {
1495
+ const field = storeFieldByReceiver(storeField[1], storeField[2], storeFields);
1496
+ if (field?.readerName) {
1497
+ const direct = `${field.readerName}(__gea_global_${sanitizeCppIdentifier(storeField[1])}())`;
1498
+ return eventArg(`gea_cpp_key(${direct})`, direct, shapeValueType(shapeForStoreFieldPlan(field)));
1499
+ }
1500
+ }
1501
+ return null;
1502
+ }
1503
+ function directCallArguments(method, args) {
1504
+ if (method.params.length !== args.length)
1505
+ return null;
1506
+ const out = [];
1507
+ for (let index = 0; index < args.length; index += 1) {
1508
+ const paramType = method.params[index]?.valueType;
1509
+ if (!paramType)
1510
+ return null;
1511
+ const arg = args[index];
1512
+ if (arg.valueType === paramType) {
1513
+ out.push(arg.direct);
1514
+ continue;
1515
+ }
1516
+ if (paramType === 'number' && arg.valueType === 'any') {
1517
+ out.push(`gea::runtime::coerce::to_number(${arg.dynamic})`);
1518
+ continue;
1519
+ }
1520
+ if (paramType === 'boolean' && arg.valueType === 'any') {
1521
+ out.push(`gea::runtime::coerce::to_boolean(${arg.dynamic})`);
1522
+ continue;
1523
+ }
1524
+ if (paramType === 'string' && arg.valueType === 'any') {
1525
+ out.push(`gea_cpp_to_string(${arg.dynamic})`);
1526
+ continue;
1527
+ }
1528
+ return null;
1529
+ }
1530
+ return out;
1531
+ }
1532
+ function storeFieldByReceiver(receiver, name, storeFields) {
1533
+ const fieldName = sanitizeCppIdentifier(name);
1534
+ const matches = storeFields.filter((field) => field.fieldName === fieldName);
1535
+ if (matches.length === 1)
1536
+ return matches[0];
1537
+ const receiverName = sanitizeCppIdentifier(receiver);
1538
+ const byReceiver = matches.filter((field) => field.storeGlobalName === receiverName);
1539
+ return byReceiver.length === 1 ? byReceiver[0] : null;
1540
+ }
1541
+ function storeMethodByReceiver(receiver, name, storeMethods) {
1542
+ const methodName = sanitizeCppIdentifier(name);
1543
+ const receiverName = sanitizeCppIdentifier(receiver);
1544
+ const matches = storeMethods.filter((method) => method.methodName === methodName);
1545
+ const byReceiver = matches.filter((method) => method.storeGlobalName === receiverName);
1546
+ if (byReceiver.length === 1)
1547
+ return byReceiver[0];
1548
+ if (receiverName !== 'this' && matches.some((method) => !!method.storeGlobalName))
1549
+ return null;
1550
+ return matches.length === 1 ? matches[0] : null;
1551
+ }
1552
+ function shapeValueType(shape) {
1553
+ if (shape?.kind !== 'literal')
1554
+ return 'any';
1555
+ return shape.valueType === 'null' ? 'any' : shape.valueType;
1556
+ }
1557
+ function parseArrowFunction(expr) {
1558
+ const text = expr.trim();
1559
+ const arrow = text.indexOf('=>');
1560
+ if (arrow < 0)
1561
+ return null;
1562
+ const rawParams = text.slice(0, arrow).trim();
1563
+ let body = text.slice(arrow + 2).trim();
1564
+ let statements;
1565
+ if (body.startsWith('{') && body.endsWith('}')) {
1566
+ const inner = body.slice(1, -1).trim();
1567
+ const returnMatch = inner.match(/^return\s+(.+?);?$/s);
1568
+ statements = returnMatch
1569
+ ? [returnMatch[1].trim()]
1570
+ : splitTopLevelSemicolon(inner).map((statement) => statement.trim()).filter(Boolean);
1571
+ }
1572
+ else {
1573
+ statements = [body.replace(/;$/, '').trim()].filter(Boolean);
1574
+ }
1575
+ const params = rawParams.startsWith('(')
1576
+ ? rawParams.slice(1, -1).split(',').map((part) => part.trim()).filter(Boolean)
1577
+ : rawParams.length === 0
1578
+ ? []
1579
+ : [rawParams];
1580
+ if (params.some((param) => !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(param)))
1581
+ return null;
1582
+ return { params, body: statements };
1583
+ }
1584
+ export function slotAttrName(slot) {
1585
+ const payload = slot.payload;
1586
+ if (!payload || typeof payload !== 'object' || !('attrName' in payload))
1587
+ return null;
1588
+ const attrName = payload.attrName;
1589
+ return typeof attrName === 'string' ? attrName : null;
1590
+ }
1591
+ function eventTypeFromAttr(attrName) {
1592
+ return attrName.startsWith('on') && attrName.length > 2 ? attrName.slice(2).toLowerCase() : attrName.toLowerCase();
1593
+ }
1594
+ function attributeValueExpression(expr, constants = new Map()) {
1595
+ const string = stringLiteralValue(expr);
1596
+ if (string !== null)
1597
+ return cppString(string);
1598
+ const number = numericLiteralValue(expr);
1599
+ if (number !== null)
1600
+ return `std::to_string(${number}).c_str()`;
1601
+ if (expr === 'true' || expr === 'false')
1602
+ return cppString(expr);
1603
+ // Runtime numeric constants (UPPER_CASE module-level identifiers) are
1604
+ // resolved at template-setup time — they're set during module init, before
1605
+ // mount() runs, and never reassigned. Stringify them imperatively into
1606
+ // setAttribute rather than letting the slot fall out to a reactive
1607
+ // emission. Without this, `<canvas width={DISPLAY_W}>` and
1608
+ // `<virtual-list item-count={ITEM_COUNT}>` would force the entire
1609
+ // component down the closure-codegen reactiveAttr path whose initial
1610
+ // apply never fires in the C++ runtime.
1611
+ const ident = simpleIdentifierValue(expr);
1612
+ if (ident && isRuntimeNumericConstantIdentifier(ident)) {
1613
+ // Prefer folding the constant to its literal value (mirrors the style
1614
+ // path's `constantExpression` resolution). A CROSS-MODULE imported
1615
+ // `const DISPLAY_W = 410` is inlined-and-dropped by the bundler, so no C++
1616
+ // global `DISPLAY_W` survives to reference — emitting the bare identifier
1617
+ // then fails to compile ("use of undeclared identifier"). The IR constants
1618
+ // map still carries its value, so fold it. Fall back to the bare identifier
1619
+ // for constants NOT in the map (same-module constants emitted as real C++
1620
+ // globals), preserving the documented module-init behavior.
1621
+ const constant = constantExpression(ident, constants);
1622
+ if (constant && constant.shape.kind === 'literal' && constant.shape.valueType === 'number') {
1623
+ return `std::to_string(static_cast<long long>(${constant.expr})).c_str()`;
1624
+ }
1625
+ return `std::to_string(static_cast<long long>(${ident})).c_str()`;
1626
+ }
1627
+ return null;
1628
+ }
1629
+ function simpleIdentifierValue(expr) {
1630
+ const text = expr.trim();
1631
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(text) ? text : null;
1632
+ }
1633
+ function parseStaticAttrs(rawTag) {
1634
+ const attrs = {};
1635
+ const attrPattern = /\s([A-Za-z_:][A-Za-z0-9_:.-]*)(?:=(?:"([^"]*)"|'([^']*)'|([^ >]+)))?/g;
1636
+ let match;
1637
+ while ((match = attrPattern.exec(rawTag))) {
1638
+ attrs[match[1]] = match[2] ?? match[3] ?? match[4] ?? 'true';
1639
+ }
1640
+ return attrs;
1641
+ }
1642
+ function numericLiteralValue(expr) {
1643
+ const text = expr.trim();
1644
+ return /^-?(?:\d+|\d+\.\d+|\.\d+)$/.test(text) ? text : null;
1645
+ }
1646
+ export function lowerTextSlot(slot, storeFields) {
1647
+ if (!slot.expr)
1648
+ return null;
1649
+ const parts = slot.exprPath && slot.exprPath.length === 2 ? [slot.exprPath.join('.')] : splitTopLevelPlus(slot.expr);
1650
+ const stateTypes = new Set();
1651
+ const deps = [];
1652
+ const fields = [];
1653
+ const expressions = [];
1654
+ for (const part of parts) {
1655
+ const literal = stringLiteralValue(part);
1656
+ if (literal !== null) {
1657
+ expressions.push(`std::string(${cppString(literal)})`);
1658
+ continue;
1659
+ }
1660
+ const match = part.match(/^[A-Za-z_$][A-Za-z0-9_$]*\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
1661
+ if (!match)
1662
+ return null;
1663
+ const lowered = lowerStoreFieldByName(match[1], storeFieldLocalName(match[1]), storeFields);
1664
+ if (!lowered)
1665
+ return null;
1666
+ stateTypes.add(lowered.store.stateType);
1667
+ deps.push(lowered.store.fieldName);
1668
+ fields.push(lowered.store);
1669
+ expressions.push(textExpressionForStoreField(lowered.store, lowered.expr));
1670
+ }
1671
+ if (stateTypes.size !== 1 || expressions.length === 0)
1672
+ return null;
1673
+ return { stateType: [...stateTypes][0], deps, fields: uniqueStoreFields(fields), expr: expressions.join(' + ') };
1674
+ }
1675
+ function lowerStoreExpression(field, storeFields) {
1676
+ const fromPath = field.exprPath && field.exprPath.length === 2 ? field.exprPath[1] : null;
1677
+ if (fromPath)
1678
+ return lowerStoreFieldByName(fromPath, storeFieldLocalName(fromPath), storeFields);
1679
+ const binary = field.expr.match(/^[A-Za-z_$][A-Za-z0-9_$]*\.([A-Za-z_$][A-Za-z0-9_$]*)\s*([+-])\s*(-?(?:\d+|\d+\.\d+|\.\d+))$/);
1680
+ if (!binary)
1681
+ return null;
1682
+ const [, fieldName, op, amount] = binary;
1683
+ return lowerStoreFieldByName(fieldName, `(${storeFieldLocalName(fieldName)} ${op} ${amount})`, storeFields);
1684
+ }
1685
+ function lowerStorePxLengthStyleExpression(field, propertyName, storeFields) {
1686
+ if (!isPxLengthStylePropertyName(propertyName) || !field.expr)
1687
+ return null;
1688
+ const source = ts.createSourceFile('style.ts', `(${field.expr});`, ts.ScriptTarget.Latest, false);
1689
+ const stmt = source.statements[0];
1690
+ if (!stmt || !ts.isExpressionStatement(stmt))
1691
+ return null;
1692
+ const node = unwrapExpressionNode(stmt.expression);
1693
+ if (!ts.isTemplateExpression(node))
1694
+ return null;
1695
+ if (node.head.text !== '' || node.templateSpans.length !== 1)
1696
+ return null;
1697
+ const span = node.templateSpans[0];
1698
+ if (span.literal.text !== 'px')
1699
+ return null;
1700
+ const expr = unwrapExpressionNode(span.expression);
1701
+ if (!ts.isPropertyAccessExpression(expr))
1702
+ return null;
1703
+ const lowered = lowerStoreFieldByName(expr.name.text, storeFieldLocalName(expr.name.text), storeFields);
1704
+ return lowered ? { ...lowered, shape: { kind: 'literal', valueType: 'number' } } : null;
1705
+ }
1706
+ function lowerStorePercentLengthStyleExpression(field, propertyName, storeFields) {
1707
+ if (!stylePercentPropertyEnumForPropertyName(propertyName) || !field.expr)
1708
+ return null;
1709
+ const source = ts.createSourceFile('style.ts', `(${field.expr});`, ts.ScriptTarget.Latest, false);
1710
+ const stmt = source.statements[0];
1711
+ if (!stmt || !ts.isExpressionStatement(stmt))
1712
+ return null;
1713
+ const node = unwrapExpressionNode(stmt.expression);
1714
+ if (!ts.isTemplateExpression(node))
1715
+ return null;
1716
+ if (node.head.text !== '' || node.templateSpans.length !== 1)
1717
+ return null;
1718
+ const span = node.templateSpans[0];
1719
+ if (span.literal.text !== '%')
1720
+ return null;
1721
+ const expr = unwrapExpressionNode(span.expression);
1722
+ if (!ts.isPropertyAccessExpression(expr))
1723
+ return null;
1724
+ const lowered = lowerStoreFieldByName(expr.name.text, storeFieldLocalName(expr.name.text), storeFields);
1725
+ return lowered ? { ...lowered, shape: { kind: 'literal', valueType: 'number' }, styleUnit: 'percent' } : null;
1726
+ }
1727
+ function lowerStoreRotateStyleExpression(field, propertyName, storeFields) {
1728
+ if (!isRotateTransformPropertyName(propertyName) || !field.expr)
1729
+ return null;
1730
+ const source = ts.createSourceFile('style.ts', `(${field.expr});`, ts.ScriptTarget.Latest, false);
1731
+ const stmt = source.statements[0];
1732
+ if (!stmt || !ts.isExpressionStatement(stmt))
1733
+ return null;
1734
+ const node = unwrapExpressionNode(stmt.expression);
1735
+ if (!ts.isTemplateExpression(node))
1736
+ return null;
1737
+ const degrees = rotateDegreesTemplateExpression(node, propertyName);
1738
+ if (!degrees)
1739
+ return null;
1740
+ const expr = unwrapExpressionNode(degrees);
1741
+ if (!ts.isPropertyAccessExpression(expr))
1742
+ return null;
1743
+ const lowered = lowerStoreFieldByName(expr.name.text, storeFieldLocalName(expr.name.text), storeFields);
1744
+ return lowered ? { ...lowered, shape: { kind: 'literal', valueType: 'number' } } : null;
1745
+ }
1746
+ function lowerStoreOpaqueColorStyleExpression(field, propertyName, storeFields, constants) {
1747
+ if (!styleOpaqueColorTargetForPropertyName(propertyName) || !field.expr)
1748
+ return null;
1749
+ const source = ts.createSourceFile('style.ts', `(${field.expr});`, ts.ScriptTarget.Latest, false);
1750
+ const stmt = source.statements[0];
1751
+ if (!stmt || !ts.isExpressionStatement(stmt))
1752
+ return null;
1753
+ const node = unwrapExpressionNode(stmt.expression);
1754
+ if (!ts.isConditionalExpression(node))
1755
+ return null;
1756
+ const condition = unwrapExpressionNode(node.condition);
1757
+ if (!ts.isPropertyAccessExpression(condition))
1758
+ return null;
1759
+ const consequent = opaqueHexColorExpressionForNode(node.whenTrue, constants);
1760
+ const alternate = opaqueHexColorExpressionForNode(node.whenFalse, constants);
1761
+ if (!consequent || !alternate)
1762
+ return null;
1763
+ const fieldName = condition.name.text;
1764
+ const lowered = lowerStoreFieldByName(fieldName, storeFieldLocalName(fieldName), storeFields);
1765
+ if (!lowered)
1766
+ return null;
1767
+ return {
1768
+ ...lowered,
1769
+ expr: `(${storeFieldAsBoolean(lowered.store, storeFieldLocalName(fieldName))} ? ${consequent} : ${alternate})`,
1770
+ shape: { kind: 'literal', valueType: 'number' },
1771
+ styleUnit: 'color',
1772
+ };
1773
+ }
1774
+ function lowerStoreKeywordStyleExpression(field, propertyName, storeFields, constants) {
1775
+ if (!styleKeywordPropertiesForPropertyName(propertyName) || !field.expr)
1776
+ return null;
1777
+ const source = ts.createSourceFile('style.ts', `(${field.expr});`, ts.ScriptTarget.Latest, false);
1778
+ const stmt = source.statements[0];
1779
+ if (!stmt || !ts.isExpressionStatement(stmt))
1780
+ return null;
1781
+ const node = unwrapExpressionNode(stmt.expression);
1782
+ if (!ts.isConditionalExpression(node))
1783
+ return null;
1784
+ const condition = unwrapExpressionNode(node.condition);
1785
+ if (!ts.isPropertyAccessExpression(condition))
1786
+ return null;
1787
+ const consequent = keywordEntriesForNode(propertyName, node.whenTrue, constants);
1788
+ const alternate = keywordEntriesForNode(propertyName, node.whenFalse, constants);
1789
+ const consequentValue = keywordCommonValue(consequent);
1790
+ const alternateValue = keywordCommonValue(alternate);
1791
+ if (consequentValue === null || alternateValue === null || !keywordEntriesCompatible(consequent, alternate))
1792
+ return null;
1793
+ const fieldName = condition.name.text;
1794
+ const lowered = lowerStoreFieldByName(fieldName, storeFieldLocalName(fieldName), storeFields);
1795
+ if (!lowered)
1796
+ return null;
1797
+ return {
1798
+ ...lowered,
1799
+ expr: `(${storeFieldAsBoolean(lowered.store, storeFieldLocalName(fieldName))} ? ${consequentValue} : ${alternateValue})`,
1800
+ shape: { kind: 'literal', valueType: 'number' },
1801
+ styleUnit: 'keyword',
1802
+ };
1803
+ }
1804
+ function isRotateTransformPropertyName(propertyName) {
1805
+ return propertyName === 'transform' || propertyName === 'rotate';
1806
+ }
1807
+ function rotateDegreesTemplateExpression(node, propertyName) {
1808
+ if (node.templateSpans.length !== 1)
1809
+ return null;
1810
+ const span = node.templateSpans[0];
1811
+ if (propertyName === 'rotate') {
1812
+ if (node.head.text !== '' || span.literal.text.trim() !== 'deg')
1813
+ return null;
1814
+ return span.expression;
1815
+ }
1816
+ if (propertyName === 'transform') {
1817
+ if (node.head.text.trim() !== 'rotate(' || span.literal.text.trim() !== 'deg)')
1818
+ return null;
1819
+ return span.expression;
1820
+ }
1821
+ return null;
1822
+ }
1823
+ function lowerStoreFieldByName(name, expr, storeFields) {
1824
+ const sanitized = sanitizeCppIdentifier(name);
1825
+ const matches = storeFields.filter((candidate) => candidate.fieldName === sanitized);
1826
+ return matches.length === 1 ? { store: matches[0], expr } : null;
1827
+ }
1828
+ export function storeFieldLocalName(fieldName) {
1829
+ return `__gea_${sanitizeCppIdentifier(fieldName)}`;
1830
+ }
1831
+ function uniqueStoreFields(fields) {
1832
+ const seen = new Set();
1833
+ const uniqueFields = [];
1834
+ for (const field of fields) {
1835
+ const key = `${field.storeClass}.${field.fieldName}`;
1836
+ if (seen.has(key))
1837
+ continue;
1838
+ seen.add(key);
1839
+ uniqueFields.push(field);
1840
+ }
1841
+ return uniqueFields;
1842
+ }
1843
+ function textExpressionForStoreField(store, expr) {
1844
+ const shape = shapeForStoreFieldPlan(store);
1845
+ if (shape?.kind === 'literal' && shape.valueType === 'string')
1846
+ return expr;
1847
+ return `gea_cpp_to_string(${expr})`;
1848
+ }
1849
+ function storeFieldAsBoolean(store, expr) {
1850
+ const shape = shapeForStoreFieldPlan(store);
1851
+ if (shape?.kind === 'literal' && shape.valueType === 'boolean')
1852
+ return expr;
1853
+ if (shape?.kind === 'literal' && shape.valueType === 'number')
1854
+ return `(${expr} != static_cast<double>(0))`;
1855
+ if (shape?.kind === 'literal' && shape.valueType === 'string')
1856
+ return `(!${expr}.empty())`;
1857
+ return `gea::runtime::coerce::to_boolean(gea_cpp_key(${expr}))`;
1858
+ }
1859
+ function directNumberStyleApplyLine(node, propertyName, value) {
1860
+ const rawNumber = rawNumberExpression(value);
1861
+ const properties = styleRawNumberPropertyEnumsForPropertyName(propertyName);
1862
+ if (properties) {
1863
+ return properties.map((property) => `${node}.style().set(gea::embedded::ui::Property::${property}, ${rawNumber});`).join(' ');
1864
+ }
1865
+ if (propertyName === 'opacity')
1866
+ return `${node}.style().opacity(${opacityNumberExpression(value)});`;
1867
+ if (propertyName === 'flex') {
1868
+ return `${node}.style().set(gea::embedded::ui::Property::Flex, ${rawNumber}); ${node}.style().set(gea::embedded::ui::Property::FlexBasis, gea::embedded::ui::kUnset);`;
1869
+ }
1870
+ if (propertyName === 'translate-x')
1871
+ return `${node}.style().translateX(${rawNumber});`;
1872
+ if (propertyName === 'translate-y')
1873
+ return `${node}.style().translateY(${rawNumber});`;
1874
+ if (propertyName === 'scale')
1875
+ return `${node}.style().scale(static_cast<double>(${value}));`;
1876
+ if (propertyName === 'transform' || propertyName === 'rotate')
1877
+ return `${node}.style().rotateDegrees(static_cast<double>(${value}));`;
1878
+ return null;
1879
+ }
1880
+ function rawNumberExpression(value) {
1881
+ return `([](double __v) -> int { return std::isfinite(__v) ? static_cast<int>(std::round(__v)) : 0; })(static_cast<double>(${value}))`;
1882
+ }
1883
+ function opacityNumberExpression(value) {
1884
+ return `([](double __v) -> int { if (!std::isfinite(__v)) return 0; if (__v <= 1.0) __v *= 255.0; if (__v < 0.0) __v = 0.0; if (__v > 255.0) __v = 255.0; return static_cast<int>(__v + 0.5); })(static_cast<double>(${value}))`;
1885
+ }
1886
+ function directStringStyleApplyLines(node, propertyName, rawValue) {
1887
+ const color = opaqueCssHexColor(rawValue);
1888
+ const colorLine = color ? directColorStyleApplyLine(node, propertyName, nativeStyleColorExpression(color)) : null;
1889
+ if (colorLine)
1890
+ return [colorLine];
1891
+ const keyword = styleKeywordPropertyValuesForPropertyName(propertyName, rawValue);
1892
+ return keyword
1893
+ ? keyword.map(({ property, value }) => `${node}.style().set(gea::embedded::ui::Property::${property}, ${value});`)
1894
+ : null;
1895
+ }
1896
+ function directKeywordStyleApplyLine(node, propertyName, value) {
1897
+ const properties = styleKeywordPropertiesForPropertyName(propertyName);
1898
+ return properties
1899
+ ? properties.map((property) => `${node}.style().set(gea::embedded::ui::Property::${property}, static_cast<int>(${value}));`).join(' ')
1900
+ : null;
1901
+ }
1902
+ function keywordEntriesForNode(propertyName, node, constants = new Map()) {
1903
+ const literal = staticStringValueForNode(node, constants);
1904
+ return literal === null ? null : styleKeywordPropertyValuesForPropertyName(propertyName, literal);
1905
+ }
1906
+ function keywordEntriesCompatible(a, b) {
1907
+ if (!a || !b || a.length !== b.length)
1908
+ return false;
1909
+ for (let i = 0; i < a.length; i += 1) {
1910
+ if (a[i].property !== b[i].property)
1911
+ return false;
1912
+ }
1913
+ return true;
1914
+ }
1915
+ function keywordCommonValue(entries) {
1916
+ if (!entries || entries.length === 0)
1917
+ return null;
1918
+ const first = entries[0].value;
1919
+ return entries.every((entry) => entry.value === first) ? first : null;
1920
+ }
1921
+ function directColorStyleApplyLine(node, propertyName, value) {
1922
+ const target = styleOpaqueColorTargetForPropertyName(propertyName);
1923
+ if (target === 'background')
1924
+ return `${node}.style().backgroundColor(static_cast<int>(${value}));`;
1925
+ if (target === 'color')
1926
+ return `${node}.style().color(static_cast<int>(${value}));`;
1927
+ if (target === 'active-background') {
1928
+ return `${node}.style().set(gea::embedded::ui::Property::ActiveBackgroundColor, static_cast<int>(${value})); ${node}.style().set(gea::embedded::ui::Property::HasActiveBackground, 1);`;
1929
+ }
1930
+ const borderProperty = opaqueColorBorderProperty(target);
1931
+ if (borderProperty)
1932
+ return `${node}.style().set(gea::embedded::ui::Property::${borderProperty}, static_cast<int>(${value}));`;
1933
+ return null;
1934
+ }
1935
+ function opaqueColorBorderProperty(target) {
1936
+ if (target === 'border-color')
1937
+ return 'BorderColor';
1938
+ if (target === 'border-top-color')
1939
+ return 'BorderTopColor';
1940
+ if (target === 'border-right-color')
1941
+ return 'BorderRightColor';
1942
+ if (target === 'border-bottom-color')
1943
+ return 'BorderBottomColor';
1944
+ if (target === 'border-left-color')
1945
+ return 'BorderLeftColor';
1946
+ return null;
1947
+ }
1948
+ function stylePropertyArgument(propertyName) {
1949
+ const declaration = styleDeclarationEnumForPropertyName(propertyName);
1950
+ return declaration ? `gea::embedded::ui::StyleDeclaration::${declaration}` : cppString(propertyName);
1951
+ }
1952
+ function styleApplyLines(node, propertyName, value, shape, styleUnit) {
1953
+ const property = stylePropertyArgument(propertyName);
1954
+ if (shape?.kind === 'literal' && shape.valueType === 'number') {
1955
+ const direct = styleUnit === 'percent'
1956
+ ? directPercentStyleApplyLine(node, propertyName, value)
1957
+ : styleUnit === 'color'
1958
+ ? directColorStyleApplyLine(node, propertyName, value)
1959
+ : styleUnit === 'keyword'
1960
+ ? directKeywordStyleApplyLine(node, propertyName, value)
1961
+ : directNumberStyleApplyLine(node, propertyName, value);
1962
+ return [direct ?? `gea::embedded::ui::StyleSheet::instance().applyNumberProperty(${node}, ${property}, static_cast<double>(${value}));`];
1963
+ }
1964
+ if (shape?.kind === 'literal' && shape.valueType === 'string') {
1965
+ return [`gea::embedded::ui::StyleSheet::instance().applyProperty(${node}, ${property}, ${value});`];
1966
+ }
1967
+ if (shape?.kind === 'literal' && shape.valueType === 'boolean') {
1968
+ return [`gea::embedded::ui::StyleSheet::instance().applyProperty(${node}, ${property}, gea_cpp_to_string(${value}));`];
1969
+ }
1970
+ return [
1971
+ `gea::embedded::ui::StyleSheet::instance().applyProperty(${node}, ${property}, gea_cpp_to_string(gea_cpp_key(${value})));`,
1972
+ ];
1973
+ }
1974
+ function directPercentStyleApplyLine(node, propertyName, value) {
1975
+ const property = stylePercentPropertyEnumForPropertyName(propertyName);
1976
+ return property
1977
+ ? `${node}.style().set(gea::embedded::ui::Property::${property}, static_cast<int>(std::round(static_cast<double>(${value}) * 10.0)));`
1978
+ : null;
1979
+ }
1980
+ function valueShapeForStoreField(field) {
1981
+ if (!field)
1982
+ return null;
1983
+ if (field.shape)
1984
+ return field.shape;
1985
+ return shapeFromInitializer(field.initializer);
1986
+ }
1987
+ function shapeForStoreFieldPlan(field) {
1988
+ return field.shape ?? shapeFromPrimitiveFieldType(field.fieldType);
1989
+ }
1990
+ function shapeFromPrimitiveFieldType(fieldType) {
1991
+ const type = fieldType.trim();
1992
+ if (type === 'double' || type === 'gea_number')
1993
+ return { kind: 'literal', valueType: 'number' };
1994
+ if (type === 'std::string')
1995
+ return { kind: 'literal', valueType: 'string' };
1996
+ if (type === 'bool')
1997
+ return { kind: 'literal', valueType: 'boolean' };
1998
+ return null;
1999
+ }
2000
+ function shapeFromInitializer(initializer) {
2001
+ if (!initializer)
2002
+ return null;
2003
+ const text = initializer.trim();
2004
+ if (/^-?(?:\d+|\d+\.\d+|\.\d+)$/.test(text))
2005
+ return { kind: 'literal', valueType: 'number' };
2006
+ if (text === 'true' || text === 'false')
2007
+ return { kind: 'literal', valueType: 'boolean' };
2008
+ if (text === 'null')
2009
+ return { kind: 'literal', valueType: 'null' };
2010
+ if ((text.startsWith("'") && text.endsWith("'")) || (text.startsWith('"') && text.endsWith('"'))) {
2011
+ return { kind: 'literal', valueType: 'string' };
2012
+ }
2013
+ return null;
2014
+ }
2015
+ function splitTopLevelPlus(expr) {
2016
+ const parts = [];
2017
+ let start = 0;
2018
+ let quote = null;
2019
+ let escaped = false;
2020
+ for (let index = 0; index < expr.length; index += 1) {
2021
+ const char = expr[index];
2022
+ if (quote) {
2023
+ if (escaped)
2024
+ escaped = false;
2025
+ else if (char === '\\')
2026
+ escaped = true;
2027
+ else if (char === quote)
2028
+ quote = null;
2029
+ continue;
2030
+ }
2031
+ if (char === '"' || char === "'")
2032
+ quote = char;
2033
+ else if (char === '+') {
2034
+ parts.push(expr.slice(start, index).trim());
2035
+ start = index + 1;
2036
+ }
2037
+ }
2038
+ parts.push(expr.slice(start).trim());
2039
+ return parts.filter(Boolean);
2040
+ }
2041
+ function splitTopLevelComma(expr) {
2042
+ const parts = [];
2043
+ let start = 0;
2044
+ let quote = null;
2045
+ let escaped = false;
2046
+ let depth = 0;
2047
+ for (let index = 0; index < expr.length; index += 1) {
2048
+ const char = expr[index];
2049
+ if (quote) {
2050
+ if (escaped)
2051
+ escaped = false;
2052
+ else if (char === '\\')
2053
+ escaped = true;
2054
+ else if (char === quote)
2055
+ quote = null;
2056
+ continue;
2057
+ }
2058
+ if (char === '"' || char === "'") {
2059
+ quote = char;
2060
+ continue;
2061
+ }
2062
+ if (char === '(' || char === '[' || char === '{')
2063
+ depth += 1;
2064
+ else if (char === ')' || char === ']' || char === '}')
2065
+ depth -= 1;
2066
+ else if (char === ',' && depth === 0) {
2067
+ parts.push(expr.slice(start, index).trim());
2068
+ start = index + 1;
2069
+ }
2070
+ }
2071
+ parts.push(expr.slice(start).trim());
2072
+ return parts;
2073
+ }
2074
+ function findTopLevelOperator(expr, operator) {
2075
+ let quote = null;
2076
+ let escaped = false;
2077
+ let depth = 0;
2078
+ for (let index = 0; index < expr.length; index += 1) {
2079
+ const char = expr[index];
2080
+ if (quote) {
2081
+ if (escaped)
2082
+ escaped = false;
2083
+ else if (char === '\\')
2084
+ escaped = true;
2085
+ else if (char === quote)
2086
+ quote = null;
2087
+ continue;
2088
+ }
2089
+ if (char === '"' || char === "'") {
2090
+ quote = char;
2091
+ continue;
2092
+ }
2093
+ if (char === '(' || char === '[' || char === '{')
2094
+ depth += 1;
2095
+ else if (char === ')' || char === ']' || char === '}')
2096
+ depth -= 1;
2097
+ else if (depth === 0 && expr.startsWith(operator, index))
2098
+ return index;
2099
+ }
2100
+ return -1;
2101
+ }
2102
+ function splitTopLevelSemicolon(expr) {
2103
+ const parts = [];
2104
+ let start = 0;
2105
+ let quote = null;
2106
+ let escaped = false;
2107
+ let depth = 0;
2108
+ for (let index = 0; index < expr.length; index += 1) {
2109
+ const char = expr[index];
2110
+ if (quote) {
2111
+ if (escaped)
2112
+ escaped = false;
2113
+ else if (char === '\\')
2114
+ escaped = true;
2115
+ else if (char === quote)
2116
+ quote = null;
2117
+ continue;
2118
+ }
2119
+ if (char === '"' || char === "'") {
2120
+ quote = char;
2121
+ continue;
2122
+ }
2123
+ if (char === '(' || char === '[' || char === '{')
2124
+ depth += 1;
2125
+ else if (char === ')' || char === ']' || char === '}')
2126
+ depth -= 1;
2127
+ else if (char === ';' && depth === 0) {
2128
+ parts.push(expr.slice(start, index).trim());
2129
+ start = index + 1;
2130
+ }
2131
+ }
2132
+ parts.push(expr.slice(start).trim());
2133
+ return parts;
2134
+ }
2135
+ function stripOuterParens(expr) {
2136
+ let text = expr.trim();
2137
+ while (text.startsWith('(') && text.endsWith(')') && matchingOuterParens(text)) {
2138
+ text = text.slice(1, -1).trim();
2139
+ }
2140
+ return text;
2141
+ }
2142
+ function matchingOuterParens(expr) {
2143
+ let depth = 0;
2144
+ let quote = null;
2145
+ let escaped = false;
2146
+ for (let index = 0; index < expr.length; index += 1) {
2147
+ const char = expr[index];
2148
+ if (quote) {
2149
+ if (escaped)
2150
+ escaped = false;
2151
+ else if (char === '\\')
2152
+ escaped = true;
2153
+ else if (char === quote)
2154
+ quote = null;
2155
+ continue;
2156
+ }
2157
+ if (char === '"' || char === "'") {
2158
+ quote = char;
2159
+ continue;
2160
+ }
2161
+ if (char === '(')
2162
+ depth += 1;
2163
+ else if (char === ')') {
2164
+ depth -= 1;
2165
+ if (depth === 0 && index < expr.length - 1)
2166
+ return false;
2167
+ }
2168
+ }
2169
+ return depth === 0;
2170
+ }
2171
+ function objectKeyName(expr) {
2172
+ const string = stringLiteralValue(expr);
2173
+ if (string !== null)
2174
+ return string;
2175
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(expr) ? expr : null;
2176
+ }
2177
+ function uniqueItemFieldNames(fields) {
2178
+ return [...new Set(fields)];
2179
+ }
2180
+ function uniqueStrings(values) {
2181
+ return [...new Set(values)];
2182
+ }
2183
+ export function stringLiteralValue(expr) {
2184
+ const quote = expr[0];
2185
+ if ((quote !== '"' && quote !== "'") || expr[expr.length - 1] !== quote)
2186
+ return null;
2187
+ return expr
2188
+ .slice(1, -1)
2189
+ .replace(/\\n/g, '\n')
2190
+ .replace(/\\t/g, '\t')
2191
+ .replace(/\\'/g, "'")
2192
+ .replace(/\\"/g, '"')
2193
+ .replace(/\\\\/g, '\\');
2194
+ }
2195
+ function opaqueHexColorExpressionForNode(node, constants = new Map()) {
2196
+ const literal = staticStringValueForNode(node, constants);
2197
+ const color = literal === null ? null : opaqueCssHexColor(literal);
2198
+ return color ? nativeStyleColorExpression(color) : null;
2199
+ }
2200
+ function staticStringValueForNode(node, constants) {
2201
+ const expr = unwrapExpressionNode(node);
2202
+ if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr))
2203
+ return expr.text;
2204
+ if (ts.isIdentifier(expr)) {
2205
+ const constant = constants.get(expr.text);
2206
+ return constant?.valueType === 'string' ? constant.value : null;
2207
+ }
2208
+ return null;
2209
+ }
2210
+ function keyedListKeyField(payload, itemName, field) {
2211
+ const explicit = explicitKeyFieldName(payload, itemName);
2212
+ if (explicit)
2213
+ return field.itemFields.find((candidate) => sanitizeCppIdentifier(candidate.name) === explicit) ?? null;
2214
+ return field.itemFields.find((candidate) => sanitizeCppIdentifier(candidate.name) === 'id') ?? null;
2215
+ }
2216
+ function explicitKeyFieldName(payload, itemName) {
2217
+ const keyPath = payload.keyPath;
2218
+ if (Array.isArray(keyPath) && keyPath.length === 2 && keyPath[0] === itemName && typeof keyPath[1] === 'string') {
2219
+ return sanitizeCppIdentifier(keyPath[1]);
2220
+ }
2221
+ for (const name of ['keyProp', 'keyField']) {
2222
+ const value = payload[name];
2223
+ if (typeof value === 'string' && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value))
2224
+ return sanitizeCppIdentifier(value);
2225
+ }
2226
+ for (const name of ['keyExpr', 'key']) {
2227
+ const value = payload[name];
2228
+ if (typeof value !== 'string')
2229
+ continue;
2230
+ const match = value.match(new RegExp(`^${itemName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.([A-Za-z_$][A-Za-z0-9_$]*)$`));
2231
+ if (match)
2232
+ return sanitizeCppIdentifier(match[1]);
2233
+ }
2234
+ return null;
2235
+ }