@barefootjs/jsx 0.39.3 → 0.39.5

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 (103) hide show
  1. package/dist/adapters/boolean-result.d.ts +32 -0
  2. package/dist/adapters/boolean-result.d.ts.map +1 -0
  3. package/dist/adapters/filter-capture-collisions.d.ts +17 -0
  4. package/dist/adapters/filter-capture-collisions.d.ts.map +1 -0
  5. package/dist/adapters/parsed-expr-emitter.d.ts +8 -0
  6. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  7. package/dist/adapters/template-name-collisions.d.ts +21 -0
  8. package/dist/adapters/template-name-collisions.d.ts.map +1 -0
  9. package/dist/analyzer-context.d.ts.map +1 -1
  10. package/dist/errors.d.ts +1 -0
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/expression-parser.d.ts +10 -0
  13. package/dist/expression-parser.d.ts.map +1 -1
  14. package/dist/index.d.ts +6 -3
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +688 -176
  17. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/plan/build-composite-loop.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  20. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +13 -0
  21. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  22. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts +3 -2
  23. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +7 -0
  25. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  27. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +2 -0
  29. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/control-flow/stringify/composite-loop.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts +14 -0
  34. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/imports.d.ts +2 -2
  37. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts +3 -1
  39. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/safe-html.d.ts +6 -0
  42. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/types.d.ts +12 -0
  44. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/utils.d.ts +39 -1
  46. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  47. package/dist/nullable-signal-attr.d.ts +33 -0
  48. package/dist/nullable-signal-attr.d.ts.map +1 -1
  49. package/dist/profiler.d.ts +9 -1
  50. package/dist/profiler.d.ts.map +1 -1
  51. package/dist/scope/binding-scope.d.ts +10 -0
  52. package/dist/scope/binding-scope.d.ts.map +1 -1
  53. package/dist/types.d.ts +7 -0
  54. package/dist/types.d.ts.map +1 -1
  55. package/package.json +2 -2
  56. package/src/__tests__/binding-scope-ratchet.test.ts +1 -1
  57. package/src/__tests__/binding-scope.test.ts +11 -0
  58. package/src/__tests__/boolean-result.test.ts +27 -0
  59. package/src/__tests__/compile-without-node-process.test.ts +78 -0
  60. package/src/__tests__/csr-template-loop-shadow.test.ts +83 -0
  61. package/src/__tests__/doc-examples.test.ts +1 -0
  62. package/src/__tests__/nested-row-shadowing.test.ts +57 -0
  63. package/src/__tests__/profile-turn-markers.test.ts +22 -0
  64. package/src/__tests__/profiler.test.ts +10 -9
  65. package/src/__tests__/rename-free-identifiers.test.ts +26 -0
  66. package/src/__tests__/ssr-portal-ref-callback.test.ts +88 -13
  67. package/src/__tests__/template-name-collisions.test.ts +81 -0
  68. package/src/adapters/boolean-result.ts +89 -0
  69. package/src/adapters/filter-capture-collisions.ts +29 -0
  70. package/src/adapters/parsed-expr-emitter.ts +18 -0
  71. package/src/adapters/template-name-collisions.ts +120 -0
  72. package/src/analyzer-context.ts +15 -1
  73. package/src/errors.ts +11 -0
  74. package/src/expression-parser.ts +32 -0
  75. package/src/index.ts +9 -2
  76. package/src/ir-to-client-js/collect-elements.ts +22 -10
  77. package/src/ir-to-client-js/control-flow/plan/build-composite-loop.ts +2 -0
  78. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +13 -0
  79. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +38 -12
  80. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +12 -5
  81. package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +2 -2
  82. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +7 -0
  83. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  84. package/src/ir-to-client-js/control-flow/plan/loop.ts +2 -0
  85. package/src/ir-to-client-js/control-flow/shared.ts +6 -1
  86. package/src/ir-to-client-js/control-flow/stringify/branch-loop.ts +6 -3
  87. package/src/ir-to-client-js/control-flow/stringify/composite-loop.ts +7 -4
  88. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +21 -6
  89. package/src/ir-to-client-js/control-flow/stringify/insert.ts +6 -1
  90. package/src/ir-to-client-js/control-flow/stringify/loop.ts +55 -8
  91. package/src/ir-to-client-js/html-template.ts +72 -15
  92. package/src/ir-to-client-js/imports.ts +3 -1
  93. package/src/ir-to-client-js/index.ts +7 -2
  94. package/src/ir-to-client-js/phases/rest-attr-applications.ts +8 -2
  95. package/src/ir-to-client-js/reactivity.ts +1 -0
  96. package/src/ir-to-client-js/safe-html.ts +10 -0
  97. package/src/ir-to-client-js/types.ts +12 -0
  98. package/src/ir-to-client-js/utils.ts +81 -7
  99. package/src/jsx-to-ir.ts +138 -32
  100. package/src/nullable-signal-attr.ts +78 -0
  101. package/src/profiler.ts +79 -10
  102. package/src/scope/binding-scope.ts +19 -0
  103. package/src/types.ts +7 -0
@@ -55,22 +55,60 @@ import type { LoopChildRefBinding, LoopPlan, PlainLoopPlan, StaticLoopPlan } fro
55
55
  export function emitLoopChildRefs(
56
56
  lines: string[],
57
57
  refs: readonly LoopChildRefBinding[],
58
- opts: { indent: string; elVar: string; bodyIsMultiRoot: boolean; elementIndexBySlot?: ReadonlyMap<string, number> },
58
+ opts: {
59
+ indent: string
60
+ elVar: string
61
+ bodyIsMultiRoot: boolean
62
+ elementIndexBySlot?: ReadonlyMap<string, number>
63
+ /** The loop container; required when a ref portals its element out of the row (#3318). */
64
+ containerVar?: string
65
+ },
59
66
  ): void {
60
67
  if (refs.length === 0) return
61
- const { indent, elVar, bodyIsMultiRoot, elementIndexBySlot } = opts
62
- const lookup = bodyIsMultiRoot ? 'qsaItem' : 'qsa'
68
+ const { indent, elVar, bodyIsMultiRoot, elementIndexBySlot, containerVar } = opts
63
69
  for (const ref of refs) {
70
+ // A portaled element sits outside the row once hydrated or adopted, so
71
+ // its lookup goes through the row's registered roots (`qsaItem`).
72
+ const lookup = bodyIsMultiRoot || ref.ssrPortalOwner ? 'qsaItem' : 'qsa'
64
73
  const varName = `__rf_${varSlotId(ref.childSlotId)}`
65
74
  const pIdx = elementIndexBySlot?.get(ref.childSlotId)
66
75
  const lookupExpr = pIdx !== undefined
67
76
  ? `__p ? __p[${pIdx}] : ${lookup}(${elVar}, '[bf="${ref.childSlotId}"]')`
68
77
  : `${lookup}(${elVar}, '[bf="${ref.childSlotId}"]')`
69
78
  lines.push(`${indent}{ const ${varName} = ${lookupExpr}`)
70
- lines.push(`${indent}if (${varName}) ${emitRefCall(ref.callback, varName)} }`)
79
+ if (ref.ssrPortalOwner && containerVar) {
80
+ // Stamp `bf-po` like a top-level portal ref, then register the element
81
+ // with its row: relayed listeners, row lookups, removal on disposal.
82
+ lines.push(`${indent}if (${varName}) { ${emitRefCall(ref.callback, varName, true)}; adoptRowPortal(${elVar}, ${varName}, ${containerVar}) } }`)
83
+ } else {
84
+ lines.push(`${indent}if (${varName}) ${emitRefCall(ref.callback, varName)} }`)
85
+ }
71
86
  }
72
87
  }
73
88
 
89
+ /** Slot ids of the row elements a `ref` callback portals out of the row (#3318). */
90
+ export function rowPortalSlotIds(refs: readonly LoopChildRefBinding[]): string[] {
91
+ return refs.filter(r => r.ssrPortalOwner).map(r => r.childSlotId)
92
+ }
93
+
94
+ /**
95
+ * Hydration: pair the row with the elements SSR placed at their portal
96
+ * outlet (#3318), before any lookup in the row body needs them. Emitted
97
+ * right after the row element (`__el`) is bound.
98
+ */
99
+ export function emitRowPortalClaim(
100
+ lines: string[],
101
+ refs: readonly LoopChildRefBinding[],
102
+ opts: { indent: string; containerVar: string; rowVar?: string },
103
+ ): void {
104
+ const slots = rowPortalSlotIds(refs)
105
+ if (slots.length === 0) return
106
+ // A mapArray row claims only when hydrating (`__existing`); a static row
107
+ // is always the SSR one, or a fresh clone the claim finds nothing for.
108
+ const claim = `claimRowPortals(${opts.rowVar ?? '__existing'}, __scopeId, ${JSON.stringify(slots)}, ${opts.containerVar})`
109
+ lines.push(opts.rowVar ? `${opts.indent}${claim}` : `${opts.indent}if (__existing) ${claim}`)
110
+ }
111
+
74
112
  /**
75
113
  * Preamble-patched regions (#2389 — `arr.map(t => { const cells = []; ...;
76
114
  * return <tr>{cells}<td>{t.name}</td></tr> })`) used to get their own
@@ -255,6 +293,11 @@ export function stringifyPlainLoop(
255
293
  singleRootLayout: 'inline',
256
294
  })
257
295
  }
296
+ // A row whose ref portals an element out of it (#3318) claims the
297
+ // element first and resolves every lookup through the row's registered
298
+ // roots (`qsaItem`), so bindings on the portaled element still find it.
299
+ emitRowPortalClaim(lines, childRefs, { indent: bodyIndent, containerVar })
300
+ const itemLookup = bodyIsMultiRoot || rowPortalSlotIds(childRefs).length > 0
258
301
  // Direct child-index paths (perf, #2143): only reachable when hoistedTpl
259
302
  // is set, which itself requires a single-root, conditional-free body — so
260
303
  // `reactiveEffects.conditionals` is always empty here and needs no path
@@ -295,14 +338,14 @@ export function stringifyPlainLoop(
295
338
  stringifyReactiveEffects(lines, reactiveEffects, {
296
339
  indent: bodyIndent,
297
340
  elVar: '__el',
298
- bodyIsMultiRoot,
341
+ bodyIsMultiRoot: itemLookup,
299
342
  elementIndexBySlot: pathPlan?.elementIndexBySlot,
300
343
  textClaimPathExprs,
301
344
  preambleRegions,
302
345
  mapPreambleWrapped,
303
346
  })
304
347
  }
305
- emitLoopChildRefs(lines, childRefs, { indent: bodyIndent, elVar: '__el', bodyIsMultiRoot, elementIndexBySlot: pathPlan?.elementIndexBySlot })
348
+ emitLoopChildRefs(lines, childRefs, { indent: bodyIndent, elVar: '__el', bodyIsMultiRoot: itemLookup, elementIndexBySlot: pathPlan?.elementIndexBySlot, containerVar })
306
349
  lines.push(`${bodyIndent}return __el`)
307
350
  lines.push(`${topIndent}}, '${markerId}'${loopBfId})`)
308
351
  }
@@ -452,11 +495,15 @@ export function stringifyStaticLoop(lines: string[], plan: StaticLoopPlan): void
452
495
  lines.push(` }`)
453
496
  }
454
497
  lines.push(` if (__iterEl) {`)
498
+ // See `stringifyPlainLoop` (#3318). A static row is never disposed on its
499
+ // own, so its portaled elements live as long as the component.
500
+ emitRowPortalClaim(lines, childRefs, { indent: ' ', containerVar, rowVar: '__iterEl' })
501
+ const rowHasPortal = rowPortalSlotIds(childRefs).length > 0
455
502
  if (attrsBySlot.length > 0) lines.push(` ${DEDUP_STORE_DECL}`)
456
503
  let ordinal = 0
457
504
  for (const [slotId, attrs] of attrsBySlot) {
458
505
  const varName = `__t_${varSlotId(slotId)}`
459
- lines.push(` const ${varName} = qsa(__iterEl, '[bf="${slotId}"]')`)
506
+ lines.push(` const ${varName} = ${rowHasPortal ? 'qsaItem' : 'qsa'}(__iterEl, '[bf="${slotId}"]')`)
460
507
  lines.push(` if (${varName}) {`)
461
508
  for (const attr of attrs) {
462
509
  lines.push(` createEffect(() => {`)
@@ -478,7 +525,7 @@ export function stringifyStaticLoop(lines: string[], plan: StaticLoopPlan): void
478
525
  // Ref callbacks fire on every forEach iteration — initial mount and any
479
526
  // future array-change-driven re-iteration (#1244). For static arrays the
480
527
  // array is non-reactive, so refs effectively fire once per item.
481
- emitLoopChildRefs(lines, childRefs, { indent: ' ', elVar: '__iterEl', bodyIsMultiRoot: false })
528
+ emitLoopChildRefs(lines, childRefs, { indent: ' ', elVar: '__iterEl', bodyIsMultiRoot: rowHasPortal, containerVar })
482
529
  lines.push(` }`)
483
530
  lines.push(` })`)
484
531
  lines.push(` }`)
@@ -4,18 +4,18 @@
4
4
 
5
5
  import type { AttrValue, FlatMapCallback, IRAttribute, IRElement, IRExpression, IRNode, IRProp, MapCallbackPreamble } from '../types.ts'
6
6
  import { isBooleanAttr } from '../html-constants.ts'
7
- import { toHtmlAttrName, attrValueToString, quotePropName, PROPS_PARAM, DATA_BF_PH, keyAttrName, loopStartMarker, loopEndMarker, loopItemMarker, freeIdsFromRefs, setIntersects, wrapExprWithLoopParams } from './utils.ts'
7
+ import { toHtmlAttrName, attrValueToString, quotePropName, PROPS_PARAM, DATA_BF_PH, keyAttrName, loopStartMarker, loopEndMarker, loopItemMarker, freeIdsFromRefs, setIntersects, wrapExprWithLoopParams, specsInsideRow } from './utils.ts'
8
8
  import type { LoopParamSpec } from './utils.ts'
9
9
  import { nameForRegistryRef } from './component-scope.ts'
10
10
  import { assertNever } from './walker.ts'
11
- import { buildSignalMemoEnv, csrSubstitute, type CsrEnv } from './csr-substitute.ts'
11
+ import { buildSignalMemoEnv, csrSubstitute, extractFreeIdentifiersFromText, type CsrEnv, type CsrSubstitution } from './csr-substitute.ts'
12
12
  import { rewritePropsObjectRef } from './rewrite-props-object.ts'
13
13
  import type { ClientJsContext } from './types.ts'
14
14
  import { BF_KEY, BF_PARENT_SCOPE_PLACEHOLDER, BF_SCOPE, classifyDOMProp, escapeHtml } from '@barefootjs/shared'
15
15
  import { buildLoopChainExpr } from '../loop-chain.ts'
16
16
  import { renderChildScopeArgs } from '../adapters/child-scope.ts'
17
17
  import { BindingScope } from '../scope/binding-scope.ts'
18
- import { interp, spliceChildValue, conditionalMarkup, renderChildCall, mappedRowsMarkup, dangerousInnerHtml, EMPTY_MARKUP } from './safe-html.ts'
18
+ import { interp, spliceChildValue, conditionalMarkup, renderChildCall, mappedRowsMarkup, withOuterBindings, dangerousInnerHtml, EMPTY_MARKUP } from './safe-html.ts'
19
19
  import { markupSlotIdsOf } from './markup-slots.ts'
20
20
  import { isEventHandlerName } from '../event-handler-name.ts'
21
21
 
@@ -965,7 +965,10 @@ export function irToHtmlTemplate(node: IRNode, restSpreadNames?: ReadonlySet<str
965
965
  // Increment loopDepth so inner key attrs become data-key-N
966
966
  // Forward loopParams so expressions referencing outer/inner loop params
967
967
  // get wrapped as signal accessors (e.g., task.title → task().title).
968
- const innerRecurse = (n: IRNode): string => irToHtmlTemplate(n, restSpreadNames, loopDepth + 1, loopParams, branchSlotsVar)
968
+ // Inside the row, a name the row rebinds is no longer an enclosing
969
+ // loop's binding (#3394).
970
+ const rowLoopParams = specsInsideRow(loopParams, node)
971
+ const innerRecurse = (n: IRNode): string => irToHtmlTemplate(n, restSpreadNames, loopDepth + 1, rowLoopParams, branchSlotsVar)
969
972
  let childTemplate = node.children.map(innerRecurse).join('')
970
973
  // Whole-item conditional loops (#1665): prepend an always-present
971
974
  // `<!--bf-loop-i:KEY-->` anchor before each item's (possibly empty)
@@ -1001,13 +1004,13 @@ export function irToHtmlTemplate(node: IRNode, restSpreadNames?: ReadonlySet<str
1001
1004
  // `mapArray` stamps on adoption/creation, so SSR, hydrate template and
1002
1005
  // csr-mount agree on it (see `leafKeyAsDataKeyAttr`).
1003
1006
  const body = renderPreamble(node.flatMapCallback, {
1004
- renderLeaf: (ir) => irToHtmlTemplate(leafKeyAsDataKeyAttr(ir), restSpreadNames, loopDepth + 1, loopParams, branchSlotsVar),
1007
+ renderLeaf: (ir) => irToHtmlTemplate(leafKeyAsDataKeyAttr(ir), restSpreadNames, loopDepth + 1, rowLoopParams, branchSlotsVar),
1005
1008
  })
1006
1009
  mapExpr = interp(mappedRowsMarkup(wrappedArray, 'flatMap', node.flatMapCallback.params, body))
1007
1010
  } else if (node.preamble) {
1008
1011
  // Stage 3 / D4 — render JSX leaves in an arbitrary array-builder
1009
1012
  // preamble (the hydrate-template context uses the bare loop param).
1010
- const preamble = renderPreamble(node.preamble, { textVariant: 'client', renderLeaf: (ir) => irToHtmlTemplate(ir, restSpreadNames, loopDepth + 1, loopParams, branchSlotsVar) })
1013
+ const preamble = renderPreamble(node.preamble, { textVariant: 'client', renderLeaf: (ir) => irToHtmlTemplate(ir, restSpreadNames, loopDepth + 1, rowLoopParams, branchSlotsVar) })
1011
1014
  mapExpr = interp(mappedRowsMarkup(wrappedArray, iterMethod, callbackParam, `{ ${preamble} return \`${childTemplate}\` }`))
1012
1015
  } else {
1013
1016
  mapExpr = interp(mappedRowsMarkup(wrappedArray, iterMethod, callbackParam, `\`${childTemplate}\``))
@@ -1455,7 +1458,10 @@ export function irToPlaceholderTemplate(node: IRNode, restSpreadNames?: Readonly
1455
1458
  case 'loop': {
1456
1459
  // Inner loops: generate inline .map().join('') with placeholders for components
1457
1460
  // Forward loopParams so inner loop param expressions get wrapped as signal accessors.
1458
- const innerRecurse = (n: IRNode): string => irToPlaceholderTemplate(n, restSpreadNames, loopDepth + 1, loopParams)
1461
+ // Inside the row, a name the row rebinds is no longer an enclosing
1462
+ // loop's binding (#3394).
1463
+ const rowLoopParams = specsInsideRow(loopParams, node)
1464
+ const innerRecurse = (n: IRNode): string => irToPlaceholderTemplate(n, restSpreadNames, loopDepth + 1, rowLoopParams)
1459
1465
  const childTemplate = node.children.map(innerRecurse).join('')
1460
1466
  const indexParam = node.index ? `, ${node.index}` : ''
1461
1467
  // Apply sort / filter chain (#1448 Tier B) — same shape as the
@@ -1468,12 +1474,12 @@ export function irToPlaceholderTemplate(node: IRNode, restSpreadNames?: Readonly
1468
1474
  if (node.flatMapCallback) {
1469
1475
  const body = renderPreamble(node.flatMapCallback, {
1470
1476
  // Leaf `key` → `data-key` — see the irToHtmlTemplate site above.
1471
- renderLeaf: (ir) => irToPlaceholderTemplate(leafKeyAsDataKeyAttr(ir), restSpreadNames, loopDepth + 1, loopParams),
1477
+ renderLeaf: (ir) => irToPlaceholderTemplate(leafKeyAsDataKeyAttr(ir), restSpreadNames, loopDepth + 1, rowLoopParams),
1472
1478
  })
1473
1479
  mapExpr = interp(mappedRowsMarkup(wrappedArray, 'flatMap', node.flatMapCallback.params, body))
1474
1480
  } else if (node.preamble) {
1475
1481
  // Stage 3 / D4 — render JSX leaves in an arbitrary array-builder preamble.
1476
- const preamble = renderPreamble(node.preamble, { textVariant: 'client', renderLeaf: (ir) => irToPlaceholderTemplate(ir, restSpreadNames, loopDepth + 1, loopParams) })
1482
+ const preamble = renderPreamble(node.preamble, { textVariant: 'client', renderLeaf: (ir) => irToPlaceholderTemplate(ir, restSpreadNames, loopDepth + 1, rowLoopParams) })
1477
1483
  mapExpr = interp(mappedRowsMarkup(wrappedArray, iterMethod, callbackParam, `{ ${preamble} return \`${childTemplate}\` }`))
1478
1484
  } else {
1479
1485
  mapExpr = interp(mappedRowsMarkup(wrappedArray, iterMethod, callbackParam, `\`${childTemplate}\``))
@@ -2327,6 +2333,41 @@ function mergeCsrNullUnsafe(ctx: ClientJsContext, unsafeLocalNames: Set<string>
2327
2333
  return merged ?? unsafeLocalNames
2328
2334
  }
2329
2335
 
2336
+ /**
2337
+ * The substitutions visible inside a loop row whose bindings are
2338
+ * `boundHere`. A name the row binds is dropped: it means the row binding
2339
+ * there, not the outer signal / memo / const. An entry the row keeps is
2340
+ * spliced INTO the row, so its replacement must not mention a name the row
2341
+ * binds either: a memo `label = () => s()` read as `label()` under a row
2342
+ * param `s` would otherwise splice `s()` where `s` is the row item (#3352).
2343
+ * Such a replacement is first resolved against the outer `env`, the scope
2344
+ * the memo / const was declared in, so its own references are already
2345
+ * substituted before it reaches the row.
2346
+ *
2347
+ * A resolved replacement can still name a row binding when the name is not
2348
+ * a substitution at all (a module-level helper the row param shadows). Those
2349
+ * entries are returned in `hoisted`: the caller evaluates them once outside
2350
+ * the row, where the names still mean what they meant at the declaration.
2351
+ */
2352
+ function closeOverLoopBindings(
2353
+ env: CsrEnv,
2354
+ boundHere: ReadonlySet<string>,
2355
+ ): { substitutions: Map<string, CsrSubstitution>; hoisted: string[] } {
2356
+ const substitutions = new Map<string, CsrSubstitution>()
2357
+ const hoisted: string[] = []
2358
+ for (const [name, sub] of env.substitutions) {
2359
+ if (boundHere.has(name)) continue
2360
+ if (!setIntersects(extractFreeIdentifiersFromText(sub.replacement), boundHere)) {
2361
+ substitutions.set(name, sub)
2362
+ continue
2363
+ }
2364
+ const closed = csrSubstitute(sub.replacement, env)
2365
+ if (setIntersects(closed.freeIdentifiers, boundHere)) hoisted.push(name)
2366
+ substitutions.set(name, { ...sub, replacement: closed.rewritten, freeIdentifiers: closed.freeIdentifiers })
2367
+ }
2368
+ return { substitutions, hoisted }
2369
+ }
2370
+
2330
2371
  /**
2331
2372
  * Build the per-component CSR substitution env (signals + memos + inlinable
2332
2373
  * constants), matching what `generateCsrTemplate` builds. Shared so the
@@ -2763,10 +2804,26 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2763
2804
  // hide an outer same-named const), not a reactivity classifier.
2764
2805
  const childScope = (opts.scope ?? BindingScope.EMPTY).enterLoopRow(node)
2765
2806
  const boundHere = childScope.boundNames()
2766
- const childEnv: CsrEnv = {
2767
- ...env,
2768
- substitutions: new Map([...env.substitutions].filter(([name]) => !boundHere.has(name))),
2807
+ const { substitutions: childSubstitutions, hoisted } = closeOverLoopBindings(env, boundHere)
2808
+ // Each hoisted entry is read once, outside the row, into a parameter
2809
+ // the row's substitution points at (#3352). Its value cannot depend on
2810
+ // the row: it was declared outside the loop.
2811
+ const hoistParams: string[] = []
2812
+ const hoistValues: string[] = []
2813
+ for (const name of hoisted) {
2814
+ const sub = env.substitutions.get(name)!
2815
+ const value = transformExpr(sub.kind === 'call' ? `${name}()` : name)
2816
+ // An init-only value stays on the resolved substitution, whose free
2817
+ // identifiers still name the init-only local, so a row expression
2818
+ // reading it is deferred like any other unsafe read rather than
2819
+ // handed a bound `undefined` to dereference.
2820
+ if (value === UNSAFE_TEMPLATE_EXPR) continue
2821
+ const param = `__bf_outer_${name}`
2822
+ hoistParams.push(param)
2823
+ hoistValues.push(value)
2824
+ childSubstitutions.set(name, { kind: sub.kind, replacement: param, freeIdentifiers: new Set([param]) })
2769
2825
  }
2826
+ const childEnv: CsrEnv = { ...env, substitutions: childSubstitutions }
2770
2827
  const recurseInLoopBody = (n: IRNode): string => generateCsrTemplateWithOpts(n, {
2771
2828
  ...opts,
2772
2829
  loopDepth: loopDepth + 1,
@@ -2816,14 +2873,14 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2816
2873
  // Leaf `key` → `data-key` — see the irToHtmlTemplate site above.
2817
2874
  renderLeaf: (ir) => recurseInLoopBody(leafKeyAsDataKeyAttr(ir)),
2818
2875
  })
2819
- mapExpr = interp(mappedRowsMarkup(iterArrayExpr, 'flatMap', node.flatMapCallback.params, body))
2876
+ mapExpr = interp(withOuterBindings(hoistParams, hoistValues, mappedRowsMarkup(iterArrayExpr, 'flatMap', node.flatMapCallback.params, body)))
2820
2877
  } else if (node.preamble) {
2821
2878
  // Stage 3 / D4 — template-variant js text with the props rewrite
2822
2879
  // applied per segment; JSX leaves render via the loop-body recursion.
2823
2880
  const preamble = renderPreamble(node.preamble, { textVariant: 'template', transformJs: (t) => rewritePropsObjectRef(t, propsObjectName ?? null, restPropsName ?? null, { enclosingScope: childScope }), renderLeaf: (ir) => recurseInLoopBody(ir) })
2824
- mapExpr = interp(mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `{ ${preamble} return \`${childTemplate}\` }`))
2881
+ mapExpr = interp(withOuterBindings(hoistParams, hoistValues, mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `{ ${preamble} return \`${childTemplate}\` }`)))
2825
2882
  } else {
2826
- mapExpr = interp(mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `\`${childTemplate}\``))
2883
+ mapExpr = interp(withOuterBindings(hoistParams, hoistValues, mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `\`${childTemplate}\``)))
2827
2884
  }
2828
2885
  return `<!--${loopStartMarker(node.markerId)}-->${mapExpr}<!--${loopEndMarker(node.markerId)}-->`
2829
2886
  }
@@ -45,7 +45,9 @@ export const RUNTIME_IMPORT_CANDIDATES = [
45
45
  // Nullish guard for a bare `{children}` passthrough splice (#2775) — the
46
46
  // value is already-stringified markup, never escaped, just nullish-safe.
47
47
  'markupOrEmpty',
48
- 'qsa', 'qsaItem', 'qsaChildScope', 'qsaChildScopes', 'upsertChildItem', '__slot', '__bfSlot', '__bfText',
48
+ 'qsa', 'qsaItem',
49
+ // Loop-row elements a `ref` callback portals out of their row (#3318).
50
+ 'adoptRowPortal', 'claimRowPortals', 'relayRowPortalEvents', 'isRowPortalOf', 'qsaChildScope', 'qsaChildScopes', 'upsertChildItem', '__slot', '__bfSlot', '__bfText',
49
51
  // Claim-plan interpreter (slot unification A2/A3, spec/slot-unification.md)
50
52
  // — the "one claim mechanism" that replaced `patchSlotRange` and
51
53
  // `updateClientMarker` (both deleted) as the content-slot update door.
@@ -16,7 +16,7 @@ import { buildReferencesGraph, graphUsedIdentifiers } from './build-references.t
16
16
  import { addConstantPropRefsToSet } from './init-declarations.ts'
17
17
  import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate } from './html-template.ts'
18
18
  import { markupSlotIdsOf } from './markup-slots.ts'
19
- import { PROPS_PARAM, initFunctionName, componentDefScopeFlags } from './utils.ts'
19
+ import { PROPS_PARAM, initFunctionName, componentDefScopeFlags, isTransparentFragmentRoot } from './utils.ts'
20
20
  import { buildInlinableConstants, csrInlinableConstantsFromCtx } from './emit-registration.ts'
21
21
  import { buildEnvFromCtx } from './compute-inlinability.ts'
22
22
  import { nameForRegistryRef, buildImportAliasMap, setActiveImportAliases } from './component-scope.ts'
@@ -367,7 +367,12 @@ function generateTemplateOnlyMount(ir: ComponentIR, ctx: ClientJsContext): strin
367
367
  // uses — a fragment-rooted stateless child must declare `comment` /
368
368
  // `fragmentRoot` too, or `renderChild()` stamps `bf-s` onto its first
369
369
  // element while SSR scopes it with a comment pair.
370
- const scopeFlags = componentDefScopeFlags(ir.root).map((f) => `, ${f}`).join('')
370
+ // A stateless transparent root (`<>{children}</>`) owns no scope at all —
371
+ // SSR renders the caller's content unmarked — so `renderChild()` must not
372
+ // stamp one either (#3355). Only the template-only path declares it: a
373
+ // stateful child still needs a scope for its init to bind against.
374
+ const transparentFlag = isTransparentFragmentRoot(ir.root) ? ['transparent: true'] : []
375
+ const scopeFlags = [...componentDefScopeFlags(ir.root), ...transparentFlag].map((f) => `, ${f}`).join('')
371
376
  lines.push(`hydrate('${registryKey}', { init: ${initName}, template: (${PROPS_PARAM}) => \`${templateHtml}\`${scopeFlags}${nameField} })`)
372
377
  // See `emitRegistrationAndHydration` (./emit-registration.ts) for the
373
378
  // rationale on why the component is also emitted as a callable
@@ -3,7 +3,9 @@
3
3
  * for HTML elements with unresolved spread attributes.
4
4
  *
5
5
  * The runtime helper applies the spread source's enumerable properties as
6
- * DOM attributes, skipping the keys statically set on the element.
6
+ * DOM attributes, skipping the keys statically set on the element. In profile
7
+ * mode a 4th argument names the site for turn attribution of the event
8
+ * handlers the spread carries.
7
9
  */
8
10
 
9
11
  import type { ClientJsContext } from '../types.ts'
@@ -14,7 +16,11 @@ export function emitRestAttrApplications(lines: string[], ctx: ClientJsContext):
14
16
  for (const elem of ctx.restAttrElements) {
15
17
  const v = varSlotId(elem.slotId)
16
18
  const excludeKeys = JSON.stringify(elem.excludeKeys)
17
- lines.push(` if (_${v}) applyRestAttrs(_${v}, ${elem.source}, ${excludeKeys})`)
19
+ // Profile mode (#3376): hand the runtime this site's handler id prefix so
20
+ // the event handlers it wires from the spread get the same turn markers
21
+ // an explicit `on*` handler gets in `event-handlers.ts`.
22
+ const turnSite = ctx.profile ? `, ${JSON.stringify(`${ctx.componentName}#handler:${elem.slotId}`)}` : ''
23
+ lines.push(` if (_${v}) applyRestAttrs(_${v}, ${elem.source}, ${excludeKeys}${turnSite})`)
18
24
  }
19
25
  lines.push('')
20
26
  }
@@ -529,6 +529,7 @@ export function collectLoopChildRefs(node: IRNode): LoopChildRef[] {
529
529
  refs.push({
530
530
  childSlotId: el.slotId,
531
531
  callback: el.ref,
532
+ ...(el.ssrPortalOwnerScope && { ssrPortalOwner: true }),
532
533
  })
533
534
  }
534
535
  }, true)
@@ -162,6 +162,16 @@ export function mappedRowsMarkup(arrayExpr: string, method: string, params: stri
162
162
  return safeHtml(`${arrayExpr}.${method}(${params} => ${body}).join('')`)
163
163
  }
164
164
 
165
+ /**
166
+ * `((p1, p2) => markup)(v1, v2)` — bind values computed outside `markup` to
167
+ * parameters it reads (#3352). `markup` is returned unchanged when there is
168
+ * nothing to bind.
169
+ */
170
+ export function withOuterBindings(params: readonly string[], values: readonly string[], markup: SafeHtml): SafeHtml {
171
+ if (params.length === 0) return markup
172
+ return safeHtml(`((${params.join(', ')}) => ${markup})(${values.join(', ')})`)
173
+ }
174
+
165
175
  /** The empty string literal — a deferred placeholder the init effect fills (#1128). */
166
176
  export const EMPTY_MARKUP: SafeHtml = safeHtml("''")
167
177
 
@@ -228,6 +228,12 @@ export interface ConditionalBranchTextEffect {
228
228
  */
229
229
  export interface ConditionalBranchReactiveAttr extends AttrMeta {
230
230
  slotId: string
231
+ /**
232
+ * For a parent-owned (`^sN`) slot: the slot ids of the components whose
233
+ * `children` enclose it, outermost first. The runtime lookup resolves the
234
+ * element only inside one of these receivers (#3324).
235
+ */
236
+ receiverSlotIds?: readonly string[]
231
237
  attrName: string
232
238
  expression: string
233
239
  }
@@ -396,6 +402,12 @@ export interface LoopChildRef {
396
402
  childSlotId: string
397
403
  /** Ref callback expression. May reference the loop param. */
398
404
  callback: string
405
+ /**
406
+ * The callback is the recognized SSR-portal pattern
407
+ * (`IRElement.ssrPortalOwnerScope`): it portals the element out of the
408
+ * row, so the row adopts it (`adoptRowPortal`, #3318).
409
+ */
410
+ ssrPortalOwner?: boolean
399
411
  }
400
412
 
401
413
  /** Loop info extracted from a conditional branch for reactive reconciliation. */
@@ -7,6 +7,7 @@ import ts from 'typescript'
7
7
  import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode, IRFragment, ComponentIR } from '../types.ts'
8
8
  import type { TopLevelLoop, BranchLoop, LoopOffset } from './types.ts'
9
9
  import { isNonReferenceIdentifierPosition } from '../analyzer.ts'
10
+ import { BindingScope, type LoopBindingSource } from '../scope/binding-scope.ts'
10
11
  import { buildLoopChainExpr } from '../loop-chain.ts'
11
12
  import { templatePartsToJsExpr } from '../template-parts.ts'
12
13
  import {
@@ -96,6 +97,16 @@ export function isScopeCommentFragmentRoot(root: ComponentIR['root']): boolean {
96
97
  return root.type === 'fragment' && !!(root as IRFragment).needsScopeComment
97
98
  }
98
99
 
100
+ /**
101
+ * True for a transparent fragment root (`<>{children}</>`). SSR renders it
102
+ * with no scope marker of any kind, so a stateless component of this shape
103
+ * declares `transparent: true` and `renderChild()` emits its markup as-is
104
+ * (#3355).
105
+ */
106
+ export function isTransparentFragmentRoot(root: ComponentIR['root']): boolean {
107
+ return root.type === 'fragment' && !!(root as IRFragment).transparent
108
+ }
109
+
99
110
  /**
100
111
  * The scope-shape flags (`comment: true` / `fragmentRoot: true`) a
101
112
  * component's `hydrate()` def declares — the ONE answer both registration
@@ -655,7 +666,7 @@ function scanForIdentifiers(expr: string, predicate: (token: string) => boolean)
655
666
  * native array method (no runtime helper required).
656
667
  */
657
668
  function renderLoopBindingAccess(b: LoopParamBinding, base: string): string {
658
- const parent = `${base}${b.path}`
669
+ const parent = `${b.accessor ?? base}${b.path}`
659
670
  if (b.rest?.kind === 'object') {
660
671
  if (b.rest.exclude.length === 0) {
661
672
  // No sibling keys to omit. A fresh shallow clone — not a direct alias
@@ -714,19 +725,48 @@ export function wrapLoopParamAsAccessor(
714
725
  paramName: string,
715
726
  bindings?: readonly LoopParamBinding[],
716
727
  indexParam?: string | null,
728
+ shadowed?: ReadonlySet<string>,
717
729
  ): string {
730
+ // `shadowed`: names a nearer row rebinds (`rowBoundNames`), so inside that
731
+ // row they mean the nearer binding and keep their plain spelling (#3394).
732
+ const destructured = !!bindings && bindings.length > 0
733
+ const liveBindings = destructured && shadowed ? bindings.filter(b => !shadowed.has(b.name)) : bindings
734
+ const liveIndex = indexParam && shadowed?.has(indexParam) ? null : indexParam
718
735
  let result: string
719
- if (bindings && bindings.length > 0) {
720
- result = rewriteLoopBindingRefs(expr, bindings, '__bfItem()')
736
+ if (destructured) {
737
+ result = liveBindings && liveBindings.length > 0 ? rewriteLoopBindingRefs(expr, liveBindings, '__bfItem()') : expr
721
738
  } else {
722
- result = rewriteIdentifierAsAccessor(expr, paramName)
739
+ result = shadowed?.has(paramName) ? expr : rewriteIdentifierAsAccessor(expr, paramName)
723
740
  }
724
- if (indexParam && indexParam !== paramName) {
725
- result = wrapIndexParamAsAccessor(result, indexParam)
741
+ if (liveIndex && liveIndex !== paramName) {
742
+ result = wrapIndexParamAsAccessor(result, liveIndex)
726
743
  }
727
744
  return result
728
745
  }
729
746
 
747
+ /**
748
+ * A loop-param accessor rewrite that can be told which names a nearer row
749
+ * rebinds (#3394). Each wrap passes `shadowed` on to the enclosing loops'
750
+ * wraps it composes, so every ancestor rewrite skips them too.
751
+ */
752
+ export type ShadowableWrap = (expr: string, shadowed?: ReadonlySet<string>) => string
753
+
754
+ /** `a` and `b` together; `a` alone when `b` is empty or absent. */
755
+ export function unionNames(a: ReadonlySet<string>, b?: ReadonlySet<string>): ReadonlySet<string> {
756
+ return b && b.size > 0 ? new Set([...a, ...b]) : a
757
+ }
758
+
759
+ /**
760
+ * Every name the row of `loop` binds — its item (or destructure bindings),
761
+ * index and preamble locals — via `BindingScope.enterLoopRow`. Inside that
762
+ * row an enclosing loop's accessor rewrite must skip these names, or an
763
+ * inner `const name = …` that shadows an outer destructure binding becomes
764
+ * `const __bfItem().name = …` (#3394).
765
+ */
766
+ export function rowBoundNames(loop: LoopBindingSource): ReadonlySet<string> {
767
+ return BindingScope.EMPTY.enterLoopRow(loop).boundNames()
768
+ }
769
+
730
770
  /**
731
771
  * The index-only half of `wrapLoopParamAsAccessor` — same AST-aware
732
772
  * identifier rewrite (`rewriteIdentifierAsAccessor`), own identifier.
@@ -962,6 +1002,8 @@ export interface LoopParamSpec {
962
1002
  bindings?: readonly LoopParamBinding[]
963
1003
  /** This loop's index parameter name, when it declares one (#2859). */
964
1004
  index?: string | null
1005
+ /** Names a nearer row rebinds, left as written (#3394). */
1006
+ shadowed?: ReadonlySet<string>
965
1007
  }
966
1008
 
967
1009
  /**
@@ -991,8 +1033,40 @@ export function wrapExprWithLoopParams(expr: string, loopParams?: ReadonlyArray<
991
1033
  let result = expr
992
1034
  for (const p of loopParams) {
993
1035
  const spec = typeof p === 'string' ? { param: p } : p
994
- result = wrapLoopParamAsAccessor(result, spec.param, spec.bindings, spec.index)
1036
+ result = wrapLoopParamAsAccessor(result, spec.param, spec.bindings, spec.index, spec.shadowed)
995
1037
  }
996
1038
  return result
997
1039
  }
998
1040
 
1041
+ /**
1042
+ * Enclosing loop specs as seen inside the row of `loop`: each spec also
1043
+ * skips the names that row rebinds (`rowBoundNames`, #3394).
1044
+ */
1045
+ export function specsInsideRow(
1046
+ specs: ReadonlyArray<string | LoopParamSpec> | undefined,
1047
+ loop: LoopBindingSource,
1048
+ ): ReadonlyArray<string | LoopParamSpec> | undefined {
1049
+ if (!specs) return specs
1050
+ const names = rowBoundNames(loop)
1051
+ if (names.size === 0) return specs
1052
+ return specs.map(p => {
1053
+ const spec = typeof p === 'string' ? { param: p } : p
1054
+ const shadowed = spec.shadowed ? new Set([...spec.shadowed, ...names]) : names
1055
+ return { ...spec, shadowed }
1056
+ })
1057
+ }
1058
+
1059
+ /**
1060
+ * The bindings of a nested destructured `.map()` row, each reading through
1061
+ * the row's own accessor `__bfItem_<markerId>()` (#3397). Every nested row
1062
+ * then names its render callback's item accessor differently, so a row
1063
+ * inside another destructured row can still read the outer row's bindings.
1064
+ */
1065
+ export function withRowAccessor(
1066
+ bindings: readonly LoopParamBinding[] | undefined,
1067
+ markerId: string,
1068
+ ): readonly LoopParamBinding[] | undefined {
1069
+ if (!bindings || bindings.length === 0) return bindings
1070
+ const accessor = `__bfItem_${markerId}()`
1071
+ return bindings.map(b => ({ ...b, accessor }))
1072
+ }