@barefootjs/jsx 0.39.3 → 0.39.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 (68) 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/errors.d.ts +1 -0
  4. package/dist/errors.d.ts.map +1 -1
  5. package/dist/index.d.ts +2 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +335 -49
  8. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  9. package/dist/ir-to-client-js/control-flow/plan/build-composite-loop.d.ts.map +1 -1
  10. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  11. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +5 -0
  12. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  13. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +7 -0
  14. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  15. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  16. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +2 -0
  18. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  20. package/dist/ir-to-client-js/control-flow/stringify/composite-loop.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  22. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts +14 -0
  23. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/imports.d.ts +2 -2
  26. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts +3 -1
  28. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/safe-html.d.ts +6 -0
  31. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/types.d.ts +12 -0
  33. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  34. package/dist/nullable-signal-attr.d.ts +21 -0
  35. package/dist/nullable-signal-attr.d.ts.map +1 -1
  36. package/dist/profiler.d.ts +9 -1
  37. package/dist/profiler.d.ts.map +1 -1
  38. package/package.json +2 -2
  39. package/src/__tests__/boolean-result.test.ts +27 -0
  40. package/src/__tests__/csr-template-loop-shadow.test.ts +83 -0
  41. package/src/__tests__/profile-turn-markers.test.ts +22 -0
  42. package/src/__tests__/profiler.test.ts +10 -9
  43. package/src/__tests__/ssr-portal-ref-callback.test.ts +88 -13
  44. package/src/adapters/boolean-result.ts +89 -0
  45. package/src/errors.ts +11 -0
  46. package/src/index.ts +3 -0
  47. package/src/ir-to-client-js/collect-elements.ts +11 -3
  48. package/src/ir-to-client-js/control-flow/plan/build-composite-loop.ts +2 -0
  49. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +13 -0
  50. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +7 -2
  51. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +7 -0
  52. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  53. package/src/ir-to-client-js/control-flow/plan/loop.ts +2 -0
  54. package/src/ir-to-client-js/control-flow/shared.ts +2 -0
  55. package/src/ir-to-client-js/control-flow/stringify/branch-loop.ts +6 -3
  56. package/src/ir-to-client-js/control-flow/stringify/composite-loop.ts +7 -4
  57. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +21 -6
  58. package/src/ir-to-client-js/control-flow/stringify/insert.ts +6 -1
  59. package/src/ir-to-client-js/control-flow/stringify/loop.ts +55 -8
  60. package/src/ir-to-client-js/html-template.ts +59 -8
  61. package/src/ir-to-client-js/imports.ts +3 -1
  62. package/src/ir-to-client-js/phases/rest-attr-applications.ts +8 -2
  63. package/src/ir-to-client-js/reactivity.ts +1 -0
  64. package/src/ir-to-client-js/safe-html.ts +10 -0
  65. package/src/ir-to-client-js/types.ts +12 -0
  66. package/src/jsx-to-ir.ts +138 -32
  67. package/src/nullable-signal-attr.ts +46 -0
  68. package/src/profiler.ts +79 -10
@@ -101,7 +101,7 @@ function preambleLineForHandler(
101
101
  }
102
102
 
103
103
  export function stringifyEventDelegation(lines: string[], plan: EventDelegationPlan): void {
104
- const { containerVar, events, itemLookup, profileComponentName, ownHandlers } = plan
104
+ const { containerVar, events, itemLookup, profileComponentName, ownHandlers, relayRowPortals } = plan
105
105
  const eventsByName = new Map<string, LoopChildEvent[]>()
106
106
  for (const ev of events) {
107
107
  if (!eventsByName.has(ev.eventName)) eventsByName.set(ev.eventName, [])
@@ -121,10 +121,14 @@ export function stringifyEventDelegation(lines: string[], plan: EventDelegationP
121
121
  const ownHandlerCall = ownHandler
122
122
  ? withTurn(`(${ownHandler.handler.trim()})(__bfEvt)`, profileComponentName, ownHandler.slotId, ownHandler.eventName)
123
123
  : null
124
- if (useCapture) {
125
- lines.push(` if (${containerVar}) ${containerVar}.addEventListener('${eventName}', (__bfEvt) => {`)
124
+ const listenedName = useCapture ? eventName : domEventName
125
+ if (relayRowPortals) {
126
+ // Named so the same listener can also be relayed to the elements rows
127
+ // portal out of the container (#3318).
128
+ lines.push(` if (${containerVar}) {`)
129
+ lines.push(` const __bfDl = (__bfEvt) => {`)
126
130
  } else {
127
- lines.push(` if (${containerVar}) ${containerVar}.addEventListener('${domEventName}', (__bfEvt) => {`)
131
+ lines.push(` if (${containerVar}) ${containerVar}.addEventListener('${listenedName}', (__bfEvt) => {`)
128
132
  }
129
133
  lines.push(` const target = __bfEvt.target`)
130
134
  for (const ev of evs) {
@@ -137,7 +141,12 @@ export function stringifyEventDelegation(lines: string[], plan: EventDelegationP
137
141
  // the `container.contains(...)` guard rejects the foreign match and the
138
142
  // handler falls through to the correct branch.
139
143
  lines.push(` const ${childVar}El = target.closest('[bf="${ev.childSlotId}"]')`)
140
- lines.push(` if (${childVar}El && ${containerVar}.contains(${childVar}El)) {`)
144
+ // A row-portaled element sits outside the container; the registry
145
+ // vouches for it instead (#3318).
146
+ const inContainer = relayRowPortals
147
+ ? `(${containerVar}.contains(${childVar}El) || isRowPortalOf(${childVar}El, ${containerVar}))`
148
+ : `${containerVar}.contains(${childVar}El)`
149
+ lines.push(` if (${childVar}El && ${inContainer}) {`)
141
150
  const handlerCall = withTurn(`(${ev.handler.trim()})(__bfEvt)`, profileComponentName, ev.childSlotId, ev.eventName)
142
151
  switch (itemLookup.kind) {
143
152
  case 'keyed':
@@ -179,7 +188,13 @@ export function stringifyEventDelegation(lines: string[], plan: EventDelegationP
179
188
  // own handler still fires — same as today's separate listener.
180
189
  lines.push(` if (!__bfEvt.cancelBubble) { ${ownHandlerCall} }`)
181
190
  }
182
- if (useCapture) {
191
+ if (relayRowPortals) {
192
+ const captureArg = useCapture ? ', true' : ''
193
+ lines.push(` }`)
194
+ lines.push(` ${containerVar}.addEventListener('${listenedName}', __bfDl${captureArg})`)
195
+ lines.push(` relayRowPortalEvents(${containerVar}, '${listenedName}', __bfDl${captureArg})`)
196
+ lines.push(` }`)
197
+ } else if (useCapture) {
183
198
  lines.push(` }, true)`)
184
199
  } else {
185
200
  lines.push(` })`)
@@ -162,7 +162,12 @@ function emitArmBody(
162
162
  for (const [slotId, attrs] of attrsBySlot) {
163
163
  const v = varSlotId(slotId)
164
164
  const elVar = `__ra_${v}`
165
- lines.push(`${indent}{ const ${elVar} = qsa(__branchScope, '[bf="${slotId}"]')`)
165
+ // A parent-owned slot passes the components it is forwarded into, so
166
+ // the lookup can cross into their scopes without resolving another
167
+ // component's same-numbered forwarded element (#3324).
168
+ const receivers = attrs[0].receiverSlotIds
169
+ const receiverArg = receivers && receivers.length > 0 ? `, ${JSON.stringify(receivers)}` : ''
170
+ lines.push(`${indent}{ const ${elVar} = qsa(__branchScope, '[bf="${slotId}"]'${receiverArg})`)
166
171
  lines.push(`${indent}${DEDUP_STORE_DECL}`)
167
172
  lines.push(`${indent}if (${elVar}) {`)
168
173
  let ordinal = 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(` }`)
@@ -8,14 +8,14 @@ import { toHtmlAttrName, attrValueToString, quotePropName, PROPS_PARAM, DATA_BF_
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
 
@@ -2327,6 +2327,41 @@ function mergeCsrNullUnsafe(ctx: ClientJsContext, unsafeLocalNames: Set<string>
2327
2327
  return merged ?? unsafeLocalNames
2328
2328
  }
2329
2329
 
2330
+ /**
2331
+ * The substitutions visible inside a loop row whose bindings are
2332
+ * `boundHere`. A name the row binds is dropped: it means the row binding
2333
+ * there, not the outer signal / memo / const. An entry the row keeps is
2334
+ * spliced INTO the row, so its replacement must not mention a name the row
2335
+ * binds either: a memo `label = () => s()` read as `label()` under a row
2336
+ * param `s` would otherwise splice `s()` where `s` is the row item (#3352).
2337
+ * Such a replacement is first resolved against the outer `env`, the scope
2338
+ * the memo / const was declared in, so its own references are already
2339
+ * substituted before it reaches the row.
2340
+ *
2341
+ * A resolved replacement can still name a row binding when the name is not
2342
+ * a substitution at all (a module-level helper the row param shadows). Those
2343
+ * entries are returned in `hoisted`: the caller evaluates them once outside
2344
+ * the row, where the names still mean what they meant at the declaration.
2345
+ */
2346
+ function closeOverLoopBindings(
2347
+ env: CsrEnv,
2348
+ boundHere: ReadonlySet<string>,
2349
+ ): { substitutions: Map<string, CsrSubstitution>; hoisted: string[] } {
2350
+ const substitutions = new Map<string, CsrSubstitution>()
2351
+ const hoisted: string[] = []
2352
+ for (const [name, sub] of env.substitutions) {
2353
+ if (boundHere.has(name)) continue
2354
+ if (!setIntersects(extractFreeIdentifiersFromText(sub.replacement), boundHere)) {
2355
+ substitutions.set(name, sub)
2356
+ continue
2357
+ }
2358
+ const closed = csrSubstitute(sub.replacement, env)
2359
+ if (setIntersects(closed.freeIdentifiers, boundHere)) hoisted.push(name)
2360
+ substitutions.set(name, { ...sub, replacement: closed.rewritten, freeIdentifiers: closed.freeIdentifiers })
2361
+ }
2362
+ return { substitutions, hoisted }
2363
+ }
2364
+
2330
2365
  /**
2331
2366
  * Build the per-component CSR substitution env (signals + memos + inlinable
2332
2367
  * constants), matching what `generateCsrTemplate` builds. Shared so the
@@ -2763,10 +2798,26 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2763
2798
  // hide an outer same-named const), not a reactivity classifier.
2764
2799
  const childScope = (opts.scope ?? BindingScope.EMPTY).enterLoopRow(node)
2765
2800
  const boundHere = childScope.boundNames()
2766
- const childEnv: CsrEnv = {
2767
- ...env,
2768
- substitutions: new Map([...env.substitutions].filter(([name]) => !boundHere.has(name))),
2801
+ const { substitutions: childSubstitutions, hoisted } = closeOverLoopBindings(env, boundHere)
2802
+ // Each hoisted entry is read once, outside the row, into a parameter
2803
+ // the row's substitution points at (#3352). Its value cannot depend on
2804
+ // the row: it was declared outside the loop.
2805
+ const hoistParams: string[] = []
2806
+ const hoistValues: string[] = []
2807
+ for (const name of hoisted) {
2808
+ const sub = env.substitutions.get(name)!
2809
+ const value = transformExpr(sub.kind === 'call' ? `${name}()` : name)
2810
+ // An init-only value stays on the resolved substitution, whose free
2811
+ // identifiers still name the init-only local, so a row expression
2812
+ // reading it is deferred like any other unsafe read rather than
2813
+ // handed a bound `undefined` to dereference.
2814
+ if (value === UNSAFE_TEMPLATE_EXPR) continue
2815
+ const param = `__bf_outer_${name}`
2816
+ hoistParams.push(param)
2817
+ hoistValues.push(value)
2818
+ childSubstitutions.set(name, { kind: sub.kind, replacement: param, freeIdentifiers: new Set([param]) })
2769
2819
  }
2820
+ const childEnv: CsrEnv = { ...env, substitutions: childSubstitutions }
2770
2821
  const recurseInLoopBody = (n: IRNode): string => generateCsrTemplateWithOpts(n, {
2771
2822
  ...opts,
2772
2823
  loopDepth: loopDepth + 1,
@@ -2816,14 +2867,14 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2816
2867
  // Leaf `key` → `data-key` — see the irToHtmlTemplate site above.
2817
2868
  renderLeaf: (ir) => recurseInLoopBody(leafKeyAsDataKeyAttr(ir)),
2818
2869
  })
2819
- mapExpr = interp(mappedRowsMarkup(iterArrayExpr, 'flatMap', node.flatMapCallback.params, body))
2870
+ mapExpr = interp(withOuterBindings(hoistParams, hoistValues, mappedRowsMarkup(iterArrayExpr, 'flatMap', node.flatMapCallback.params, body)))
2820
2871
  } else if (node.preamble) {
2821
2872
  // Stage 3 / D4 — template-variant js text with the props rewrite
2822
2873
  // applied per segment; JSX leaves render via the loop-body recursion.
2823
2874
  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}\` }`))
2875
+ mapExpr = interp(withOuterBindings(hoistParams, hoistValues, mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `{ ${preamble} return \`${childTemplate}\` }`)))
2825
2876
  } else {
2826
- mapExpr = interp(mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `\`${childTemplate}\``))
2877
+ mapExpr = interp(withOuterBindings(hoistParams, hoistValues, mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `\`${childTemplate}\``)))
2827
2878
  }
2828
2879
  return `<!--${loopStartMarker(node.markerId)}-->${mapExpr}<!--${loopEndMarker(node.markerId)}-->`
2829
2880
  }
@@ -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.
@@ -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. */
package/src/jsx-to-ir.ts CHANGED
@@ -4561,6 +4561,128 @@ function applyLoopKeyAttr(node: IRNode, name: string, value: string): void {
4561
4561
  }
4562
4562
  }
4563
4563
 
4564
+ /**
4565
+ * Give every SSR-portal element (`ssrPortalOwnerScope`) in a `.map()` row
4566
+ * the row's key attribute (#3318). SSR places such an element at its portal
4567
+ * outlet, outside the row, so its slot and owner scope alone cannot say
4568
+ * which row it belongs to; the row key on the element itself lets
4569
+ * hydration pair it with its row (`claimRowPortals`) and lets the loop's
4570
+ * delegated listener resolve the row from the element
4571
+ * (`closest('[data-key]')`). Every SSR adapter renders `IRElement.keyAttr`,
4572
+ * and the client templates render it from a `key` attribute, so the element
4573
+ * also gets a copy of the row root's `key` attribute; no adapter changes
4574
+ * are needed.
4575
+ *
4576
+ * Only a keyed top-level loop (`depth === 0`) is supported. A nested loop's
4577
+ * row key is not unique on its own and an unkeyed row has none, so a
4578
+ * portal element there is refused (BF064) rather than rendered at an
4579
+ * outlet nothing can pair. So is one forwarded as a child component's
4580
+ * `children` (or inside a provider / `<Async>`), where the row's key is not
4581
+ * this element's to render; one inside a reactive conditional in the row,
4582
+ * whose `ref` the conditional's branch runs rather than the row; and the
4583
+ * row root itself, whose move leaves no inline row for hydration to find.
4584
+ * Nested loops are skipped: their own construction applies this to their
4585
+ * rows (a nested loop's portaled row root is refused here, as it already
4586
+ * carries its `keyAttr`).
4587
+ */
4588
+ function applyRowPortalKeyAttrs(
4589
+ children: IRNode[],
4590
+ key: string | null,
4591
+ depth: number,
4592
+ ctx: TransformContext,
4593
+ ): void {
4594
+ const refuse = (el: IRElement, reason: string): void => {
4595
+ ctx.analyzer.errors.push(
4596
+ createError(ErrorCodes.ROW_PORTAL_UNPAIRABLE, el.loc, {
4597
+ message:
4598
+ `A ref callback portals <${el.tag}> out of a .map() row, but ${reason}, so hydration cannot pair the ` +
4599
+ 'portaled element with its row and its event handlers would stop running after hydration.',
4600
+ suggestion: {
4601
+ message:
4602
+ 'Portal an element inside the root of a keyed top-level .map() row (`key={…}` on the row root), ' +
4603
+ "outside reactive conditionals and child components' children, or move the portal outside the loop.",
4604
+ escape: [{ kind: 'rewrite' }],
4605
+ },
4606
+ }),
4607
+ )
4608
+ }
4609
+ // `blocked` names why an element at this position cannot be paired with
4610
+ // its row; `null` means it can.
4611
+ const visit = (node: IRNode, blocked: string | null): void => {
4612
+ switch (node.type) {
4613
+ case 'element':
4614
+ if (node.ssrPortalOwnerScope) {
4615
+ // `applyLoopKeyAttr` stamps the row root (of this loop, or of a
4616
+ // nested loop already built) before this pass: a portaled row root
4617
+ // leaves no inline row for hydration to find.
4618
+ if (node.keyAttr) refuse(node, 'it is the root element of the row')
4619
+ else if (blocked) refuse(node, blocked)
4620
+ else if (key === null) refuse(node, 'the loop has no `key`')
4621
+ else if (depth > 0) refuse(node, 'the loop is nested inside another loop')
4622
+ else {
4623
+ node.keyAttr = { name: keyAttrName(depth), value: key }
4624
+ // The client templates render the row key from a `key` attribute
4625
+ // gated on `keyAttr`, as they do for the row root, so the element
4626
+ // carries a copy of the row root's.
4627
+ if (!node.attrs.some((a) => a.name === 'key')) {
4628
+ node.attrs.push(rowKeyAttribute(children) ?? { name: 'key', value: { kind: 'expression', expr: key }, loc: node.loc })
4629
+ }
4630
+ }
4631
+ }
4632
+ for (const c of node.children) visit(c, blocked)
4633
+ return
4634
+ case 'fragment':
4635
+ for (const c of node.children) visit(c, blocked)
4636
+ return
4637
+ case 'conditional': {
4638
+ // A reactive conditional (`slotId`) owns its branch's refs, which
4639
+ // the row's ref collection skips, so the row cannot adopt them.
4640
+ const inner = blocked ?? (node.slotId ? 'it is rendered inside a reactive conditional in the row' : null)
4641
+ visit(node.whenTrue, inner)
4642
+ visit(node.whenFalse, inner)
4643
+ return
4644
+ }
4645
+ case 'if-statement':
4646
+ visit(node.consequent, blocked)
4647
+ if (node.alternate) visit(node.alternate, blocked)
4648
+ return
4649
+ case 'component':
4650
+ case 'provider':
4651
+ for (const c of node.children) visit(c, blocked ?? "it is rendered inside another component's children")
4652
+ return
4653
+ case 'async':
4654
+ visit(node.fallback, blocked ?? "it is rendered inside another component's children")
4655
+ for (const c of node.children) visit(c, blocked ?? "it is rendered inside another component's children")
4656
+ return
4657
+ default:
4658
+ return
4659
+ }
4660
+ }
4661
+ for (const c of children) visit(c, null)
4662
+ }
4663
+
4664
+ /** The `key` attribute the row's key was read from (`extractLoopKey`), when it is on an element. */
4665
+ function rowKeyAttribute(children: IRNode[]): IRAttribute | null {
4666
+ const find = (node: IRNode): IRAttribute | null => {
4667
+ switch (node.type) {
4668
+ case 'element':
4669
+ return node.attrs.find((a) => a.name === 'key') ?? null
4670
+ case 'conditional':
4671
+ return find(node.whenTrue)
4672
+ case 'fragment': {
4673
+ const first = node.children.find(
4674
+ (c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim())
4675
+ )
4676
+ return first ? find(first) : null
4677
+ }
4678
+ default:
4679
+ return null
4680
+ }
4681
+ }
4682
+ const first = children.find((c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim()))
4683
+ return first ? find(first) : null
4684
+ }
4685
+
4564
4686
  function loopBodyItemConditional(children: IRNode[]): IRConditional | null {
4565
4687
  const real = children.filter(
4566
4688
  (c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim())
@@ -5419,6 +5541,7 @@ function transformMapCall(
5419
5541
  applyLoopKeyAttr(children[0], resolvedKeyAttrName, key)
5420
5542
  }
5421
5543
  }
5544
+ applyRowPortalKeyAttrs(children, key, depth, ctx)
5422
5545
 
5423
5546
  // Stage 3 / D5 (spec/callback-fidelity.md) — the keyFn is hoisted: `mapArray`
5424
5547
  // computes it from the raw item BEFORE the callback body runs, so the key must
@@ -7092,14 +7215,6 @@ interface LocalCallback {
7092
7215
  interface RefCallback extends LocalCallback {
7093
7216
  /** Bound by name (`ref={handleMount}`) rather than written inline. */
7094
7217
  named: boolean
7095
- /**
7096
- * True only for a named callback declared in the `ref`'s innermost
7097
- * enclosing function scope; false for an inline callback and for one
7098
- * `findNamedCallback`'s outward walk found further out (e.g. a `ref` in a
7099
- * `.map()` row naming a component-body handler). BF063 ignores this;
7100
- * `isSsrPortalRefCallback` requires it.
7101
- */
7102
- innermostScope: boolean
7103
7218
  }
7104
7219
 
7105
7220
  /**
@@ -7111,11 +7226,11 @@ interface RefCallback extends LocalCallback {
7111
7226
  function resolveRefCallback(refExpr: ts.Expression): RefCallback | undefined {
7112
7227
  const expr = unwrapTransparentTsWrappers(refExpr)
7113
7228
  if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) {
7114
- return { param: firstSimpleParamName(expr), body: expr.body, named: false, innermostScope: false }
7229
+ return { param: firstSimpleParamName(expr), body: expr.body, named: false }
7115
7230
  }
7116
7231
  if (!ts.isIdentifier(expr)) return undefined
7117
- const resolved = findNamedCallback(expr)
7118
- return resolved && { ...resolved.callback, named: true, innermostScope: resolved.innermostScope }
7232
+ const callback = findNamedCallback(expr)
7233
+ return callback && { ...callback, named: true }
7119
7234
  }
7120
7235
 
7121
7236
  type FunctionLike = ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration
@@ -7147,20 +7262,13 @@ function findEnclosingFunctionLike(node: ts.Node): FunctionLike | undefined {
7147
7262
  * Never searches a nested function's own body: two sibling components in the
7148
7263
  * same file can each declare their own, unrelated `handleMount`, and reaching
7149
7264
  * into the wrong one's closure would misattribute its behavior to this `ref`.
7150
- * `innermostScope` reports whether the deciding scope was the `ref`'s own
7151
- * innermost one: BF063 accepts any scope, the SSR-portal recognition only
7152
- * that one (see `isSsrPortalRefCallback`).
7153
7265
  */
7154
- function findNamedCallback(
7155
- ident: ts.Identifier,
7156
- ): { callback: LocalCallback; innermostScope: boolean } | undefined {
7157
- const innermost = findEnclosingFunctionLike(ident)
7158
- for (let fn = innermost; fn; fn = findEnclosingFunctionLike(fn)) {
7266
+ function findNamedCallback(ident: ts.Identifier): LocalCallback | undefined {
7267
+ for (let fn = findEnclosingFunctionLike(ident); fn; fn = findEnclosingFunctionLike(fn)) {
7159
7268
  if (fn.parameters.some(p => bindingDeclares(p.name, ident.text))) return undefined
7160
7269
  const decl = fn.body && findScopeDeclaration(ident.text, fn.body)
7161
7270
  if (!decl) continue
7162
- const callback = localCallbackOf(decl)
7163
- return callback && { callback, innermostScope: fn === innermost }
7271
+ return localCallbackOf(decl)
7164
7272
  }
7165
7273
  return undefined
7166
7274
  }
@@ -7238,24 +7346,22 @@ function bindingDeclares(binding: ts.BindingName, name: string): boolean {
7238
7346
  * (the "worth the scope-walk?" open question from #3059) is therefore
7239
7347
  * left for when a real caller needs it.
7240
7348
  *
7241
- * The callback must be declared in the `ref`'s INNERMOST enclosing
7242
- * function scope (`RefCallback.innermostScope`) — BF063 shares the
7243
- * resolution but may walk further out; this recognition may not. The gate
7244
- * only restores the scope limit recognition had before BF063 widened the
7245
- * lookup, so sharing the resolution does not widen what is recognized. It
7246
- * is not a `.map()`-row guard: a portal element inside a row is broken
7247
- * either way (a row-declared callback is still recognized, and still
7248
- * breaks) — the known limitation `loop-row-ref-portal`
7249
- * (`packages/adapter-tests/limitations/loop-row-ref-portal.ts`).
7349
+ * The callback may be declared in any enclosing function scope
7350
+ * (`findNamedCallback`, shared with BF063): a `ref` in a `.map()` row
7351
+ * naming a handler declared in the component body is recognized too. The
7352
+ * resolution never crosses into a sibling function's body and stops at a
7353
+ * shadowing parameter or non-function binding, so the callback found is
7354
+ * the one that runs.
7250
7355
  *
7251
7356
  * A match makes `element.ssrPortalOwnerScope` true, which every adapter
7252
7357
  * (#3119) uses to place the element's SSR markup at its own portal
7253
- * outlet instead of inline.
7358
+ * outlet instead of inline. Inside a keyed top-level `.map()` row the
7359
+ * element also carries the row key (`applyRowPortalKeyAttrs`, #3318), so
7360
+ * hydration pairs it with its row; a nested or unkeyed row refuses (BF064).
7254
7361
  */
7255
7362
  function isSsrPortalRefCallback(callback: RefCallback | undefined): boolean {
7256
7363
  return (
7257
7364
  !!callback?.named &&
7258
- callback.innermostScope &&
7259
7365
  !!callback.param &&
7260
7366
  containsSsrPortalPlacementCall(callback.body, callback.param)
7261
7367
  )