@barefootjs/jsx 0.18.4 → 0.18.7

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 (109) hide show
  1. package/dist/adapters/dangerous-inner-html.d.ts +77 -0
  2. package/dist/adapters/dangerous-inner-html.d.ts.map +1 -0
  3. package/dist/adapters/loop-bound-names.d.ts +22 -0
  4. package/dist/adapters/loop-bound-names.d.ts.map +1 -0
  5. package/dist/adapters/parsed-expr-emitter.d.ts +2 -2
  6. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  7. package/dist/analyzer.d.ts.map +1 -1
  8. package/dist/expression-parser.d.ts +2 -1
  9. package/dist/expression-parser.d.ts.map +1 -1
  10. package/dist/index.d.ts +14 -4
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1108 -307
  13. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  14. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  15. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  16. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -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/event-delegation.d.ts +10 -0
  19. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  20. package/dist/ir-to-client-js/control-flow/plan/loop-child-arm.d.ts +9 -0
  21. package/dist/ir-to-client-js/control-flow/plan/loop-child-arm.d.ts.map +1 -1
  22. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +9 -0
  23. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/shared.d.ts +45 -3
  25. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/control-flow/stringify/loop-child-arm.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts +1 -0
  29. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/stringify/reactive-effects.d.ts +10 -0
  31. package/dist/ir-to-client-js/control-flow/stringify/reactive-effects.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/stringify/skeleton-paths.d.ts +38 -0
  33. package/dist/ir-to-client-js/control-flow/stringify/skeleton-paths.d.ts.map +1 -0
  34. package/dist/ir-to-client-js/control-flow/stringify/template-parse.d.ts +19 -0
  35. package/dist/ir-to-client-js/control-flow/stringify/template-parse.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/csr-substitute.d.ts +24 -0
  37. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/html-template.d.ts +42 -0
  39. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/imports.d.ts +2 -2
  41. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +20 -1
  43. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -1
  46. package/dist/ir-to-client-js/types.d.ts +30 -0
  47. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/utils.d.ts +25 -0
  49. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  50. package/dist/jsx-to-ir.d.ts.map +1 -1
  51. package/dist/signal-init-eval.d.ts +82 -0
  52. package/dist/signal-init-eval.d.ts.map +1 -0
  53. package/dist/static-literal.d.ts +45 -0
  54. package/dist/static-literal.d.ts.map +1 -0
  55. package/dist/types.d.ts +66 -0
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +2 -2
  58. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +19 -13
  59. package/src/__tests__/create-selector.test.ts +110 -0
  60. package/src/__tests__/csr-template-loop-shadowing.test.ts +214 -0
  61. package/src/__tests__/dangerous-inner-html-resolver.test.ts +197 -0
  62. package/src/__tests__/event-delegation-index-param.test.ts +130 -0
  63. package/src/__tests__/expression-parser.test.ts +38 -0
  64. package/src/__tests__/inner-loop-svg-namespace.test.ts +245 -0
  65. package/src/__tests__/ir-walker.test.ts +1 -0
  66. package/src/__tests__/loop-bound-names.test.ts +102 -0
  67. package/src/__tests__/loop-plan-classification.test.ts +2 -0
  68. package/src/__tests__/map-function-reference.test.ts +303 -0
  69. package/src/__tests__/materialize-getter-calls.test.ts +1 -0
  70. package/src/__tests__/nested-loop-index-param.test.ts +285 -0
  71. package/src/__tests__/signal-init-eval.test.ts +138 -0
  72. package/src/__tests__/static-array-inner-loop-index-param.test.ts +180 -0
  73. package/src/__tests__/static-literal.test.ts +126 -0
  74. package/src/__tests__/string-concat-identifier.test.ts +55 -0
  75. package/src/adapters/dangerous-inner-html.ts +186 -0
  76. package/src/adapters/loop-bound-names.ts +80 -0
  77. package/src/adapters/parsed-expr-emitter.ts +19 -1
  78. package/src/analyzer.ts +6 -0
  79. package/src/expression-parser.ts +59 -25
  80. package/src/index.ts +19 -3
  81. package/src/ir-to-client-js/collect-elements.ts +18 -3
  82. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +6 -0
  83. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +21 -4
  84. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +13 -1
  85. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +1 -0
  86. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +10 -0
  87. package/src/ir-to-client-js/control-flow/plan/loop-child-arm.ts +9 -0
  88. package/src/ir-to-client-js/control-flow/plan/loop.ts +9 -0
  89. package/src/ir-to-client-js/control-flow/shared.ts +103 -6
  90. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +31 -7
  91. package/src/ir-to-client-js/control-flow/stringify/inner-loop.ts +11 -2
  92. package/src/ir-to-client-js/control-flow/stringify/loop-child-arm.ts +5 -0
  93. package/src/ir-to-client-js/control-flow/stringify/loop.ts +53 -10
  94. package/src/ir-to-client-js/control-flow/stringify/reactive-effects.ts +25 -4
  95. package/src/ir-to-client-js/control-flow/stringify/skeleton-paths.ts +70 -0
  96. package/src/ir-to-client-js/control-flow/stringify/template-parse.ts +25 -1
  97. package/src/ir-to-client-js/csr-substitute.ts +54 -1
  98. package/src/ir-to-client-js/html-template.ts +292 -13
  99. package/src/ir-to-client-js/imports.ts +1 -0
  100. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +12 -1
  101. package/src/ir-to-client-js/plan/static-array-child-init.ts +20 -1
  102. package/src/ir-to-client-js/reactivity.ts +6 -0
  103. package/src/ir-to-client-js/stringify/static-array-child-init.ts +11 -6
  104. package/src/ir-to-client-js/types.ts +31 -0
  105. package/src/ir-to-client-js/utils.ts +34 -1
  106. package/src/jsx-to-ir.ts +322 -48
  107. package/src/signal-init-eval.ts +165 -0
  108. package/src/static-literal.ts +128 -0
  109. package/src/types.ts +68 -0
@@ -6,7 +6,8 @@ import { type IRNode, type IRElement, type IRComponent, type IRLoop, type IRProp
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 } from './utils.ts'
8
8
  import { classifyReactivity, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings } from './reactivity.ts'
9
- import { irToHtmlTemplate, irToPlaceholderTemplate, irChildrenToJsExpr, buildLoopSkeletonTemplate } from './html-template.ts'
9
+ import { irToHtmlTemplate, irToPlaceholderTemplate, irChildrenToJsExpr, buildLoopSkeletonTemplate, computeSkeletonSlotPaths, type SkeletonSlotPaths } from './html-template.ts'
10
+ import { templateRootIsSvg } from './control-flow/stringify/template-parse.ts'
10
11
  import { expandDynamicPropValue, expandConstantForReactivity } from './prop-handling.ts'
11
12
  import { walkIR, stopAt } from './walker.ts'
12
13
  import { buildLoopChainExpr } from '../loop-chain.ts'
@@ -385,11 +386,13 @@ export function collectInnerLoops(
385
386
  arrayFreeIdentifiers: n.arrayFreeIdentifiers,
386
387
  param: n.param,
387
388
  paramBindings: n.paramBindings,
389
+ index: n.index,
388
390
  key: n.key,
389
391
  markerId: n.markerId,
390
392
  bodyIsMultiRoot: n.bodyIsMultiRoot,
391
393
  bodyIsItemConditional: n.bodyIsItemConditional,
392
394
  iterationShape: n.iterationShape,
395
+ objectIteration: n.objectIteration,
393
396
  containerSlotId: scope.parentSlotId,
394
397
  template,
395
398
  mapPreamble: n.mapPreamble,
@@ -672,6 +675,7 @@ export function collectElements(
672
675
  let template = ''
673
676
  let staticItemTemplate: string | undefined
674
677
  let skeletonTemplate: string | undefined
678
+ let skeletonPaths: SkeletonSlotPaths | undefined
675
679
  if (l.childComponent) {
676
680
  template = '' // childComponent path uses createComponent directly
677
681
  // CSR materialize fallback (#1268): when the loop array references an
@@ -723,10 +727,18 @@ export function collectElements(
723
727
  // expressions, …) and returns `null` for anything it can't prove
724
728
  // safe; the plan builder (`build-loop.ts`) falls back to the
725
729
  // per-row `template` above whenever this stays `undefined`.
726
- skeletonTemplate = buildLoopSkeletonTemplate(l.children[0], {
730
+ const skeletonSafeSlots = {
727
731
  reactiveAttrKeys: new Set(bindings.reactiveAttrs.map(a => `${a.childSlotId}::${a.attrName}`)),
728
732
  reactiveTextSlotIds: new Set(bindings.reactiveTexts.map(t => t.slotId)),
729
- }) ?? undefined
733
+ }
734
+ skeletonTemplate = buildLoopSkeletonTemplate(l.children[0], skeletonSafeSlots) ?? undefined
735
+ // Direct child-index paths (perf, #2143): only attempted when the
736
+ // skeleton itself hoisted, and skipped for SVG roots for now (the
737
+ // `<svg>`-wrap namespace fix-up is orthogonal and untested against
738
+ // this path model — safe fallback to qsa/$t for those loops).
739
+ if (skeletonTemplate && !templateRootIsSvg(skeletonTemplate)) {
740
+ skeletonPaths = computeSkeletonSlotPaths(l.children[0], skeletonSafeSlots) ?? undefined
741
+ }
730
742
  }
731
743
  }
732
744
 
@@ -743,9 +755,11 @@ export function collectElements(
743
755
  bodyIsMultiRoot: l.bodyIsMultiRoot,
744
756
  bodyIsItemConditional: l.bodyIsItemConditional,
745
757
  iterationShape: l.iterationShape,
758
+ objectIteration: l.objectIteration,
746
759
  template,
747
760
  staticItemTemplate,
748
761
  skeletonTemplate,
762
+ skeletonPaths,
749
763
  childEventHandlers: childHandlers,
750
764
  bindings,
751
765
  childComponent: l.childComponent,
@@ -1096,6 +1110,7 @@ function collectBranchLoops(
1096
1110
  bodyIsMultiRoot: n.bodyIsMultiRoot,
1097
1111
  bodyIsItemConditional: n.bodyIsItemConditional,
1098
1112
  iterationShape: n.iterationShape,
1113
+ objectIteration: n.objectIteration,
1099
1114
  template: childTemplate,
1100
1115
  containerSlotId: containerSlot,
1101
1116
  mapPreamble: n.mapPreamble ?? null,
@@ -34,6 +34,7 @@ export function buildDynamicLoopDelegationPlan(
34
34
  param: elem.param,
35
35
  paramBindings: elem.paramBindings,
36
36
  key: elem.key,
37
+ index: elem.index,
37
38
  mapPreamble: elem.mapPreamble ?? null,
38
39
  }),
39
40
  }
@@ -58,6 +59,7 @@ export function buildBranchLoopDelegationPlan(
58
59
  param: loop.param,
59
60
  paramBindings: loop.paramBindings,
60
61
  key: loop.key,
62
+ index: loop.index,
61
63
  mapPreamble: loop.mapPreamble ?? null,
62
64
  }),
63
65
  }
@@ -86,6 +88,7 @@ export function buildStaticArrayDelegationPlan(
86
88
  param: elem.param,
87
89
  mapPreamble: elem.mapPreamble ?? null,
88
90
  offset: elem.offset ?? null,
91
+ indexParam: elem.index ?? null,
89
92
  },
90
93
  }
91
94
  }
@@ -99,6 +102,7 @@ function buildKeyedOrIndexLookup(args: {
99
102
  param: string
100
103
  paramBindings: TopLevelLoop['paramBindings']
101
104
  key: string | null
105
+ index: string | null
102
106
  mapPreamble: string | null
103
107
  }): ItemLookup {
104
108
  const hasBindings = (args.paramBindings?.length ?? 0) > 0
@@ -116,6 +120,7 @@ function buildKeyedOrIndexLookup(args: {
116
120
  keyWithItem,
117
121
  mapPreamble: args.mapPreamble,
118
122
  hasBindings,
123
+ indexParam: args.index,
119
124
  }
120
125
  }
121
126
  return {
@@ -124,6 +129,7 @@ function buildKeyedOrIndexLookup(args: {
124
129
  param: args.param,
125
130
  mapPreamble: args.mapPreamble,
126
131
  hasBindings,
132
+ indexParam: args.index,
127
133
  }
128
134
  }
129
135
 
@@ -58,6 +58,7 @@ import type { DepthLevel } from '../shared.ts'
58
58
  import {
59
59
  destructureLoopParam,
60
60
  loopKeyFn,
61
+ nestedLoopIndexAlias,
61
62
  } from '../shared.ts'
62
63
  import type {
63
64
  InnerLoopPlan,
@@ -114,8 +115,8 @@ export function buildInnerLoopsPlan(args: BuildInnerLoopsArgs): InnerLoopsPlan {
114
115
  const useReactive = refsParent && !!inner.template
115
116
 
116
117
  const emit: InnerLoopReactiveEmit | InnerLoopStaticEmit = useReactive
117
- ? buildReactiveEmit(inner, level, wrapOuter)
118
- : buildStaticEmit(inner, level)
118
+ ? buildReactiveEmit(inner, level, wrapOuter, uidSuffix)
119
+ : buildStaticEmit(inner, level, uidSuffix)
119
120
 
120
121
  const arrayExpr = useReactive ? wrapOuter(inner.array) : inner.array
121
122
 
@@ -153,6 +154,7 @@ function buildReactiveEmit(
153
154
  inner: NestedLoop,
154
155
  level: DepthLevel,
155
156
  wrapOuter: (expr: string) => string,
157
+ uidSuffix: string,
156
158
  ): InnerLoopReactiveEmit {
157
159
  const wrapInner = (expr: string) => wrapLoopParamAsAccessor(expr, inner.param, inner.paramBindings)
158
160
  const { head: paramHead, unwrap: paramUnwrap } = destructureLoopParam(inner.param, inner.paramBindings)
@@ -218,7 +220,14 @@ function buildReactiveEmit(
218
220
  // The destructure unwrap (when `inner.param` is a binding pattern)
219
221
  // has to land before the preamble so the preamble's bare-binding
220
222
  // references resolve.
223
+ //
224
+ // The index alias (#2218) lands first — before both the unwrap and the
225
+ // preamble — since either may reference the user's index name (e.g. a
226
+ // `const rowTag = \`row-${i}\`` preamble line), and both run before the
227
+ // cloned-template IIFE that may also reference it.
221
228
  const preludeStatements: string[] = []
229
+ const indexAlias = nestedLoopIndexAlias(inner, `__innerIdx${uidSuffix}`, paramHead, level.comps, level.events)
230
+ if (indexAlias) preludeStatements.push(indexAlias)
222
231
  if (paramUnwrap) preludeStatements.push(paramUnwrap)
223
232
  if (inner.mapPreamble) preludeStatements.push(wrapInner(wrapOuter(inner.mapPreamble)))
224
233
 
@@ -240,7 +249,7 @@ function buildReactiveEmit(
240
249
  }
241
250
  }
242
251
 
243
- function buildStaticEmit(inner: NestedLoop, level: DepthLevel): InnerLoopStaticEmit {
252
+ function buildStaticEmit(inner: NestedLoop, level: DepthLevel, uidSuffix: string): InnerLoopStaticEmit {
244
253
  // Static `forEach` iterates with the literal item as its first param, so
245
254
  // no signal-accessor rewrite is needed — emit the preamble verbatim
246
255
  // before the component/event setup so prop getters and event handlers
@@ -248,7 +257,15 @@ function buildStaticEmit(inner: NestedLoop, level: DepthLevel): InnerLoopStaticE
248
257
  // wrapping the callback would rewrite `s.x` to `s().x` and throw at
249
258
  // runtime when the callback closes over the static inner param (#1244,
250
259
  // PR #1352 Copilot review).
251
- const preludeStatements: string[] = inner.mapPreamble ? [inner.mapPreamble] : []
260
+ //
261
+ // The index alias (#2218) lands first, same rationale as the reactive
262
+ // path: `forEach`'s second param is the synthetic `__innerIdx<uid>`, not
263
+ // the user's index name, so a preamble/prop/event that reads it needs the
264
+ // alias bound before anything else runs.
265
+ const preludeStatements: string[] = []
266
+ const indexAlias = nestedLoopIndexAlias(inner, `__innerIdx${uidSuffix}`, inner.param, level.comps, level.events)
267
+ if (indexAlias) preludeStatements.push(indexAlias)
268
+ if (inner.mapPreamble) preludeStatements.push(inner.mapPreamble)
252
269
  return {
253
270
  mode: 'static',
254
271
  rawKey: inner.key ?? null,
@@ -57,7 +57,7 @@ function wrapAttrValueExpression(value: AttrValue, wrap: (s: string) => string):
57
57
  return AttrValueOf.spread(wrap(value.expr), value.templateExpr ? wrap(value.templateExpr) : undefined)
58
58
  }
59
59
  }
60
- import { destructureLoopParam, loopKeyFn, buildCompSelector } from '../shared.ts'
60
+ import { destructureLoopParam, loopKeyFn, buildCompSelector, nestedLoopIndexAlias } from '../shared.ts'
61
61
  import { BF_HOST, BF_AT } from '@barefootjs/shared'
62
62
  import type {
63
63
  BranchChildComponentInit,
@@ -269,6 +269,17 @@ export function buildBranchInnerLoopsPlan(
269
269
  handler: wrapInner(ev.handler),
270
270
  }))
271
271
 
272
+ // Index-param gating runs against the RAW (pre-wrap) component/event
273
+ // data — wrapping only rewrites loop-param references, never the
274
+ // index name, so it doesn't affect whether the index is referenced.
275
+ const indexAlias = nestedLoopIndexAlias(
276
+ inner,
277
+ `__bidxbr_${i}`,
278
+ paramHead,
279
+ inner.childComponents ?? [],
280
+ inner.bindings.events,
281
+ )
282
+
272
283
  const reactiveTexts: BranchInnerLoopText[] = inner.bindings.reactiveTexts.map(text => ({
273
284
  slotId: text.slotId,
274
285
  wrappedExpression: wrapBoth(text.expression),
@@ -286,6 +297,7 @@ export function buildBranchInnerLoopsPlan(
286
297
  keyFn: loopKeyFn(inner),
287
298
  paramHead,
288
299
  paramUnwrap,
300
+ indexAlias,
289
301
  wrappedTemplate: inner.template!,
290
302
  wrappedKey,
291
303
  keyDepth: 1,
@@ -103,6 +103,7 @@ export function buildPlainLoopPlan(elem: TopLevelLoop, profileComponentName?: st
103
103
  mapPreambleWrapped: elem.mapPreamble ? wrap(elem.mapPreamble) : '',
104
104
  template: elem.template,
105
105
  skeletonTemplate: elem.skeletonTemplate,
106
+ skeletonPaths: elem.skeletonPaths,
106
107
  reactiveEffects: hasReactive ? buildLoopReactiveEffectsPlan(elem, profileComponentName) : null,
107
108
  childRefs: buildChildRefBindings(elem.bindings.refs, elem.param, elem.paramBindings),
108
109
  bodyIsMultiRoot: elem.bodyIsMultiRoot ?? false,
@@ -51,6 +51,12 @@ export interface KeyedItemLookup {
51
51
  arrayExpr: string
52
52
  /** Loop param identifier (or destructure pattern text — used as receiver name only). */
53
53
  param: string
54
+ /**
55
+ * Loop index param name (e.g. `i` from `.map((item, i) => ...)`), or `null`.
56
+ * When a delegated handler closes over it, the stringifier re-derives the
57
+ * index at dispatch time and binds it so the reference resolves (#2189).
58
+ */
59
+ indexParam: string | null
54
60
  /** Destructured-binding metadata. Determines TDZ-safe `__bfLoopItem` shape (#951). */
55
61
  paramBindings: TopLevelLoop['paramBindings']
56
62
  /**
@@ -72,6 +78,8 @@ export interface DynamicIndexItemLookup {
72
78
  param: string
73
79
  mapPreamble: string | null
74
80
  hasBindings: boolean
81
+ /** Loop index param name — see `KeyedItemLookup.indexParam` (#2189). */
82
+ indexParam: string | null
75
83
  }
76
84
 
77
85
  export interface StaticIndexItemLookup {
@@ -79,6 +87,8 @@ export interface StaticIndexItemLookup {
79
87
  arrayExpr: string
80
88
  param: string
81
89
  mapPreamble: string | null
90
+ /** Loop index param name — see `KeyedItemLookup.indexParam` (#2189). */
91
+ indexParam: string | null
82
92
  /**
83
93
  * Offset of the loop's items past its preceding container siblings. Its
84
94
  * terms are subtracted from the DOM child index to recover the array index,
@@ -108,6 +108,15 @@ export interface BranchInnerLoop {
108
108
  paramHead: string
109
109
  /** Body-entry unwrap statement (empty when no destructured param). */
110
110
  paramUnwrap: string
111
+ /**
112
+ * Body-entry index-alias statement (#2218), or `null` when the inner
113
+ * loop declares no index param or never references it. Binds the user's
114
+ * index name to the synthetic `__bidx<uid>` renderItem param — mirrors
115
+ * `InnerLoopReactiveEmit`'s prelude alias in `plan/inner-loop.ts`. Must
116
+ * be emitted before `paramUnwrap` and the template clone, since either
117
+ * may reference the index.
118
+ */
119
+ indexAlias: string | null
111
120
  /** Already-wrapped HTML template for one inner-loop item. */
112
121
  wrappedTemplate: string
113
122
  /** Pre-wrapped key expression for setAttribute, or null when no key. */
@@ -23,6 +23,7 @@ import type {
23
23
  TopLevelLoop,
24
24
  } from '../../types.ts'
25
25
  import type { IRLoopChildComponent } from '../../../types.ts'
26
+ import type { SkeletonSlotPaths } from '../../html-template.ts'
26
27
  import type { ReactiveEffectsPlan } from './reactive-effects.ts'
27
28
  import type { InnerLoopsPlan } from './inner-loop.ts'
28
29
 
@@ -103,6 +104,14 @@ interface PlainLoopVariant extends DynamicLoopCommon {
103
104
  * stringifier falls back to the legacy per-row `emitTemplateCloneInline`.
104
105
  */
105
106
  skeletonTemplate?: string
107
+ /**
108
+ * Compile-time child-index paths for `skeletonTemplate`'s dynamic slots
109
+ * (perf, #2143). When present, the stringifier resolves attr/text/ref
110
+ * slots via direct `.firstChild`/`.nextSibling` property chains on a
111
+ * fresh clone instead of `qsa`/`$t`, falling back to the runtime lookup
112
+ * only for hydration (`__existing`) or any slot missing from the map.
113
+ */
114
+ skeletonPaths?: SkeletonSlotPaths
106
115
  /** Resolved reactive-effects plan — null forces the single-line renderItem shape. */
107
116
  reactiveEffects: ReactiveEffectsPlan | null
108
117
  /**
@@ -20,21 +20,118 @@ import { emitListenerBlock } from './stringify/event-listener.ts'
20
20
  import { nameForRegistryRef } from '../component-scope.ts'
21
21
  import { BF_SCOPE, BF_HOST, BF_AT } from '@barefootjs/shared'
22
22
  import type { LoopChildRefBinding } from './plan/loop.ts'
23
+ import {
24
+ extractFreeIdentifiersFromText,
25
+ extractFreeIdentifiersFromStatementText,
26
+ extractFreeIdentifiersFromTemplateText,
27
+ } from '../csr-substitute.ts'
23
28
 
24
29
  /**
25
30
  * Build the `keyFn` argument for mapArray / reconcileElements. `null` when
26
- * the loop has no key expression. Narrowing on `loop.kind` keeps `index`
27
- * off `NestedLoop` (nested loops never thread an explicit index parameter)
28
- * and lets the compiler verify we handled every flavour exhaustively.
31
+ * the loop has no key expression. Every `CollectedLoop` variant (top-level /
32
+ * branch / nested) carries an `index: string | null` field (#2218 threaded
33
+ * it onto `NestedLoop` too), so the index param when present is always
34
+ * appended to the keyFn's own parameter list. mapArray invokes `keyFn(item,
35
+ * i)` directly with the numeric index, independent of the synthetic
36
+ * `__innerIdx<uid>` binding used inside a nested loop's renderItem body
37
+ * (see `nestedLoopReferencesIndex` below), so no aliasing is needed here.
29
38
  */
30
39
  export function loopKeyFn(loop: CollectedLoop): string {
31
40
  if (loop.key === null) return 'null'
32
- const params = loop.kind === 'nested'
33
- ? loop.param
34
- : `${loop.param}${loop.index ? `, ${loop.index}` : ''}`
41
+ const params = `${loop.param}${loop.index ? `, ${loop.index}` : ''}`
35
42
  return `(${params}) => String(${loop.key})`
36
43
  }
37
44
 
45
+ /**
46
+ * Does a nested inner loop's body reference its own declared index
47
+ * parameter (e.g. `i` from `.map((item, i) => ...)`)? Scans every surface
48
+ * the renderItem/forEach body can read the index from — the key
49
+ * expression, reactive text/attr expressions, the map-preamble statements,
50
+ * the per-item HTML template's `${...}` interpolations, per-item events,
51
+ * ref callbacks, and child-component props — so the byte-stable gate only
52
+ * fires when the index is truly used (mirrors #2189's handler-only gate
53
+ * for delegated events, `indexBindingLine` in `stringify/event-delegation.ts`).
54
+ *
55
+ * `comps` / `events` are passed separately (rather than read off `inner`)
56
+ * because callers hold them in different shapes at different points in the
57
+ * build pipeline — `DepthLevel.comps`/`.events` for the plain inner-loop
58
+ * path, `inner.childComponents`/`inner.bindings.events` for the loop-child-
59
+ * arm (conditional-branch) path.
60
+ *
61
+ * AST-based throughout (never regex) per repo convention — a token-level
62
+ * scan would false-match a property access like `item.i` as a reference to
63
+ * an index param named `i`.
64
+ */
65
+ export function nestedLoopReferencesIndex(
66
+ inner: NestedLoop,
67
+ comps: readonly IRLoopChildComponent[],
68
+ events: readonly LoopChildEvent[],
69
+ ): boolean {
70
+ const index = inner.index
71
+ if (!index) return false
72
+
73
+ const exprRefs = (text: string | null | undefined, precomputed?: ReadonlySet<string>): boolean => {
74
+ if (precomputed) return precomputed.has(index)
75
+ if (!text) return false
76
+ return extractFreeIdentifiersFromText(text).has(index)
77
+ }
78
+
79
+ if (exprRefs(inner.key)) return true
80
+ for (const t of inner.bindings.reactiveTexts) {
81
+ if (exprRefs(t.expression, t.freeIdentifiers)) return true
82
+ }
83
+ for (const a of inner.bindings.reactiveAttrs) {
84
+ if (exprRefs(a.expression, a.freeIdentifiers)) return true
85
+ }
86
+ if (inner.mapPreamble && extractFreeIdentifiersFromStatementText(inner.mapPreamble).has(index)) return true
87
+ if (inner.template && extractFreeIdentifiersFromTemplateText(inner.template).has(index)) return true
88
+ for (const ev of events) {
89
+ if (exprRefs(ev.handler)) return true
90
+ }
91
+ for (const r of inner.bindings.refs) {
92
+ if (exprRefs(r.callback)) return true
93
+ }
94
+ for (const c of comps) {
95
+ for (const p of c.props) {
96
+ if (exprRefs(attrValueToString(p.value))) return true
97
+ }
98
+ if (c.children?.length) {
99
+ const childrenExpr = irChildrenToJsExpr(c.children)
100
+ if (childrenExpr && exprRefs(childrenExpr)) return true
101
+ }
102
+ }
103
+ return false
104
+ }
105
+
106
+ /**
107
+ * Build the prelude alias statement that binds a nested inner loop's index
108
+ * param to the synthetic numeric-index value mapArray/forEach passes into
109
+ * renderItem (#2218), or `null` when no alias is needed. Gated by
110
+ * `nestedLoopReferencesIndex` for byte-for-byte stability — loops that
111
+ * declare an index but never read it emit no extra line. `paramHead` guards
112
+ * against the (JS-illegal, can't actually happen) case where the index name
113
+ * collides with the loop's own emitted item-parameter identifier — mirrors
114
+ * the self-alias guard in #2189's `indexBindingLine`.
115
+ *
116
+ * `syntheticIndexVar` is the already-formatted variable name the caller's
117
+ * stringifier binds the numeric index to (`__innerIdx<uid>` in
118
+ * `stringify/inner-loop.ts`, `__bidx<uid>` in `stringify/loop-child-arm.ts`)
119
+ * — passed in rather than assembled here so this helper doesn't need to
120
+ * know which emission family is calling it.
121
+ */
122
+ export function nestedLoopIndexAlias(
123
+ inner: NestedLoop,
124
+ syntheticIndexVar: string,
125
+ paramHead: string,
126
+ comps: readonly IRLoopChildComponent[],
127
+ events: readonly LoopChildEvent[],
128
+ ): string | null {
129
+ const index = inner.index
130
+ if (!index || index === paramHead) return null
131
+ if (!nestedLoopReferencesIndex(inner, comps, events)) return null
132
+ return `const ${index} = ${syntheticIndexVar}`
133
+ }
134
+
38
135
  /**
39
136
  * Wrap each ref's `callback` expression with the loop-param accessor and
40
137
  * return `LoopChildRefBinding[]` ready for the stringifier. For dynamic
@@ -33,6 +33,7 @@
33
33
  */
34
34
 
35
35
  import { toDomEventName, varSlotId, substituteLoopBindings, buildLoopChildIndexSubtraction, DATA_KEY, keyAttrName } from '../../utils.ts'
36
+ import { extractFreeIdentifiersFromText } from '../../csr-substitute.ts'
36
37
  import type {
37
38
  EventDelegationPlan,
38
39
  KeyedItemLookup,
@@ -60,6 +61,19 @@ function withTurn(call: string, componentName: string | undefined, childSlotId:
60
61
  return `beginTurn(${id}); try { ${call} } finally { endTurn() }`
61
62
  }
62
63
 
64
+ /**
65
+ * Bind the loop index under the user's param name for a delegated handler that
66
+ * closes over it (#2189). Returns `null` when there is no index param, the
67
+ * handler doesn't reference it (so unaffected loops keep byte-for-byte output),
68
+ * or the name already equals the in-scope index var (a self-alias). Uses AST
69
+ * free identifiers, not a token match, so `item.id` (property) doesn't count.
70
+ */
71
+ function indexBindingLine(handler: string, indexParam: string | null, indexExpr: string): string | null {
72
+ if (!indexParam || indexParam === indexExpr) return null
73
+ if (!extractFreeIdentifiersFromText(handler).has(indexParam)) return null
74
+ return `const ${indexParam} = ${indexExpr}`
75
+ }
76
+
63
77
  export function stringifyEventDelegation(lines: string[], plan: EventDelegationPlan): void {
64
78
  const { containerVar, events, itemLookup, profileComponentName } = plan
65
79
  const eventsByName = new Map<string, LoopChildEvent[]>()
@@ -112,10 +126,11 @@ function emitKeyedLookup(
112
126
  handlerCall: string,
113
127
  lookup: KeyedItemLookup,
114
128
  ): void {
115
- const { arrayExpr, param, keyWithItem, mapPreamble, hasBindings } = lookup
129
+ const { arrayExpr, param, keyWithItem, mapPreamble, hasBindings, indexParam } = lookup
116
130
 
117
131
  if (ev.nestedLoops.length === 0) {
118
132
  // Single-level keyed lookup.
133
+ const idxLine = indexBindingLine(ev.handler, indexParam, `${arrayExpr}.findIndex(item => String(${keyWithItem}) === key)`)
119
134
  ls.push(` const li = ${varSlotId(ev.childSlotId)}El.closest('[${DATA_KEY}]')`)
120
135
  ls.push(` if (li) {`)
121
136
  ls.push(` const key = li.getAttribute('${DATA_KEY}')`)
@@ -125,12 +140,14 @@ function emitKeyedLookup(
125
140
  ls.push(` if (__bfLoopItem) {`)
126
141
  ls.push(` const ${param} = __bfLoopItem`)
127
142
  if (mapPreamble) ls.push(` ${mapPreamble}`)
143
+ if (idxLine) ls.push(` ${idxLine}`)
128
144
  ls.push(` ${handlerCall}`)
129
145
  ls.push(` }`)
130
146
  } else {
131
147
  ls.push(` const ${param} = ${arrayExpr}.find(item => String(${keyWithItem}) === key)`)
132
148
  if (mapPreamble) ls.push(` ${mapPreamble}`)
133
- ls.push(` if (${param}) ${handlerCall}`)
149
+ if (idxLine) ls.push(` if (${param}) { ${idxLine}; ${handlerCall} }`)
150
+ else ls.push(` if (${param}) ${handlerCall}`)
134
151
  }
135
152
  ls.push(` }`)
136
153
  return
@@ -164,7 +181,9 @@ function emitKeyedLookup(
164
181
  const outerGuard = hasBindings ? '__bfLoopItem' : param
165
182
  const allParams = [outerGuard, ...ev.nestedLoops.map(n => n.param)]
166
183
  if (mapPreamble) ls.push(` ${mapPreamble}`)
167
- ls.push(` if (${allParams.join(' && ')}) ${handlerCall}`)
184
+ const idxLine = indexBindingLine(ev.handler, indexParam, `${arrayExpr}.findIndex(item => String(${keyWithItem}) === outerKey)`)
185
+ if (idxLine) ls.push(` if (${allParams.join(' && ')}) { ${idxLine}; ${handlerCall} }`)
186
+ else ls.push(` if (${allParams.join(' && ')}) ${handlerCall}`)
168
187
  }
169
188
 
170
189
  function emitDynamicIndexLookup(
@@ -173,7 +192,8 @@ function emitDynamicIndexLookup(
173
192
  handlerCall: string,
174
193
  lookup: DynamicIndexItemLookup,
175
194
  ): void {
176
- const { arrayExpr, param, mapPreamble, hasBindings } = lookup
195
+ const { arrayExpr, param, mapPreamble, hasBindings, indexParam } = lookup
196
+ const idxLine = indexBindingLine(ev.handler, indexParam, 'idx')
177
197
  ls.push(` const li = ${varSlotId(ev.childSlotId)}El.closest('li, [bf-i]')`)
178
198
  ls.push(` if (li && li.parentElement) {`)
179
199
  ls.push(` const idx = Array.from(li.parentElement.children).indexOf(li)`)
@@ -182,12 +202,14 @@ function emitDynamicIndexLookup(
182
202
  ls.push(` if (__bfLoopItem) {`)
183
203
  ls.push(` const ${param} = __bfLoopItem`)
184
204
  if (mapPreamble) ls.push(` ${mapPreamble}`)
205
+ if (idxLine) ls.push(` ${idxLine}`)
185
206
  ls.push(` ${handlerCall}`)
186
207
  ls.push(` }`)
187
208
  } else {
188
209
  ls.push(` const ${param} = ${arrayExpr}[idx]`)
189
210
  if (mapPreamble) ls.push(` ${mapPreamble}`)
190
- ls.push(` if (${param}) ${handlerCall}`)
211
+ if (idxLine) ls.push(` if (${param}) { ${idxLine}; ${handlerCall} }`)
212
+ else ls.push(` if (${param}) ${handlerCall}`)
191
213
  }
192
214
  ls.push(` }`)
193
215
  }
@@ -199,7 +221,8 @@ function emitStaticIndexLookup(
199
221
  lookup: StaticIndexItemLookup,
200
222
  containerVar: string,
201
223
  ): void {
202
- const { arrayExpr, param, mapPreamble, offset } = lookup
224
+ const { arrayExpr, param, mapPreamble, offset, indexParam } = lookup
225
+ const idxLine = indexBindingLine(ev.handler, indexParam, '__idx')
203
226
  ls.push(` let __el = ${varSlotId(ev.childSlotId)}El`)
204
227
  ls.push(` while (__el.parentElement && __el.parentElement !== ${containerVar}) __el = __el.parentElement`)
205
228
  ls.push(` if (__el.parentElement === ${containerVar}) {`)
@@ -207,6 +230,7 @@ function emitStaticIndexLookup(
207
230
  ls.push(` const __idx = Array.from(${containerVar}.children).indexOf(__el)${idxOffset}`)
208
231
  ls.push(` const ${param} = ${arrayExpr}[__idx]`)
209
232
  if (mapPreamble) ls.push(` ${mapPreamble}`)
210
- ls.push(` if (${param}) ${handlerCall}`)
233
+ if (idxLine) ls.push(` if (${param}) { ${idxLine}; ${handlerCall} }`)
234
+ else ls.push(` if (${param}) ${handlerCall}`)
211
235
  ls.push(` }`)
212
236
  }
@@ -33,7 +33,7 @@
33
33
  import { keyAttrName, profileBindingId } from '../../utils.ts'
34
34
  import { emitComponentAndEventSetup } from '../shared.ts'
35
35
  import { emitAttrUpdate } from '../../emit-reactive.ts'
36
- import { emitMultiRootTemplateCloneLines } from './template-parse.ts'
36
+ import { emitMultiRootTemplateCloneLines, templateRootIsSvg } from './template-parse.ts'
37
37
  import { emitLoopChildRefs } from './loop.ts'
38
38
  import type {
39
39
  InnerLoopPlan,
@@ -82,7 +82,16 @@ function emitReactive(lines: string[], inner: InnerLoopPlan, indent: string, pc:
82
82
  lines.push(`${innerIndent} __innerEl${uid}.__bfExtras = __innerExtras${uid}`)
83
83
  lines.push(`${indent} }`)
84
84
  } else {
85
- lines.push(`${indent} let __innerEl${uid} = __existing ?? (() => { const __t = document.createElement('template'); __t.innerHTML = \`${emit.wrappedTemplate}\`; return __t.content.firstElementChild.cloneNode(true) })()`)
85
+ // SVG-rooted item templates must parse inside a synthetic `<svg>` wrap
86
+ // (#2219): `template.innerHTML` parses in the HTML namespace, so a bare
87
+ // `<line>`/`<circle>` root clones as an HTMLUnknownElement and the SVG
88
+ // renderer silently draws nothing. Mirrors `templateRootIsSvg` handling
89
+ // on the top-level (#135/#1088) and branch-arm paths; HTML-rooted
90
+ // templates keep byte-identical output.
91
+ const isSvg = templateRootIsSvg(emit.wrappedTemplate)
92
+ const innerHtml = isSvg ? `<svg>${emit.wrappedTemplate}</svg>` : emit.wrappedTemplate
93
+ const childPath = isSvg ? '.firstElementChild.firstElementChild' : '.firstElementChild'
94
+ lines.push(`${indent} let __innerEl${uid} = __existing ?? (() => { const __t = document.createElement('template'); __t.innerHTML = \`${innerHtml}\`; return __t.content${childPath}.cloneNode(true) })()`)
86
95
  }
87
96
  if (emit.wrappedKey) {
88
97
  lines.push(`${indent} __innerEl${uid}.setAttribute('${keyAttrName(inner.keyDepth)}', String(${emit.wrappedKey}))`)
@@ -86,6 +86,11 @@ export function stringifyBranchInnerLoops(
86
86
  const uid = inner.uidSuffix
87
87
  lines.push(`${indent}{ const __bic${uid} = ${inner.containerExpr}`)
88
88
  lines.push(`${indent}if (__bic${uid}) mapArray(() => ${inner.arrayExpr} || [], __bic${uid}, ${inner.keyFn}, (${inner.paramHead}, __bidx${uid}, __existing) => {`)
89
+ // Index alias (#2218) lands first — before the destructure unwrap and
90
+ // the template clone, either of which may reference the index.
91
+ if (inner.indexAlias) {
92
+ lines.push(`${indent} ${inner.indexAlias}`)
93
+ }
89
94
  if (inner.paramUnwrap) {
90
95
  lines.push(`${indent} ${inner.paramUnwrap}`)
91
96
  }