@barefootjs/jsx 0.35.2 → 0.35.4

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 (30) hide show
  1. package/dist/debug.d.ts +33 -3
  2. package/dist/debug.d.ts.map +1 -1
  3. package/dist/index.js +2995 -2851
  4. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  5. package/dist/ir-to-client-js/plan/build-static-array-child-init.d.ts.map +1 -1
  6. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +19 -1
  7. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  8. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  9. package/dist/ir-to-client-js/types.d.ts +25 -0
  10. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  11. package/dist/jsx-to-ir.d.ts.map +1 -1
  12. package/dist/prop-rewrite.d.ts +26 -0
  13. package/dist/prop-rewrite.d.ts.map +1 -1
  14. package/package.json +2 -2
  15. package/src/__tests__/branch-local-in-attr-position.test.ts +24 -12
  16. package/src/__tests__/client-only-date-lowering.test.ts +29 -1
  17. package/src/__tests__/debug.test.ts +246 -0
  18. package/src/__tests__/issue-2798-static-nested-loop-bindings.test.ts +127 -0
  19. package/src/__tests__/issue-2856-branch-local-shorthand.test.ts +86 -0
  20. package/src/__tests__/issue-2897-static-loop-conditional.test.ts +340 -0
  21. package/src/__tests__/lazy-conditional.test.ts +1 -0
  22. package/src/__tests__/rewrite-destructured-props.test.ts +10 -5
  23. package/src/debug.ts +214 -84
  24. package/src/ir-to-client-js/collect-elements.ts +83 -3
  25. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +59 -19
  26. package/src/ir-to-client-js/plan/static-array-child-init.ts +19 -1
  27. package/src/ir-to-client-js/stringify/static-array-child-init.ts +39 -0
  28. package/src/ir-to-client-js/types.ts +37 -1
  29. package/src/jsx-to-ir.ts +16 -4
  30. package/src/prop-rewrite.ts +74 -33
@@ -5,7 +5,7 @@
5
5
  import { type IRNode, type IRElement, type IRComponent, type IRLoop, type IRProp, pickAttrMetaFromIR } from '../types.ts'
6
6
  import type { ClientJsContext, ConditionalBranchChildComponent, ConditionalBranchReactiveAttr, BranchLoop, ConditionalBranchTextEffect, ConditionalElement, LoopChildBindings, LoopChildBranchSummary, LoopChildConditional, LoopOffset, NestedLoop } from './types.ts'
7
7
  import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, type LoopParamSpec } from './utils.ts'
8
- import { classifyReactivity, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings, buildLoopRowScope, anyNameIn } from './reactivity.ts'
8
+ import { classifyReactivity, needsEffectWrapper, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings, buildLoopRowScope, anyNameIn } from './reactivity.ts'
9
9
  import { irToHtmlTemplate, irToPlaceholderTemplate, irChildrenToJsExpr, jsxChildrenPropGetterExpr, buildLoopSkeletonTemplate, computeSkeletonSlotPaths, renderFlatMapClientBody, renderFlatMapProjectionClientBody, flatMapCallbackHasKeyedLeaf, type SkeletonSlotPaths } from './html-template.ts'
10
10
  import { detectRootNamespaceWrapTag } from './control-flow/stringify/template-parse.ts'
11
11
  import { expandDynamicPropValue, expandConstantForReactivity, resolveRestSpreadOrigin, resolveRestSpreadNames } from './prop-handling.ts'
@@ -752,10 +752,78 @@ export function collectElements(
752
752
  // Determine rendering strategy for dynamic arrays:
753
753
  // Use element reconciliation when the loop body has nested components,
754
754
  // or when inner loops need their own mapArray for events/reactive text.
755
- const { useElementReconciliation, innerLoops } = projectionInner
755
+ const { useElementReconciliation: reconciliationBase, innerLoops } = projectionInner
756
756
  ? { useElementReconciliation: false, innerLoops: undefined }
757
757
  : decideLoopRendering(l, siblingOffsets, ctx)
758
758
 
759
+ // #2897: a static (non-signal) array's forEach bake and the
760
+ // `inner-loop-nested` clone-and-wire architecture (#2798) have NO
761
+ // conditional-handling machinery at all — a `{cond ? A : B}` inside
762
+ // either the outer row or a depth-1 inner loop's row bakes to its
763
+ // initial branch at compile time and never updates, since neither
764
+ // path ever re-evaluates the condition. `elem.bodyIsItemConditional`
765
+ // (below) already carves out the WHOLE-row, one-empty-branch shape;
766
+ // this widens the same idea to any conditional anywhere in the row
767
+ // tree. `bindings.conditionals` is the outer row's own conditionals
768
+ // (never recurses into `loop` nodes, see `collectLoopChildConditionals`'s
769
+ // `stopAt(..., 'loop', ...)`); `innerLoops[i].bindings.conditionals` is
770
+ // collected separately per inner loop (#2706) — together they cover
771
+ // the whole tree with no overlap. Excludes a child-component-rooted
772
+ // outer item (`l.childComponent`) — out of scope, matching #2798's own
773
+ // plain-element-only scoping for the identical reason (#1725's
774
+ // document-order-zip shape doesn't address plain-element bindings).
775
+ //
776
+ // Gated on `reactiveBeyondLoopScope`, not mere presence: EVERY
777
+ // loop-param-referencing conditional lands in `bindings.conditionals`
778
+ // (`classifyReactivity` reports `'loop-param'` for `item.key === 'x'`
779
+ // exactly like it does for `flag()` — array static-ness plays no part
780
+ // in that classification, by design). For a static array the row
781
+ // item never changes after first render, so a condition that reads
782
+ // ONLY the item/index (`item.key === 'messages'`) is exactly as
783
+ // compile-time-bakeable as the #2798 static path already assumes —
784
+ // regardless of whether its branches are a bare element or a child
785
+ // component (`SocialShell`'s `NAV_ITEMS.map()` row: `{item.key ===
786
+ // 'messages' ? <SocialUnreadBadge /> : null}` inside a static
787
+ // function-local array — the static `outer-nested`/`inner-loop-nested`
788
+ // init already tolerates an absent-this-row child component). Only a
789
+ // condition that can ITSELF change value later (`flag()`, or a mixed
790
+ // `item.x && flag()`) needs the escalation #2897 actually fixed.
791
+ const staticRowHasConditional = !projectionInner && l.isStaticArray && !l.childComponent
792
+ && bindings.conditionals.some(c => c.reactiveBeyondLoopScope)
793
+ const staticInnerLoopHasConditional = !projectionInner && l.isStaticArray && !l.childComponent
794
+ && (innerLoops ?? []).some(il => il.bindings.conditionals.some(c => c.reactiveBeyondLoopScope))
795
+ const hasInnerStructure = (l.nestedComponents?.length ?? 0) > 0 || (innerLoops?.length ?? 0) > 0
796
+ // An own-row conditional alone needs no inner structure to reconcile —
797
+ // it falls through (via `clientIsStaticArray` below) straight to the
798
+ // plain dynamic-array path, which already wires a bare conditional's
799
+ // live branch-swap correctly (`buildLoopReactiveEffectsPlan`, proven
800
+ // by the identical shape on a signal-backed array). But when the row
801
+ // ALSO has a sibling inner loop (`hasInnerStructure`), that plain path
802
+ // (`buildPlainLoopPlan`) never reads `TopLevelLoop.innerLoops` at all —
803
+ // only the composite and static-array-child-init plans do — so an
804
+ // inner loop's own ref/reactive-attr/reactive-text bindings would be
805
+ // silently dropped (pullfrog review on #2899: confirmed by compiling
806
+ // a static row with a signal-driven sibling conditional next to an
807
+ // inner loop with a `ref` — the ref callback never appeared in the
808
+ // emitted JS). Escalating to the composite path here, exactly as an
809
+ // inner-loop conditional already does, keeps those bindings wired.
810
+ // An inner-loop conditional always DOES need reconciliation on its
811
+ // own (no `hasInnerStructure` gate needed there — `innerLoops` being
812
+ // non-empty is exactly what `hasInnerStructure` already asks), since
813
+ // #2798's static machinery it would otherwise take has no conditional
814
+ // support to add to — `buildTopLevelCompositePlan` already handles
815
+ // nested loops of arbitrary depth, including the conditional case,
816
+ // unconditionally.
817
+ const useElementReconciliation =
818
+ reconciliationBase || staticInnerLoopHasConditional || (staticRowHasConditional && hasInnerStructure)
819
+ // The client-side `isStaticArray` field (NOT the IR-level `l.isStaticArray`,
820
+ // which SSR adapters like Go template's static-loop baking still read
821
+ // directly and are unaffected by — #2897 is client-JS-only): false
822
+ // whenever a conditional forces this loop off the static fast path,
823
+ // so `buildLoopPlan`'s dispatcher and `buildStaticArrayChildInitsPlan`
824
+ // both skip the static machinery for it automatically.
825
+ const clientIsStaticArray = l.isStaticArray && !staticRowHasConditional && !staticInnerLoopHasConditional
826
+
759
827
  let template = ''
760
828
  let templateIndexed: string | undefined
761
829
  let staticItemTemplate: string | undefined
@@ -878,7 +946,7 @@ export function collectElements(
878
946
  bindings,
879
947
  childComponent: l.childComponent,
880
948
  nestedComponents: l.nestedComponents,
881
- isStaticArray: l.isStaticArray,
949
+ isStaticArray: clientIsStaticArray,
882
950
  useElementReconciliation,
883
951
  innerLoops: (useElementReconciliation || (l.isStaticArray && innerLoops?.length)) ? innerLoops : undefined,
884
952
  offset: resolveLoopOffset(siblingOffsets.get(l)),
@@ -1565,6 +1633,17 @@ export function collectLoopChildConditionals(
1565
1633
  // accessors; classifyReactivity sees all three paths (signal/memo/prop
1566
1634
  // + loop-param + loop-index, #2861).
1567
1635
  if (!readsPreamble && classifyReactivity(expanded.expr, ctx, scope, expanded.freeIds).kind === 'none') return
1636
+ // #2897 follow-up: does the condition read anything beyond the loop
1637
+ // item/index? `classifyReactivity`'s `kind` can't answer this — it
1638
+ // reports `'loop-param'` first whenever a loop-bound name appears,
1639
+ // even alongside a signal read (`item.x && flag()`), which is the
1640
+ // right precedence for its own two typed callers but the wrong
1641
+ // question here. Computed independently so a static array's
1642
+ // escalation decision (`collect-elements.ts`'s `loop:` visitor) can
1643
+ // ask "can this branch decision change after first render" instead
1644
+ // of "does this touch the loop param at all" — see
1645
+ // `LoopChildConditional.reactiveBeyondLoopScope`'s doc comment.
1646
+ const reactiveBeyondLoopScope = n.reactive || readsPreamble || needsEffectWrapper(expanded.expr, ctx, expanded.freeIds)
1568
1647
 
1569
1648
  const loopParamsForCond =
1570
1649
  loopParams ?? (loopParam ? [{ param: loopParam, bindings: loopParamBindings, index: loopIndex }] : undefined)
@@ -1583,6 +1662,7 @@ export function collectLoopChildConditionals(
1583
1662
  whenFalse: summarizeLoopChildBranch(n.whenFalse, ctx, siblingOffsets, loopParam, loopParamBindings, preambleNames, loopIndex),
1584
1663
  ...(expanded.freeIds !== undefined && { conditionFreeIdentifiers: expanded.freeIds }),
1585
1664
  ...(readsPreamble && { readsPreamble: true }),
1665
+ reactiveBeyondLoopScope,
1586
1666
  })
1587
1667
  },
1588
1668
  })
@@ -18,7 +18,7 @@
18
18
  */
19
19
 
20
20
  import type { IRLoopChildComponent, MapCallbackPreamble } from '../../types.ts'
21
- import type { ClientJsContext, NestedLoop, TopLevelLoop } from '../types.ts'
21
+ import type { ClientJsContext, LoopChildReactiveAttr, NestedLoop, TopLevelLoop } from '../types.ts'
22
22
  import { quotePropName, varSlotId, attrValueToString, buildLoopChildIndexExpr } from '../utils.ts'
23
23
  import { jsxChildrenPropGetterExpr, renderPreamble, irToHtmlTemplate } from '../html-template.ts'
24
24
 
@@ -34,7 +34,7 @@ function staticPreludeStatements(preamble: MapCallbackPreamble | undefined): str
34
34
  })]
35
35
  : []
36
36
  }
37
- import { buildCompSelector } from '../control-flow/shared.ts'
37
+ import { buildCompSelector, buildStaticChildRefBindings } from '../control-flow/shared.ts'
38
38
 
39
39
  /** The inline prop shape carried on `IRLoopChildComponent.props`. */
40
40
  type LoopChildCompProp = IRLoopChildComponent['props'][number]
@@ -66,25 +66,47 @@ export function buildStaticArrayChildInitsPlan(
66
66
  if (comp.loopDepth) continue // handled in inner-loop pass
67
67
  plans.push(buildOuterNestedPlan(elem, comp))
68
68
  }
69
+ }
70
+
71
+ if (!elem.innerLoops) continue
69
72
 
70
- if (elem.innerLoops) {
71
- for (const innerLoop of elem.innerLoops) {
72
- const innerComps = elem.nestedComponents.filter(c =>
73
- (c.loopDepth ?? 0) === innerLoop.depth && c.innerLoopArray === innerLoop.array,
74
- )
75
- if (innerComps.length === 0) continue
76
- // Component-rooted outer item (#1725): the inner `.map()` lives
77
- // inside the child component's JSX children. The element-offset
78
- // addressing of `inner-loop-nested` can't reach a fragment-rooted
79
- // passthrough's flattened items, so use the document-order zip
80
- // shape instead.
81
- plans.push(
82
- elem.childComponent
83
- ? buildComponentRootedInnerLoopPlan(elem, innerLoop, innerComps)
84
- : buildInnerLoopNestedPlan(elem, innerLoop, innerComps),
85
- )
86
- }
73
+ for (const innerLoop of elem.innerLoops) {
74
+ const innerComps = (elem.nestedComponents ?? []).filter(c =>
75
+ (c.loopDepth ?? 0) === innerLoop.depth && c.innerLoopArray === innerLoop.array,
76
+ )
77
+
78
+ if (elem.childComponent) {
79
+ // Component-rooted outer item (#1725): the inner `.map()` lives
80
+ // inside the child component's JSX children. The element-offset
81
+ // addressing of `inner-loop-nested` can't reach a fragment-rooted
82
+ // passthrough's flattened items, so use the document-order zip
83
+ // shape instead. (Plain-element bindings on a component-rooted
84
+ // inner loop aren't addressed by this shape either — out of scope
85
+ // here, same as this shape's existing filter/sort limitation.)
86
+ if (innerComps.length === 0) continue
87
+ plans.push(buildComponentRootedInnerLoopPlan(elem, innerLoop, innerComps))
88
+ continue
87
89
  }
90
+
91
+ // Plain-element-rooted outer item: `inner-loop-nested`'s element-offset
92
+ // addressing also wires up a plain element's own reactive attrs/texts/
93
+ // refs inside the inner loop (#2798) — previously this whole pass only
94
+ // ever ran for depth-N CHILD COMPONENTS (gated behind
95
+ // `elem.nestedComponents.length > 0` with an `innerComps.length === 0`
96
+ // skip), so a static outer array's nested `.map()` over plain elements
97
+ // wired up NOTHING: no ref invocation, no reactive text/attr effect,
98
+ // even though the outer row's OWN bindings at this same depth-0 level
99
+ // are faithfully wired (`buildStaticLoopPlan`'s `childRefs`/`texts`/
100
+ // `attrsBySlot`). Scoped to depth 1 — `NestedLoop` has no parent link
101
+ // to thread a second offset through for depth ≥ 2, and the inner
102
+ // array expression there reads the depth-1 param, so a flat emission
103
+ // would `ReferenceError`; deeper nesting stays a known limitation.
104
+ if (innerLoop.depth !== 1) continue
105
+ const hasPlainBindings = innerLoop.bindings.refs.length > 0
106
+ || innerLoop.bindings.reactiveTexts.length > 0
107
+ || innerLoop.bindings.reactiveAttrs.length > 0
108
+ if (innerComps.length === 0 && !hasPlainBindings) continue
109
+ plans.push(buildInnerLoopNestedPlan(elem, innerLoop, innerComps))
88
110
  }
89
111
  }
90
112
 
@@ -147,6 +169,21 @@ function buildInnerLoopNestedPlan(
147
169
  propsExpr: buildStaticPropsExpr(comp.props),
148
170
  }))
149
171
 
172
+ // Plain-element bindings (#2798) — grouped/passed the same way
173
+ // `buildStaticLoopPlan` handles the OUTER row's own bindings: `forEach`
174
+ // binds the param as the raw item value, so texts/attrs stay unwrapped
175
+ // (no signal-accessor rewrite) and refs go through
176
+ // `buildStaticChildRefBindings`, not `buildChildRefBindings`.
177
+ const attrsBySlotMap = new Map<string, LoopChildReactiveAttr[]>()
178
+ for (const attr of innerLoop.bindings.reactiveAttrs) {
179
+ let bucket = attrsBySlotMap.get(attr.childSlotId)
180
+ if (!bucket) {
181
+ bucket = []
182
+ attrsBySlotMap.set(attr.childSlotId, bucket)
183
+ }
184
+ bucket.push(attr)
185
+ }
186
+
150
187
  return {
151
188
  kind: 'inner-loop-nested',
152
189
  containerVar: `_${varSlotId(elem.slotId)}`,
@@ -163,6 +200,9 @@ function buildInnerLoopNestedPlan(
163
200
  innerPreludeStatements: staticPreludeStatements(innerLoop.preamble),
164
201
  depth: innerLoop.depth,
165
202
  comps,
203
+ attrsBySlot: [...attrsBySlotMap].map(([slotId, attrs]) => [slotId, attrs] as const),
204
+ texts: innerLoop.bindings.reactiveTexts,
205
+ refs: buildStaticChildRefBindings(innerLoop.bindings.refs),
166
206
  }
167
207
  }
168
208
 
@@ -7,7 +7,9 @@
7
7
  * - `outer-nested` — depth 0 の `nestedComponents`。outer forEach で
8
8
  * `__iterEl.querySelector(...)` 経由で initChild。
9
9
  * - `inner-loop-nested` — depth > 0 の `nestedComponents`。outer + inner
10
- * forEach の二重ループで initChild。
10
+ * forEach の二重ループで initChild。同じ二重ループで
11
+ * プレーン要素の ref / reactive text / reactive attr
12
+ * も配線する (#2798、depth 1 のみ)。
11
13
  * - `component-rooted-inner-loop`
12
14
  * — outer の loop item root が **child component**
13
15
  * (`loop.childComponent`) で、その JSX children に
@@ -24,6 +26,8 @@
24
26
  */
25
27
 
26
28
  import type { PreludeStatements } from '../control-flow/plan/inner-loop.ts'
29
+ import type { LoopChildRefBinding } from '../control-flow/plan/loop.ts'
30
+ import type { LoopChildReactiveAttr, LoopChildReactiveText } from '../types.ts'
27
31
 
28
32
  /** Pre-built `{ name: value, ... }` props object expression. */
29
33
  export type PropsExpr = string
@@ -143,6 +147,20 @@ export interface InnerLoopNestedInitPlan {
143
147
  depth: number
144
148
  /** Per-component initialisers emitted inside the inner forEach body. */
145
149
  comps: readonly InnerLoopComp[]
150
+ /**
151
+ * Reactive attrs on plain elements inside this inner loop's body,
152
+ * grouped by child slot id (#2798 — a static outer array's nested
153
+ * `.map()` over plain elements used to wire up NOTHING: no refs, no
154
+ * reactive text/attr effects, since the whole `elem.innerLoops` pass
155
+ * only ever ran for depth-N CHILD COMPONENTS). Only populated for a
156
+ * depth-1 inner loop under a plain-element-rooted outer item — see
157
+ * `buildStaticArrayChildInitsPlan`'s docstring.
158
+ */
159
+ attrsBySlot: ReadonlyArray<readonly [string, readonly LoopChildReactiveAttr[]]>
160
+ /** Reactive text interpolations inside this inner loop's body (#2798). */
161
+ texts: readonly LoopChildReactiveText[]
162
+ /** Imperative ref callbacks on elements inside this inner loop's body (#2798). */
163
+ refs: readonly LoopChildRefBinding[]
146
164
  }
147
165
 
148
166
  /**
@@ -58,6 +58,10 @@ import type {
58
58
  StaticArrayChildInitsPlan,
59
59
  } from '../plan/static-array-child-init.ts'
60
60
  import { nameForRegistryRef } from '../component-scope.ts'
61
+ import { varSlotId } from '../utils.ts'
62
+ import { emitDedupedAttrUpdate, DEDUP_STORE_DECL } from '../emit-reactive.ts'
63
+ import { claimPlanLiteral, claimWriterVarName, type ClaimSlotSpec } from '../control-flow/stringify/claim-plan.ts'
64
+ import { emitLoopChildRefs } from '../control-flow/stringify/loop.ts'
61
65
 
62
66
  export function stringifyStaticArrayChildInits(
63
67
  lines: string[],
@@ -142,6 +146,9 @@ function emitInnerLoopNested(lines: string[], plan: InnerLoopNestedInitPlan): vo
142
146
  innerPreludeStatements,
143
147
  depth,
144
148
  comps,
149
+ attrsBySlot,
150
+ texts,
151
+ refs,
145
152
  } = plan
146
153
  lines.push(` // Initialize inner-loop components in static array (depth ${depth})`)
147
154
  lines.push(` if (${containerVar}) {`)
@@ -174,6 +181,38 @@ function emitInnerLoopNested(lines: string[], plan: InnerLoopNestedInitPlan): vo
174
181
  lines.push(` const ${compElVar} = qsaChildScope(__innerEl, ${comp.selector})`)
175
182
  lines.push(` if (${compElVar}) initChild('${nameForRegistryRef(comp.componentName)}', ${compElVar}, ${comp.propsExpr})`)
176
183
  })
184
+ // Plain-element reactive attrs / texts / refs inside this inner loop's
185
+ // body (#2798) — mirrors `stringifyStaticLoop`'s own per-row wiring for
186
+ // the OUTER static loop, one nesting level in. `forEach` binds
187
+ // `innerParam` as the raw item value, so `texts`/`attrsBySlot`
188
+ // expressions stay unwrapped, same as the outer row.
189
+ if (attrsBySlot.length > 0) lines.push(` ${DEDUP_STORE_DECL}`)
190
+ let ordinal = 0
191
+ for (const [slotId, attrs] of attrsBySlot) {
192
+ const varName = `__t_${varSlotId(slotId)}`
193
+ lines.push(` const ${varName} = qsa(__innerEl, '[bf="${slotId}"]')`)
194
+ lines.push(` if (${varName}) {`)
195
+ for (const attr of attrs) {
196
+ lines.push(` createEffect(() => {`)
197
+ for (const stmt of emitDedupedAttrUpdate(varName, attr.attrName, attr.expression, attr, ordinal++)) {
198
+ lines.push(` ${stmt}`)
199
+ }
200
+ lines.push(` })`)
201
+ }
202
+ lines.push(` }`)
203
+ }
204
+ if (texts.length > 0) {
205
+ const slots: ClaimSlotSpec[] = texts.map(t => ({ id: t.slotId, kind: 'text', path: [] }))
206
+ const writer = claimWriterVarName(slots, varSlotId)
207
+ lines.push(` const ${writer} = lazySlots(__innerEl, ${claimPlanLiteral(slots)})`)
208
+ for (const text of texts) {
209
+ lines.push(` createEffect(() => { ${writer}('${text.slotId}', String(${text.expression})) })`)
210
+ }
211
+ }
212
+ // Ref callbacks fire on every forEach iteration — initial mount and any
213
+ // future array-change-driven re-iteration. For a static array the array
214
+ // is non-reactive, so refs effectively fire once per item (#1244).
215
+ emitLoopChildRefs(lines, refs, { indent: ' ', elVar: '__innerEl', bodyIsMultiRoot: false })
177
216
  lines.push(` })`)
178
217
  lines.push(` })`)
179
218
  lines.push(` }`)
@@ -625,6 +625,31 @@ export interface LoopChildConditional {
625
625
  * preamble-bound identifier unexpanded on purpose (#2482 Stage 1b).
626
626
  */
627
627
  readsPreamble?: boolean
628
+ /**
629
+ * `condition` can change value after first render — it reads a signal,
630
+ * memo, prop, or preamble-derived reactive local, as opposed to reading
631
+ * ONLY the (for a static array, fixed-forever) loop item/index (#2897
632
+ * follow-up). `classifyReactivity`'s `kind` can't answer this: it
633
+ * reports `'loop-param'` for ANY expression referencing a loop-bound
634
+ * name, even one that ALSO reads a signal (`item.x && flag()`) — that
635
+ * precedence is deliberate for its own two `ReactivitySource`-typed
636
+ * callers and must not change. This field is computed independently,
637
+ * at collection time, as `n.reactive || readsPreamble ||
638
+ * needsEffectWrapper(...)` — the same "does it need a patchable slot
639
+ * beyond the row's own item" question, without the loop-param
640
+ * short-circuit.
641
+ *
642
+ * Consumers: a static array's row/inner-loop conditional only needs
643
+ * escalation off the compile-time-bakeable static path when THIS is
644
+ * true — a condition that reads only the item/index never changes for
645
+ * a static array, so the row's branch decision (bare element OR child
646
+ * component) is correctly baked once by SSR and wired once by the
647
+ * static `initChild` pass, exactly as it was before #2897. A dynamic
648
+ * (signal-backed) array's `mapArray`/`insert()` path is unaffected by
649
+ * this field — every loop-param conditional is genuinely per-row
650
+ * reactive there, so `bindings.conditionals` itself is never filtered.
651
+ */
652
+ reactiveBeyondLoopScope: boolean
628
653
  }
629
654
 
630
655
  export interface TopLevelLoop extends LoopCore {
@@ -673,7 +698,18 @@ export interface TopLevelLoop extends LoopCore {
673
698
  nestedComponents?: IRLoopChildComponent[] // For nested components in loop bodies
674
699
  // Per-item bindings (events / reactiveAttrs / reactiveTexts / refs / conditionals)
675
700
  // now live on `LoopCore.bindings` — see issue #1244 §B.
676
- isStaticArray: boolean // True if array is a static prop (not a signal)
701
+ // True when this loop takes the static forEach fast path — the IR's own
702
+ // `isStaticArray` (a static, non-signal array) MINUS a fast-path refusal
703
+ // (#2897): a conditional anywhere in the row tree (this row's own
704
+ // `bindings.conditionals`, or any depth-1 `innerLoops[i].bindings.conditionals`)
705
+ // forces this false even when the IR flag is true, since neither the static
706
+ // forEach bake nor `inner-loop-nested`'s clone-and-wire architecture has any
707
+ // conditional-handling machinery — the row falls through to the plain/
708
+ // composite dynamic path instead, which already wires a conditional's live
709
+ // branch-swap correctly. SSR adapters (e.g. Go template's static-loop
710
+ // baking) read the IR-level `isStaticArray` directly and are unaffected;
711
+ // this field is client-JS routing only.
712
+ isStaticArray: boolean
677
713
  useElementReconciliation?: boolean // True: mapArray/mapArrayAnchored + composite rendering (native root with child components)
678
714
  /** Inner loop metadata for composite element reconciliation (array, param, key, container) */
679
715
  innerLoops?: NestedLoop[]
package/src/jsx-to-ir.ts CHANGED
@@ -49,6 +49,7 @@ import { containsReactiveExpression, collectReactiveBrandLeaves } from './reacti
49
49
  import {
50
50
  rewriteBarePropRefs as rewriteBarePropRefsCore,
51
51
  collectAstPropRefs,
52
+ rewriteScopedValueRefs,
52
53
  } from './prop-rewrite.ts'
53
54
  import { boundPropLocalNames, buildPropAliasMap, resolveAliasOrigin, resolveRestSpreadOriginCore } from './props-binding.ts'
54
55
  import { resolveFreeRefs, isNameBound as isNameBoundInEnv, type BindingEnvironment } from './free-refs.ts'
@@ -8456,10 +8457,19 @@ function inferExpressionType(
8456
8457
 
8457
8458
  /**
8458
8459
  * Substitute branch-local identifier references in `text` with the
8459
- * value returned by `resolve(name)`. Skips occurrences inside string
8460
- * / regex / template-body / comment tokens via the shared
8461
- * `replaceInExprContexts` scanner, so a string like `'mergedClass'`
8462
- * never gets rewritten into invalid JS. Identifier boundaries use
8460
+ * value returned by `resolve(name)`. Tries the AST-based, scope-aware
8461
+ * `rewriteScopedValueRefs` (`prop-rewrite.ts`) first — it correctly
8462
+ * expands an object-literal shorthand property (`{ local }`) to
8463
+ * `{ local: <resolved> }` instead of corrupting it to `{ (<resolved>) }`
8464
+ * (#2856), and understands inner-scope shadowing. `allowStatements`
8465
+ * covers raw-captured text that isn't guaranteed to be a bare
8466
+ * expression (e.g. a `.map()`-callback preamble statement).
8467
+ *
8468
+ * Falls back to the legacy `replaceInExprContexts` scanner — which
8469
+ * skips occurrences inside string / regex / template-body / comment
8470
+ * tokens, so a string like `'mergedClass'` never gets rewritten into
8471
+ * invalid JS, but has no notion of AST position — only when `text`
8472
+ * doesn't parse under either attempt. Identifier boundaries use
8463
8473
  * `[\w$]` lookarounds rather than `\b`, since JS regex's word-char
8464
8474
  * class excludes `$` — a bare `\b` would mis-match the `foo` inside
8465
8475
  * `$foo`. Branch-local names are syntactically `[A-Za-z_$][A-Za-z0-9_$]*`
@@ -8478,6 +8488,8 @@ function replaceBranchLocalRefs(
8478
8488
  resolve: (name: string) => string,
8479
8489
  ): string {
8480
8490
  if (branchNames.length === 0) return text
8491
+ const astResult = rewriteScopedValueRefs(text, new Set(branchNames), resolve, { allowStatements: true })
8492
+ if (astResult !== null) return astResult
8481
8493
  const pattern = new RegExp(`(?<![\\w$])(${branchNames.join('|')})(?![\\w$])`, 'g')
8482
8494
  return replaceInExprContexts(text, pattern, (_match, name) => resolve(name))
8483
8495
  }
@@ -89,8 +89,16 @@ function walkWithScope(
89
89
  /**
90
90
  * True when `n` sits in a non-value position where a prop rewrite must
91
91
  * never apply: an object-literal key, a member-access name, a binding
92
- * position (parameter / variable / binding-element name), or a type
93
- * reference.
92
+ * position (parameter / variable / binding-element name), a destructuring
93
+ * declaration's SOURCE key (`propertyName`, e.g. the `local` in
94
+ * `const { local: renamed } = obj`), or a type reference.
95
+ *
96
+ * The `propertyName` check matters even though `BindingElement.name` is
97
+ * already excluded above it: a renamed destructuring pattern has BOTH —
98
+ * `propertyName` is the source key (`local`) and `name` is the local
99
+ * binding (`renamed`) — and pullfrog review on #2889 caught that only the
100
+ * latter was excluded, so a substituted name colliding with the SOURCE key
101
+ * still corrupted to invalid JS (`const { (_p.tag): renamed } = obj`).
94
102
  */
95
103
  function isNonValuePosition(n: ts.Identifier, parent: ts.Node | undefined): boolean {
96
104
  if (!parent) return false
@@ -98,6 +106,7 @@ function isNonValuePosition(n: ts.Identifier, parent: ts.Node | undefined): bool
98
106
  if (ts.isPropertyAccessExpression(parent) && parent.name === n) return true
99
107
  if (ts.isQualifiedName(parent) && parent.right === n) return true
100
108
  if ((ts.isParameter(parent) || ts.isVariableDeclaration(parent) || ts.isBindingElement(parent)) && parent.name === n) return true
109
+ if (ts.isBindingElement(parent) && parent.propertyName === n) return true
101
110
  if (ts.isTypeReferenceNode(parent)) return true
102
111
  return false
103
112
  }
@@ -130,49 +139,54 @@ export function collectAstPropRefs(
130
139
 
131
140
  /**
132
141
  * Scope-aware rewrite: parse `text` as an expression, walk it with the
133
- * binding stack, and splice `${PROPS_PARAM}.` onto exactly the
134
- * identifier references that are (a) in `propRefs` and (b) not
135
- * shadowed by a binding inside the text. Shorthand properties expand
136
- * (`{ org }` → `{ org: _p.org }`) so the result stays syntactically
137
- * valid.
142
+ * binding stack, and splice `replacementFor(name)` onto exactly the
143
+ * identifier references that are (a) in `names` and (b) not shadowed by
144
+ * a binding inside the text. Shorthand properties expand
145
+ * (`{ org }` → `{ org: <replacement> }`) so the result stays
146
+ * syntactically valid — this is the one place in the compiler that
147
+ * correctly distinguishes a value reference from an object-literal key
148
+ * / property-access name / shorthand property / binding name, so every
149
+ * caller doing this class of substitution (prop refs, #1425 branch-local
150
+ * refs, …) should route through this rather than growing its own
151
+ * regex-based text splice (#2856 — a second, regex-based substitution
152
+ * mechanism doesn't know shorthand is simultaneously a key and a value,
153
+ * and drops the key).
138
154
  *
139
- * `replacementFor` overrides the substitution text for a value
140
- * reference (default `${PROPS_PARAM}.<callerKey>`) — e.g. the reactive
141
- * client-JS emit path (`emit-reactive.ts`'s `rewriteDestructuredPropsInExpr`)
142
- * wraps it in a `(_p.x ?? <default>)` fallback for a prop with a
143
- * destructure default. Kept as a caller override rather than a
144
- * duplicate AST walk in that module, per the "one decision, one
145
- * implementation" rule (CLAUDE.md) — this walk is already the one place
146
- * that correctly distinguishes a value reference from an object-literal
147
- * key / property-access name / shorthand property / binding name.
155
+ * With `allowStatements`, a `text` that fails to parse as a bare
156
+ * expression is retried as a standalone statement list (no wrapping
157
+ * parens) — for callers whose raw-captured text isn't guaranteed to be
158
+ * expression-shaped (e.g. a `.map()`-callback preamble statement).
148
159
  *
149
- * Returns null when `text` does not parse cleanly as an expression —
150
- * the caller falls back to the legacy regex rewrite.
160
+ * Returns null when `text` doesn't parse cleanly under either attempt —
161
+ * the caller falls back to its own legacy mechanism.
151
162
  */
152
- function applyScopedPropRefRewrite(
163
+ export function rewriteScopedValueRefs(
153
164
  text: string,
154
- propRefs: Set<string>,
155
- propAliases?: ReadonlyMap<string, string>,
156
- replacementFor?: (localName: string, callerKey: string) => string,
165
+ names: ReadonlySet<string>,
166
+ replacementFor: (name: string) => string,
167
+ opts?: { allowStatements?: boolean },
157
168
  ): string | null {
158
169
  // Wrap in parens so object literals and arrows parse as expressions.
159
170
  const prefix = '('
160
- const sf = ts.createSourceFile('__bf_prop_rewrite.ts', `${prefix}${text}\n)`, ts.ScriptTarget.Latest, true)
161
- const parseDiagnostics = (sf as unknown as { parseDiagnostics?: unknown[] }).parseDiagnostics
162
- if (parseDiagnostics && parseDiagnostics.length > 0) return null
171
+ let sf = ts.createSourceFile('__bf_scoped_rewrite.ts', `${prefix}${text}\n)`, ts.ScriptTarget.Latest, true)
172
+ let parseDiagnostics = (sf as unknown as { parseDiagnostics?: unknown[] }).parseDiagnostics
173
+ let usedPrefix = prefix
174
+ if (parseDiagnostics && parseDiagnostics.length > 0) {
175
+ if (!opts?.allowStatements) return null
176
+ sf = ts.createSourceFile('__bf_scoped_rewrite.ts', text, ts.ScriptTarget.Latest, true)
177
+ parseDiagnostics = (sf as unknown as { parseDiagnostics?: unknown[] }).parseDiagnostics
178
+ if (parseDiagnostics && parseDiagnostics.length > 0) return null
179
+ usedPrefix = ''
180
+ }
163
181
 
164
182
  const edits: Array<{ start: number; end: number; replacement: string }> = []
165
183
  walkWithScope(sf, (n, parent, shadowed) => {
166
- if (shadowed || !propRefs.has(n.text)) return
184
+ if (shadowed || !names.has(n.text)) return
167
185
  if (isNonValuePosition(n, parent)) return
168
- const start = n.getStart(sf) - prefix.length
169
- const end = n.getEnd() - prefix.length
186
+ const start = n.getStart(sf) - usedPrefix.length
187
+ const end = n.getEnd() - usedPrefix.length
170
188
  if (start < 0 || end > text.length) return
171
- // `_p` is always keyed by the caller-facing name (`sourceName ?? name`
172
- // — #2524 CSR half); the local binding (`n.text`) only survives on the
173
- // left of a shorthand expansion.
174
- const callerKey = propAliases?.get(n.text) ?? n.text
175
- const value = replacementFor ? replacementFor(n.text, callerKey) : `${PROPS_PARAM}.${callerKey}`
189
+ const value = replacementFor(n.text)
176
190
  if (parent && ts.isShorthandPropertyAssignment(parent) && parent.name === n) {
177
191
  edits.push({ start, end, replacement: `${n.text}: ${value}` })
178
192
  return
@@ -188,6 +202,33 @@ function applyScopedPropRefRewrite(
188
202
  return result
189
203
  }
190
204
 
205
+ /**
206
+ * `applyScopedPropRefRewrite` specializes `rewriteScopedValueRefs` for
207
+ * the destructured-prop case: the substitution defaults to
208
+ * `${PROPS_PARAM}.<callerKey>`, where the caller-facing key comes from
209
+ * `propAliases` (`_p` is always keyed by the caller-facing name —
210
+ * `sourceName ?? name`, #2524 CSR half — the local binding only
211
+ * survives on the left of a shorthand expansion).
212
+ *
213
+ * `replacementFor` overrides the substitution text for a value
214
+ * reference — e.g. the reactive client-JS emit path
215
+ * (`emit-reactive.ts`'s `rewriteDestructuredPropsInExpr`) wraps it in a
216
+ * `(_p.x ?? <default>)` fallback for a prop with a destructure default.
217
+ * Kept as a caller override rather than a duplicate AST walk in that
218
+ * module, per the "one decision, one implementation" rule (CLAUDE.md).
219
+ */
220
+ function applyScopedPropRefRewrite(
221
+ text: string,
222
+ propRefs: Set<string>,
223
+ propAliases?: ReadonlyMap<string, string>,
224
+ replacementFor?: (localName: string, callerKey: string) => string,
225
+ ): string | null {
226
+ return rewriteScopedValueRefs(text, propRefs, (name) => {
227
+ const callerKey = propAliases?.get(name) ?? name
228
+ return replacementFor ? replacementFor(name, callerKey) : `${PROPS_PARAM}.${callerKey}`
229
+ })
230
+ }
231
+
191
232
  /**
192
233
  * Apply the targeted regex rewrite for one or more prop names on a
193
234
  * type-stripped expression text. Idempotent under `_p.X` (negative