@barefootjs/jsx 0.26.4 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/compiler.d.ts.map +1 -1
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +941 -130
  5. package/dist/ir-to-client-js/client-only-elision.d.ts +103 -0
  6. package/dist/ir-to-client-js/client-only-elision.d.ts.map +1 -0
  7. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  8. package/dist/ir-to-client-js/control-flow/plan/branch-loop.d.ts +6 -0
  9. package/dist/ir-to-client-js/control-flow/plan/branch-loop.d.ts.map +1 -1
  10. package/dist/ir-to-client-js/control-flow/plan/build-branch-loop.d.ts +2 -1
  11. package/dist/ir-to-client-js/control-flow/plan/build-branch-loop.d.ts.map +1 -1
  12. package/dist/ir-to-client-js/control-flow/plan/build-insert.d.ts +7 -0
  13. package/dist/ir-to-client-js/control-flow/plan/build-insert.d.ts.map +1 -1
  14. package/dist/ir-to-client-js/control-flow/plan/build-lazy-row.d.ts +107 -0
  15. package/dist/ir-to-client-js/control-flow/plan/build-lazy-row.d.ts.map +1 -0
  16. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts +9 -1
  17. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/plan/lazy-row-eligibility.d.ts +203 -0
  19. package/dist/ir-to-client-js/control-flow/plan/lazy-row-eligibility.d.ts.map +1 -0
  20. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +10 -0
  21. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  22. package/dist/ir-to-client-js/control-flow/shared.d.ts +1 -1
  23. package/dist/ir-to-client-js/control-flow/stringify/branch-loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts +54 -0
  25. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts.map +1 -0
  26. package/dist/ir-to-client-js/control-flow/stringify/inner-loop.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/control-flow/stringify/insert.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/lazy-row.d.ts +98 -0
  29. package/dist/ir-to-client-js/control-flow/stringify/lazy-row.d.ts.map +1 -0
  30. package/dist/ir-to-client-js/control-flow/stringify/loop-child-arm.d.ts +5 -0
  31. package/dist/ir-to-client-js/control-flow/stringify/loop-child-arm.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts +17 -20
  33. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/stringify/reactive-effects.d.ts +63 -4
  35. package/dist/ir-to-client-js/control-flow/stringify/reactive-effects.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/control-flow.d.ts +1 -1
  37. package/dist/ir-to-client-js/control-flow.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/element-refs.d.ts +8 -3
  39. package/dist/ir-to-client-js/element-refs.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/emit-reactive.d.ts +8 -1
  41. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/html-template.d.ts +24 -0
  43. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/imports.d.ts +2 -2
  45. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/types.d.ts +9 -1
  48. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/utils.d.ts +1 -1
  50. package/dist/types.d.ts +25 -2
  51. package/dist/types.d.ts.map +1 -1
  52. package/package.json +2 -2
  53. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +542 -689
  54. package/src/__tests__/child-components-in-map.test.ts +4 -4
  55. package/src/__tests__/client-js-generation.test.ts +23 -12
  56. package/src/__tests__/composite-branch-loop.test.ts +14 -5
  57. package/src/__tests__/conditional-mapArray-key.test.ts +7 -1
  58. package/src/__tests__/create-selector.test.ts +21 -7
  59. package/src/__tests__/cross-file-client-signal.test.ts +5 -1
  60. package/src/__tests__/early-return-scope-var-ref.test.ts +10 -11
  61. package/src/__tests__/inline-jsx-callback.test.ts +6 -4
  62. package/src/__tests__/ir-jsx-props.test.ts +6 -5
  63. package/src/__tests__/lazy-row-eligibility.test.ts +692 -0
  64. package/src/__tests__/loop-branch-bare-expression-reactive-text.test.ts +98 -0
  65. package/src/__tests__/loop-fallback-wrap.test.ts +34 -16
  66. package/src/__tests__/loop-hoisted-template.test.ts +10 -6
  67. package/src/__tests__/module-level-signal.audit.test.ts +7 -2
  68. package/src/__tests__/nested-loop-conditional.test.ts +9 -7
  69. package/src/__tests__/nested-loop-reactive-attrs.test.ts +2 -2
  70. package/src/__tests__/preamble-region-patch.test.ts +18 -12
  71. package/src/__tests__/profile-cond-binding-ids.test.ts +3 -2
  72. package/src/__tests__/profile-loop-binding-ids.test.ts +4 -3
  73. package/src/__tests__/profile-nested-binding-ids.test.ts +11 -6
  74. package/src/__tests__/reactive-attrs-in-map.test.ts +6 -4
  75. package/src/__tests__/static-loop-csr-materialize.test.ts +6 -1
  76. package/src/__tests__/template-closure.test.ts +1 -1
  77. package/src/compiler.ts +11 -0
  78. package/src/index.ts +1 -0
  79. package/src/ir-to-client-js/client-only-elision.ts +273 -0
  80. package/src/ir-to-client-js/collect-elements.ts +56 -17
  81. package/src/ir-to-client-js/control-flow/plan/branch-loop.ts +6 -0
  82. package/src/ir-to-client-js/control-flow/plan/build-branch-loop.ts +35 -12
  83. package/src/ir-to-client-js/control-flow/plan/build-insert.ts +9 -2
  84. package/src/ir-to-client-js/control-flow/plan/build-lazy-row.ts +305 -0
  85. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +44 -12
  86. package/src/ir-to-client-js/control-flow/plan/lazy-row-eligibility.ts +440 -0
  87. package/src/ir-to-client-js/control-flow/plan/loop.ts +10 -0
  88. package/src/ir-to-client-js/control-flow/shared.ts +1 -1
  89. package/src/ir-to-client-js/control-flow/stringify/branch-loop.ts +34 -4
  90. package/src/ir-to-client-js/control-flow/stringify/claim-plan.ts +68 -0
  91. package/src/ir-to-client-js/control-flow/stringify/inner-loop.ts +18 -9
  92. package/src/ir-to-client-js/control-flow/stringify/insert.ts +17 -11
  93. package/src/ir-to-client-js/control-flow/stringify/lazy-row.ts +478 -0
  94. package/src/ir-to-client-js/control-flow/stringify/loop-child-arm.ts +41 -17
  95. package/src/ir-to-client-js/control-flow/stringify/loop.ts +71 -46
  96. package/src/ir-to-client-js/control-flow/stringify/reactive-effects.ts +241 -31
  97. package/src/ir-to-client-js/control-flow.ts +8 -3
  98. package/src/ir-to-client-js/element-refs.ts +9 -11
  99. package/src/ir-to-client-js/emit-reactive.ts +50 -14
  100. package/src/ir-to-client-js/html-template.ts +29 -9
  101. package/src/ir-to-client-js/imports.ts +13 -4
  102. package/src/ir-to-client-js/reactivity.ts +3 -2
  103. package/src/ir-to-client-js/types.ts +10 -2
  104. package/src/ir-to-client-js/utils.ts +1 -1
  105. package/src/jsx-to-ir.ts +26 -8
  106. package/src/types.ts +25 -2
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Slot unification Step B (`spec/slot-unification.md` §3(b), §5 "Step B —
3
+ * marker elision"): decide, EXACTLY ONCE and BEFORE either `adapter.generate`
4
+ * (SSR) or `generateClientJs` (CSR) run, which `/* @client *\/` text slots
5
+ * can drop their `<!--bf:sN-->…<!--/-->` marker pair entirely from both
6
+ * outputs. Every consumer (all nine SSR adapters' `renderExpression`, and
7
+ * the CSR emitters in `html-template.ts`) reads the single
8
+ * `IRExpression.markerless` flag this pass writes — nobody re-derives the
9
+ * decision, per CLAUDE.md's "Never add compiler options/hooks for
10
+ * tool-specific output rewriting" spirit: one door in, everyone reads it.
11
+ *
12
+ * Scope — deliberately the NARROWEST slice of §3(b)'s elision rule that is
13
+ * fully sound today, not the general case:
14
+ *
15
+ * Only `expr.clientOnly && expr.slotId` expressions OUTSIDE any loop or
16
+ * conditional branch (i.e. reachable from the component's own render tree
17
+ * by walking only `element`/`text`/`expression`/`fragment` nodes).
18
+ *
19
+ * Why THIS slice and not ordinary reactive text slots (loop rows,
20
+ * conditional branches): every other kind of slot's SSR-rendered width is
21
+ * DATA-DEPENDENT — an ordinary `{item.name}` may render empty or non-empty
22
+ * per request, so a LATER sibling's absolute child-index path would only be
23
+ * valid for the specific width THIS request happened to produce, not for
24
+ * every request the compiled function ever serves. `/* @client *\/`
25
+ * expressions are the one case free of that problem: SSR can never evaluate
26
+ * client-only JS (the whole point of the escape valve), so its rendered
27
+ * width is deterministically ZERO on every request, for every adapter, with
28
+ * no data dependence at all. That determinism is what makes computing a
29
+ * real, reusable, hydration-safe path sound here without also solving the
30
+ * general "does an earlier sibling's width vary by request" problem.
31
+ *
32
+ * Path safety within that scope — the part that generalizes A3's
33
+ * `computeSkeletonSlotPaths` (`html-template.ts`) rather than reinventing
34
+ * it: paths are root-relative child-index chains, exactly like that
35
+ * function's, walked in document order with the SAME "once we hit something
36
+ * whose contributed width isn't a compile-time constant, every remaining
37
+ * sibling AND everything nested inside it loses eligibility" rule (nested
38
+ * content reached only through an uncertain-index sibling would resolve an
39
+ * absolute path through that uncertain index — silently wrong, not loud, so
40
+ * it must never be attempted). Concretely, walking a children list left to
41
+ * right:
42
+ * - a static `element` always contributes exactly one node — recurse into
43
+ * its own children as an independent, freshly-indexed scope (its own
44
+ * internal accounting can't leak out, and nothing external can poison
45
+ * it either, since the element itself is a fixed anchor regardless of
46
+ * what's inside it);
47
+ * - static `text` contributes a node per HTML-parser text-run-merging
48
+ * rules (adjacent text/expression children collapse into ONE Text
49
+ * node — mirrors `computeSkeletonSlotPaths`'s `pendingText` tracking);
50
+ * - a `clientOnly` expression with a slotId is the one ELIGIBLE case,
51
+ * PROVIDED it is not itself part of a merged text run (rule (i) — the
52
+ * `/* @client *\/` slot must not be immediately adjacent, once markers
53
+ * are gone, to loose text or another expression, or the HTML parser
54
+ * would merge them into one Text node with no way to tell which
55
+ * content is which). Once one is elided, this level (and everything
56
+ * nested inside any later sibling) is marked ineligible for the
57
+ * remainder of the walk at this level — see the "freeze" note below;
58
+ * - any other `expression` (a real reactive/static text or markup slot),
59
+ * any `conditional`/`loop`/`component`/`async`/`provider`/
60
+ * `if-statement`/`slot` node, is data-dependent or opaque width and
61
+ * FREEZES the rest of this children list (see below) — this is
62
+ * strictly conservative: it also means a `/* @client *\/` expression
63
+ * is never eligible once any of these appears earlier at the same
64
+ * level, even though `/* @client *\/`'s own width is always zero,
65
+ * because SIBLINGS reached only via nested recursion past that point
66
+ * would otherwise resolve an absolute path through the frozen node's
67
+ * uncertain contributed width;
68
+ * - the same hazard-tag / force-close-group / void-element / `<tr>`
69
+ * foster-parenting guards `computeSkeletonSlotPaths` uses (imported,
70
+ * not re-derived) abort the ENTIRE walk (a global bail, exactly like
71
+ * that function's `state.bailed`) — a parser hazard means every index
72
+ * computed anywhere in this tree is suspect, not just the ones near
73
+ * the hazard, so "don't guess" means don't guess about the blast
74
+ * radius either.
75
+ *
76
+ * "Freeze" (the one simplification versus a maximally-precise per-branch
77
+ * eligibility tracker): once ANY `/* @client *\/` slot at a given level is
78
+ * elided — OR once anything data-dependent/opaque is seen at that level —
79
+ * that level's remaining siblings (and anything nested only through them)
80
+ * stop being assigned real paths for the rest of THIS walk, even though a
81
+ * maximally precise analysis could sometimes still find one. This caps
82
+ * elision at (at most) one `/* @client *\/` slot per static subtree —
83
+ * conservative by design, matching the elision rule's own framing, and it
84
+ * guarantees two elided slots can never end up needing an insertion whose
85
+ * reference node depends on the other's still-unresolved width. Freezing is
86
+ * PER CHILDREN-LIST (an element's own children start a fresh, unfrozen
87
+ * scope) — global-bail is reserved for hazard tags alone.
88
+ *
89
+ * Deferred (loudly, not silently): ordinary reactive text slots in loop
90
+ * rows / conditional branches keep their markers — see above for why
91
+ * widening this to data-dependent-width content needs a materially
92
+ * different (and per-adapter-verified) safety argument that this PR does
93
+ * not attempt.
94
+ */
95
+
96
+ import type { IRNode, IRExpression } from '../types.ts'
97
+ import {
98
+ VOID_ELEMENTS,
99
+ SKELETON_PATH_HAZARD_TAGS,
100
+ skeletonForceCloseGroup,
101
+ hasForeignTableRowContent,
102
+ flattenSkeletonChildren,
103
+ } from './html-template.ts'
104
+
105
+ /** Global bail, mirroring `computeSkeletonSlotPaths`'s `state.bailed`: once
106
+ * a parser hazard is seen anywhere, every remaining step of this ONE
107
+ * `decideClientOnlyElision` call becomes a no-op. Slots already elided
108
+ * before the hazard was reached keep their `markerless`/`elidedPath` —
109
+ * those paths were computed from safe ground and remain valid; only
110
+ * FURTHER assignment stops. */
111
+ interface ElisionState {
112
+ bailed: boolean
113
+ }
114
+
115
+ /**
116
+ * Entry point: mutates `root`'s `expression` nodes in place, setting
117
+ * `markerless`/`elidedPath` on every eligible `/* @client *\/` slot found.
118
+ * Safe to call on any component's render tree; a tree with none simply
119
+ * mutates nothing.
120
+ */
121
+ export function decideClientOnlyElision(root: IRNode): void {
122
+ walkNode(root, [], new Set(), { bailed: false })
123
+ }
124
+
125
+ /** Walk one node that occupies a known position (`path`) in its parent's
126
+ * children. Only `element`/`fragment` are ever recursed into by the
127
+ * children-list walker below — this wrapper exists so both the top-level
128
+ * call and `walkChildren`'s per-element recursion can share one path. */
129
+ function walkNode(
130
+ node: IRNode,
131
+ path: readonly number[],
132
+ forceCloseAncestors: ReadonlySet<number>,
133
+ state: ElisionState,
134
+ ): void {
135
+ if (state.bailed) return
136
+ if (node.type === 'element') {
137
+ if (!elementIsPathSafe(node.tag, flattenSkeletonChildren(node.children))) {
138
+ state.bailed = true
139
+ return
140
+ }
141
+ const groupIdx = skeletonForceCloseGroup(node.tag)
142
+ if (groupIdx >= 0 && forceCloseAncestors.has(groupIdx)) {
143
+ state.bailed = true
144
+ return
145
+ }
146
+ const nextAncestors = groupIdx >= 0 ? new Set([...forceCloseAncestors, groupIdx]) : forceCloseAncestors
147
+ walkChildren(flattenSkeletonChildren(node.children), path, nextAncestors, state)
148
+ } else if (node.type === 'fragment') {
149
+ walkChildren(flattenSkeletonChildren(node.children), path, forceCloseAncestors, state)
150
+ }
151
+ // Any other root shape (a bare conditional/loop/component return, etc.)
152
+ // has no static children list to walk — nothing to do.
153
+ }
154
+
155
+ /**
156
+ * Walk one parent's (already-fragment-flattened) children left to right,
157
+ * assigning paths to eligible `/* @client *\/` slots. `parentPath` is the
158
+ * path to the PARENT of this children list (the element/root whose
159
+ * `childNodes` these indices are relative to). `forceCloseAncestors`
160
+ * mirrors `computeSkeletonSlotPaths`'s ancestor-threaded force-close-group
161
+ * tracking (`<h2>` inside an open `<h1>`, `<li>` inside an open `<li>`, …) —
162
+ * threaded down through element recursion, exactly like that function.
163
+ * `frozen` is local to THIS call (this one children list) — an element's
164
+ * own children get a fresh, unfrozen scope regardless of what froze here.
165
+ */
166
+ function walkChildren(
167
+ children: readonly IRNode[],
168
+ parentPath: readonly number[],
169
+ forceCloseAncestors: ReadonlySet<number>,
170
+ state: ElisionState,
171
+ ): void {
172
+ let frozen = false
173
+ let idx = 0
174
+ let pendingText = false
175
+
176
+ for (let i = 0; i < children.length; i++) {
177
+ if (state.bailed) return
178
+ const child = children[i]
179
+
180
+ switch (child.type) {
181
+ case 'text': {
182
+ if (child.value === '') continue
183
+ if (!pendingText) idx += 1
184
+ pendingText = true
185
+ continue
186
+ }
187
+
188
+ case 'expression': {
189
+ if (child.expr === 'null' || child.expr === 'undefined') continue
190
+ if (child.clientOnly && child.slotId) {
191
+ const adjacent = isTextLike(children[i - 1]) || isTextLike(children[i + 1])
192
+ if (!frozen && !adjacent) {
193
+ markElided(child, [...parentPath, idx])
194
+ frozen = true // one elision per level — see module docstring
195
+ } else {
196
+ frozen = true // still freeze: an un-elided expression here is
197
+ // no different from any other data-dependent-width sibling.
198
+ }
199
+ idx += 1
200
+ pendingText = false
201
+ continue
202
+ }
203
+ // Any other expression — data-dependent width. Freeze the rest of
204
+ // this level; still consume ONE index (best-effort bookkeeping —
205
+ // nothing downstream reads `idx` past this point since `frozen`
206
+ // blocks any further assignment).
207
+ frozen = true
208
+ idx += 1
209
+ pendingText = false
210
+ continue
211
+ }
212
+
213
+ case 'element': {
214
+ if (!elementIsPathSafe(child.tag, flattenSkeletonChildren(child.children))) {
215
+ // Hazard shape: bail the WHOLE walk (matches
216
+ // `computeSkeletonSlotPaths`'s "don't guess" stance), not just
217
+ // this level — a parser hazard means indices anywhere in this
218
+ // tree are untrustworthy, not only the ones near it.
219
+ state.bailed = true
220
+ return
221
+ }
222
+ if (!frozen) {
223
+ walkNode(child, [...parentPath, idx], forceCloseAncestors, state)
224
+ }
225
+ idx += 1
226
+ pendingText = false
227
+ continue
228
+ }
229
+
230
+ case 'fragment':
231
+ continue // already flattened
232
+
233
+ default:
234
+ // conditional / loop / component / async / provider / if-statement /
235
+ // slot: opaque or variable width. Freeze the rest of this level.
236
+ frozen = true
237
+ idx += 1
238
+ pendingText = false
239
+ continue
240
+ }
241
+ }
242
+ }
243
+
244
+ /** True for a node that would merge (per HTML text-node-merging rules) with
245
+ * an adjacent bare-text-position slot if that slot's markers were removed —
246
+ * rule (i) of §3(b). `undefined` (no sibling — start/end of the children
247
+ * list) is never adjacent. */
248
+ function isTextLike(node: IRNode | undefined): boolean {
249
+ if (!node) return false
250
+ if (node.type === 'text') return node.value !== ''
251
+ if (node.type === 'expression') return node.expr !== 'null' && node.expr !== 'undefined'
252
+ return false
253
+ }
254
+
255
+ function markElided(expr: IRExpression, path: readonly number[]): void {
256
+ expr.markerless = true
257
+ expr.elidedPath = path
258
+ }
259
+
260
+ /**
261
+ * Mirrors `computeSkeletonSlotPaths`'s per-element safety checks (hazard
262
+ * tags, void elements, `<tr>` foster-parenting) without re-deriving the
263
+ * underlying tag sets — imported from `html-template.ts` so the two walks
264
+ * can never silently diverge on which shapes are hazardous. Force-close
265
+ * groups are checked separately by the caller (`walkNode`), which has the
266
+ * ancestor set this check does not.
267
+ */
268
+ function elementIsPathSafe(tag: string, flatChildren: readonly IRNode[]): boolean {
269
+ if (SKELETON_PATH_HAZARD_TAGS.has(tag)) return false
270
+ if (VOID_ELEMENTS.has(tag) && flatChildren.length > 0) return false
271
+ if (tag === 'tr' && hasForeignTableRowContent(flatChildren)) return false
272
+ return true
273
+ }
@@ -414,8 +414,8 @@ export function collectInnerLoops(
414
414
 
415
415
  /**
416
416
  * Decide whether a loop's runtime rendering needs element reconciliation
417
- * (reconcileElements + composite item rendering) rather than the simple
418
- * template-per-item path, and collect inner-loop metadata for its body.
417
+ * (mapArray/mapArrayAnchored + composite item rendering) rather than the
418
+ * simple template-per-item path, and collect inner-loop metadata for its body.
419
419
  *
420
420
  * Used by both the top-level `case 'loop'` in `collectElements` and the
421
421
  * branch-loop collector in `collectBranchLoops`. Each call site applies
@@ -595,7 +595,11 @@ export function collectElements(
595
595
  },
596
596
  expression: ({ node: ex, scope: inCond }) => {
597
597
  if (ex.clientOnly && ex.slotId) {
598
- ctx.clientOnlyElements.push({ slotId: ex.slotId, expression: ex.expr })
598
+ ctx.clientOnlyElements.push({
599
+ slotId: ex.slotId,
600
+ expression: ex.expr,
601
+ elidedPath: ex.markerless ? ex.elidedPath : undefined,
602
+ })
599
603
  return
600
604
  }
601
605
  if (!ex.slotId || inCond) return
@@ -1113,7 +1117,7 @@ function collectBranchLoops(
1113
1117
  : decideLoopRendering(n, siblingOffsets, undefined)
1114
1118
 
1115
1119
  // Build the item template from loop children.
1116
- // Use loopDepth=0: this loop gets its own reconcileElements (independent
1120
+ // Use loopDepth=0: this loop gets its own mapArray/mapArrayAnchored call (independent
1117
1121
  // from the conditional's template), so items use data-key (not data-key-1).
1118
1122
  // Pass loopParams so expressions reference the per-item signal accessor,
1119
1123
  // keeping the template consistent with reactive effect expressions that
@@ -1409,19 +1413,54 @@ function summarizeLoopChildBranch(
1409
1413
  // on the branch root yields exactly this branch's direct bindings
1410
1414
  // without re-collecting what a nested arm already owns (#2347).
1411
1415
  reactiveAttrs: collectLoopChildReactiveAttrs(node, ctx, loopParam, loopParamBindings, true),
1412
- // Skip when the branch's ENTIRE content is a single bare `expression`
1413
- // (no wrapping element) e.g. a hoisted `renderNode={(n) => <Pill/>}`
1414
- // callback (#1211/#1213). That value is already fully re-evaluated and
1415
- // spliced via `__bfSlot` whenever `insert()` (re-)mounts this branch;
1416
- // an *additional* nested createEffect for the same expression re-calls
1417
- // it and creates a second, independent live element (a JSX-callback
1418
- // result isn't idempotent to re-invoke the way a plain signal read is),
1419
- // and the loop-child arm's `$t()`-based anchor lookup designed for
1420
- // text nodes doesn't cleanly displace an already-mounted Element,
1421
- // so the second instance lands beside the first instead of replacing
1422
- // it. A text *nested inside* a static wrapper element in the branch
1423
- // (the element-descent case) is unaffected and still collected below.
1424
- reactiveTexts: node.type === 'expression'
1416
+ // Skip ONLY when the branch's entire content is a single bare
1417
+ // `expression` (no wrapping element) that MAY yield a live DOM node
1418
+ // i.e. it contains a call anywhere (`node.hasFunctionCalls`, computed
1419
+ // by the AST walk in `exprHasFunctionCalls`/jsx-to-ir.ts, recursively
1420
+ // catches a call nested in a template literal or a nested ternary, not
1421
+ // just a top-level call). A call can return an Element (a hoisted
1422
+ // `renderNode={(n) => <Pill/>}` callback lowered to a component call,
1423
+ // #1211/#1213) and the compiler cannot tell from syntax whether it does
1424
+ // — both `renderChild(...)` and `_p.renderCell(...)` are a
1425
+ // `CallExpression` so this stays conservative for ANY call, not just
1426
+ // ones known to return JSX. Re-evaluating a non-idempotent call inside
1427
+ // an *additional* nested createEffect (on top of the eval already done
1428
+ // for the `__bfSlot`-wrapped splice whenever `insert()` (re-)mounts this
1429
+ // branch) would call it again on every unrelated tick and discard the
1430
+ // previous element's listeners/state.
1431
+ //
1432
+ // Everything else — a property access (`row.label`), an identifier, a
1433
+ // literal, a template literal, string concatenation, or a nested
1434
+ // ternary of those — cannot itself construct a DOM node (only a JSX
1435
+ // literal or a call can, and a JSX literal branch is never `type:
1436
+ // 'expression'` in the first place — see `transformJsxExpression`), so
1437
+ // it is safe to collect. This is the fix for the loop-branch-stale-text
1438
+ // defect: a keyed loop row whose branch is e.g. `row.done ? row.label :
1439
+ // 'pending'` previously had NO update path at all when `row.label`
1440
+ // changed without `row.done` flipping — `insert()` (runtime/insert.ts)
1441
+ // correctly no-ops when its condition is unchanged (branch-internal
1442
+ // updates are deliberately the effect system's job, not DOM
1443
+ // replacement's), but with reactiveTexts always `[]` for this shape,
1444
+ // no effect existed either, so the branch was frozen at its mount-time
1445
+ // value. The stale rationale in a prior version of this comment blamed
1446
+ // "the loop-child arm's `$t()`-based anchor lookup", but `$t()` no
1447
+ // longer exists — it was one of four content mechanisms deleted by the
1448
+ // slot-unification work. The current claim door
1449
+ // (`stringifyLoopChildArm` → `lazySlots(..., kind: 'markup')` →
1450
+ // `writeMarkup`, runtime/claim-slots.ts) clears the claimed range and
1451
+ // splices the Node by identity, so "lands beside the first" cannot
1452
+ // happen through it; only the call's non-idempotence still applies, and
1453
+ // that alone is why the skip narrows rather than disappears.
1454
+ //
1455
+ // Collecting here is necessary but not sufficient: `n.slotId` must also
1456
+ // be set for `collectLoopChildReactiveTexts` (ir-to-client-js/
1457
+ // reactivity.ts) to do anything — see `transformConditionalBranch`'s
1458
+ // `refsLoopParam` check (jsx-to-ir.ts) for the matching half of this fix
1459
+ // that gives a bare loop-item-reading branch a slotId at all, which also
1460
+ // makes `irToHtmlTemplate` emit its `<!--bf:sN-->…<!--/-->` marker (the
1461
+ // same call builds both the SSR and the CSR/hydration template, so the
1462
+ // two can't disagree on shape).
1463
+ reactiveTexts: node.type === 'expression' && node.hasFunctionCalls
1425
1464
  ? []
1426
1465
  : collectLoopChildReactiveTexts(node, ctx, loopParam, loopParamBindings, true),
1427
1466
  }
@@ -18,6 +18,7 @@
18
18
  import type { CompositeLoopPlan, LoopChildRefBinding, PreambleRegionPlan } from './loop.ts'
19
19
  import type { EventDelegationPlan } from './event-delegation.ts'
20
20
  import type { ReactiveEffectsPlan } from './reactive-effects.ts'
21
+ import type { LazyRowPlanData } from './build-lazy-row.ts'
21
22
 
22
23
  export interface BranchPlainLoopPlan {
23
24
  /**
@@ -89,6 +90,11 @@ export interface BranchPlainLoopPlan {
89
90
  * renderItem layout, mirroring the top-level plain plan.
90
91
  */
91
92
  preambleRegions: readonly PreambleRegionPlan[]
93
+ /**
94
+ * Lazy row graph plan (`spec/slot-unification.md` §9, L3) — see
95
+ * `PlainLoopVariant.lazyRow`. Undefined ⇒ today's eager emission.
96
+ */
97
+ lazyRow?: LazyRowPlanData
92
98
  }
93
99
 
94
100
  export interface BranchCompositeLoopPlan {
@@ -15,6 +15,8 @@ import { buildChainedArrayExpr, varSlotId, wrapLoopParamAsAccessor } from '../..
15
15
  import { buildBranchCompositePlan } from './build-composite-loop.ts'
16
16
  import { buildBranchLoopDelegationPlan } from './build-event-delegation.ts'
17
17
  import { buildReactiveEffectsPlan } from './build-reactive-effects.ts'
18
+ import { buildLazyRowPlan } from './build-lazy-row.ts'
19
+ import type { LazyRowScopeInfo } from './lazy-row-eligibility.ts'
18
20
  import { destructureLoopParam, loopKeyFn, buildChildRefBindings, buildPreambleRegionPlans } from '../shared.ts'
19
21
  import { renderPreamble, irToHtmlTemplate } from '../../html-template.ts'
20
22
  import type {
@@ -23,7 +25,11 @@ import type {
23
25
  BranchPlainLoopPlan,
24
26
  } from './branch-loop.ts'
25
27
 
26
- export function buildBranchLoopPlan(loop: BranchLoop, profileComponentName?: string): BranchLoopPlan {
28
+ export function buildBranchLoopPlan(
29
+ loop: BranchLoop,
30
+ profileComponentName?: string,
31
+ lazyScope?: LazyRowScopeInfo,
32
+ ): BranchLoopPlan {
27
33
  const containerSlotId = loop.containerSlotId
28
34
  const cv = varSlotId(containerSlotId)
29
35
  const containerVar = `__loop_${cv}`
@@ -45,6 +51,17 @@ export function buildBranchLoopPlan(loop: BranchLoop, profileComponentName?: str
45
51
 
46
52
  // flatMap descriptor mode — see buildPlainLoopPlan (build-loop.ts).
47
53
  const fm = loop.flatMapClient
54
+ const arrayExpr = fm
55
+ ? `(${buildChainedArrayExpr(loop)}).flatMap(${fm.params} => ${fm.body})`
56
+ : buildChainedArrayExpr(loop)
57
+ const indexParam = loop.index || '__idx'
58
+ const mapPreambleWrapped = loop.preamble
59
+ ? renderPreamble(loop.preamble, {
60
+ transformJs: (t) => wrapLoopParamAsAccessor(t, loop.param, loop.paramBindings),
61
+ renderLeaf: (ir) => irToHtmlTemplate(ir, undefined, 1, [{ param: loop.param, bindings: loop.paramBindings }], undefined, true),
62
+ })
63
+ : ''
64
+ const preambleRegions = buildPreambleRegionPlans(loop.preambleRegions, loop.param, loop.paramBindings)
48
65
  const plan: BranchPlainLoopPlan = {
49
66
  kind: 'plain',
50
67
  rowConstruction: 'string-template',
@@ -52,23 +69,29 @@ export function buildBranchLoopPlan(loop: BranchLoop, profileComponentName?: str
52
69
  containerVar,
53
70
  markerId: loop.markerId,
54
71
  flatMapLeafItem: fm ? true : undefined,
55
- arrayExpr: fm
56
- ? `(${buildChainedArrayExpr(loop)}).flatMap(${fm.params} => ${fm.body})`
57
- : buildChainedArrayExpr(loop),
72
+ arrayExpr,
58
73
  keyFn: fm
59
74
  ? (fm.keyed ? '(__bfD, __bfI) => String(__bfD.k ?? __bfI)' : 'null')
60
75
  : loopKeyFn(loop),
61
76
  paramHead,
62
77
  paramUnwrap,
63
- indexParam: loop.index || '__idx',
78
+ indexParam,
64
79
  // Wrap loop-param references to signal-accessor form so the preamble
65
80
  // matches the template literal's already-wrapped reads (#1065).
66
- mapPreambleWrapped: loop.preamble
67
- ? renderPreamble(loop.preamble, {
68
- transformJs: (t) => wrapLoopParamAsAccessor(t, loop.param, loop.paramBindings),
69
- renderLeaf: (ir) => irToHtmlTemplate(ir, undefined, 1, [{ param: loop.param, bindings: loop.paramBindings }], undefined, true),
70
- })
71
- : '',
81
+ mapPreambleWrapped,
82
+ // Lazy row graph (§9, L3) — undefined for every ineligible loop.
83
+ lazyRow: buildLazyRowPlan({
84
+ loop,
85
+ arrayExpr,
86
+ indexParam,
87
+ paramUnwrap,
88
+ mapPreambleWrapped,
89
+ preambleRegionCount: preambleRegions.length,
90
+ callSite: 'branch-plain',
91
+ flatMapLeafItem: Boolean(fm),
92
+ anchored: false,
93
+ scope: lazyScope,
94
+ }) ?? undefined,
72
95
  template: loop.template,
73
96
  reactiveEffects: hasReactiveEffects
74
97
  ? buildReactiveEffectsPlan({
@@ -82,7 +105,7 @@ export function buildBranchLoopPlan(loop: BranchLoop, profileComponentName?: str
82
105
  : null,
83
106
  eventDelegation: buildBranchLoopDelegationPlan(loop, cv, profileComponentName),
84
107
  childRefs: buildChildRefBindings(loop.bindings.refs, loop.param, loop.paramBindings),
85
- preambleRegions: buildPreambleRegionPlans(loop.preambleRegions, loop.param, loop.paramBindings),
108
+ preambleRegions,
86
109
  bodyIsMultiRoot: loop.bodyIsMultiRoot ?? false,
87
110
  profileLoopId: profileComponentName ? `${profileComponentName}#binding:${containerSlotId}` : undefined,
88
111
  }
@@ -14,6 +14,7 @@ import type {
14
14
  } from '../../types.ts'
15
15
  import { addCondAttrToTemplate } from '../../html-template.ts'
16
16
  import { buildBranchLoopPlan } from './build-branch-loop.ts'
17
+ import type { LazyRowScopeInfo } from './lazy-row-eligibility.ts'
17
18
  import type {
18
19
  InsertPlan,
19
20
  InsertArm,
@@ -26,6 +27,12 @@ export interface BuildInsertOptions {
26
27
  eventNameMode: 'dom' | 'raw'
27
28
  /** Owning component name in profile mode (#1690, SR3) — else undefined. */
28
29
  profileComponentName?: string
30
+ /**
31
+ * Component-scope name facts for the lazy row graph gate
32
+ * (`spec/slot-unification.md` §9.4). Threaded down to branch-scoped plain
33
+ * loops; omitted → those loops keep today's eager emission.
34
+ */
35
+ lazyScope?: LazyRowScopeInfo
29
36
  }
30
37
 
31
38
  export function buildInsertPlan(
@@ -88,13 +95,13 @@ function buildArmBody(branch: BranchSummary, options: BuildInsertOptions): ArmBo
88
95
  expression: t.expression,
89
96
  })),
90
97
  // Branch-scoped loops, fully Plan-built (Item 2 final migration).
91
- loops: branch.loops.map(l => buildBranchLoopPlan(l, pc)),
98
+ loops: branch.loops.map(l => buildBranchLoopPlan(l, pc, options.lazyScope)),
92
99
  // Nested conditionals are themselves InsertPlans — built recursively so
93
100
  // the same stringifier handles arbitrary depth. Their scope is always
94
101
  // `__branchScope` (the parent arm's bindEvents argument), regardless of
95
102
  // the outer scope; only the eventNameMode is inherited.
96
103
  conditionals: branch.conditionals.map(c =>
97
- buildInsertPlan(c, { scope: { kind: 'branchScope' }, eventNameMode: options.eventNameMode, profileComponentName: pc }),
104
+ buildInsertPlan(c, { scope: { kind: 'branchScope' }, eventNameMode: options.eventNameMode, profileComponentName: pc, lazyScope: options.lazyScope }),
98
105
  ),
99
106
  }
100
107
  }