@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
@@ -0,0 +1,83 @@
1
+ /**
2
+ * A memo inlined into the CSR template inside a `.map()` row whose binding
3
+ * shadows a name the memo reads (#3352). The memo body must resolve in its
4
+ * declaration scope, not against the row binding.
5
+ */
6
+
7
+ import { describe, test, expect } from 'bun:test'
8
+ import { compileJSX } from '../index'
9
+ import { HonoAdapter } from '../../../adapter-hono/src/adapter'
10
+
11
+ /** Compile `source` and evaluate its CSR template lambda with `props`. */
12
+ function renderTemplate(source: string, name: string, props: Record<string, unknown>): string {
13
+ const result = compileJSX(source, 'loop-shadow.tsx', { adapter: new HonoAdapter() })
14
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
15
+ const clientJs = result.files.filter(f => f.type === 'clientJs').map(f => f.content).join('\n')
16
+ const line = clientJs.split('\n').find(l => l.startsWith(`hydrate('${name}'`))
17
+ expect(line).toBeDefined()
18
+ const lambda = line!.slice(line!.indexOf('template: ') + 'template: '.length, line!.lastIndexOf(' })'))
19
+ const helpers = clientJs.slice(0, clientJs.indexOf('export function init'))
20
+ .split('\n').filter(l => /^(var|const|function) /.test(l)).join('\n')
21
+ const escape = (v: unknown) => String(v)
22
+ const template = new Function('escapeAttr', 'escapeText', `${helpers}\nreturn (${lambda})`)(escape, escape)
23
+ return template(props)
24
+ }
25
+
26
+ describe('CSR template: memo read under a shadowing loop binding (#3352)', () => {
27
+ test("resolves the memo body's dependency to the signal, not the row param", () => {
28
+ const html = renderTemplate(`
29
+ 'use client'
30
+ import { createMemo, createSignal } from '@barefootjs/client'
31
+ export function C(props: { rows: string[] }) {
32
+ const [s] = createSignal('outer')
33
+ const label = createMemo(() => s() + '!')
34
+ return <ul>{props.rows.map(s => <li key={s} title={label()}>{s}</li>)}</ul>
35
+ }
36
+ `, 'C', { rows: ['x', 'y'] })
37
+ expect(html).toContain('title="outer!"')
38
+ expect(html).not.toContain('title="x')
39
+ })
40
+
41
+ test('evaluates the memo outside the row when its body reads a module helper the row param shadows', () => {
42
+ const html = renderTemplate(`
43
+ 'use client'
44
+ import { createMemo, createSignal } from '@barefootjs/client'
45
+ function fmt(v: string) { return '[' + v + ']' }
46
+ export function C(props: { rows: string[] }) {
47
+ const [s] = createSignal('outer')
48
+ const label = createMemo(() => fmt(s()))
49
+ return <ul>{props.rows.map(fmt => <li key={fmt} title={label()}>{fmt}</li>)}</ul>
50
+ }
51
+ `, 'C', { rows: ['x', 'y'] })
52
+ expect(html).toContain('title="[outer]"')
53
+ })
54
+
55
+ test('defers a row read of an init-only memo instead of hoisting `undefined`', () => {
56
+ const html = renderTemplate(`
57
+ 'use client'
58
+ import { createMemo } from '@barefootjs/client'
59
+ function fmt(v: string) { return '[' + v + ']' }
60
+ export function C(props: { rows: string[] }) {
61
+ const local = () => 'outer'
62
+ const label = createMemo(() => fmt(local()))
63
+ return <ul>{props.rows.map(fmt => <li key={fmt}>{label().length}</li>)}</ul>
64
+ }
65
+ `, 'C', { rows: ['x'] })
66
+ expect(html).not.toContain('__bf_outer_')
67
+ expect(html).toContain('<li')
68
+ })
69
+
70
+ test('a row param shadowing the memo itself reads the row item', () => {
71
+ const html = renderTemplate(`
72
+ 'use client'
73
+ import { createMemo, createSignal } from '@barefootjs/client'
74
+ export function C(props: { rows: string[] }) {
75
+ const [s] = createSignal('outer')
76
+ const label = createMemo(() => s() + '!')
77
+ return <ul>{props.rows.map(label => <li key={label} title={label}>{s()}</li>)}</ul>
78
+ }
79
+ `, 'C', { rows: ['x', 'y'] })
80
+ expect(html).toContain('title="x"')
81
+ expect(html).toContain('outer')
82
+ })
83
+ })
@@ -52,3 +52,25 @@ describe('profile mode on (SR3)', () => {
52
52
  expect(importLine).toContain('endTurn')
53
53
  })
54
54
  })
55
+
56
+ describe('rest-spread event forwarding (#3376)', () => {
57
+ const spread = `
58
+ 'use client'
59
+ interface Props { onClick?: () => void }
60
+ export function SpreadButton(props: Props) {
61
+ return <button {...props}>Increment</button>
62
+ }
63
+ `
64
+ const compile = (profile: boolean) =>
65
+ compileJSX(spread, 'SpreadButton.tsx', { adapter, profile }).files.find(f => f.type === 'clientJs')!.content
66
+
67
+ test('profile mode names the spread site so the runtime can open a turn per handler', () => {
68
+ expect(compile(true)).toContain('applyRestAttrs(_s0, _p, [], "SpreadButton#handler:s0")')
69
+ })
70
+
71
+ test('profile mode off passes no site (zero instrumentation in production)', () => {
72
+ const off = compile(false)
73
+ expect(off).toContain('applyRestAttrs(_s0, _p, [])')
74
+ expect(off).not.toContain('#handler:')
75
+ })
76
+ })
@@ -564,8 +564,9 @@ describe('agent contract: status, findings, guidance (#1841)', () => {
564
564
 
565
565
  test('a clean run is status ok with no findings', () => {
566
566
  n = 0
567
- // One memo run in a turn → runsPerTurn 1 → not hot, nothing flagged.
568
- const turn = 'Calc#handler:s0:click'
567
+ // One memo run in a turn → runsPerTurn 1 → not hot, nothing flagged. The
568
+ // turn id is the button's real handler id, so coverage reads 1/1.
569
+ const turn = 'Calc#handler:s1:click'
569
570
  const events: ProfilerEvent[] = [
570
571
  ev('turnBegin', { handlerId: turn }),
571
572
  ev('effectEnter', { subscriber: 'Calc#memo:a', turn }),
@@ -614,18 +615,18 @@ describe('agent contract: status, findings, guidance (#1841)', () => {
614
615
  expect(gap.nextCommands.every(c => !c.includes('graph Calc'))).toBe(true)
615
616
  })
616
617
 
617
- test('coverage.ratio is clamped to 1 when the stream over-counts handlers', () => {
618
+ test('a turn id the IR does not list joins the inventory, so the ratio stays within 1', () => {
618
619
  n = 0
619
- // Calc exposes a single handler (handlersTotal 1), but a malformed stream
620
- // reports two distinct turn ids — without clamping the ratio would be 2.0
621
- // and silently pass a `--min-coverage` gate it shouldn't.
620
+ // Calc lists a single handler, but the stream reports a second distinct
621
+ // turn id (#3377). It is a handler site that ran, so it counts on both
622
+ // sides: 2/2, never 2/1 — the ratio can't pass a `--min-coverage` gate it
623
+ // shouldn't.
622
624
  const events: ProfilerEvent[] = [
623
- ev('effectEnter', { subscriber: 'Calc#memo:a', turn: 'Calc#handler:s0:click' }),
625
+ ev('effectEnter', { subscriber: 'Calc#memo:a', turn: 'Calc#handler:s1:click' }),
624
626
  ev('effectEnter', { subscriber: 'Calc#memo:a', turn: 'Calc#handler:s9:click' }),
625
627
  ]
626
628
  const r = buildProfileReport({ source: src, filePath: 'Calc.tsx', scenario: 'auto', events })
627
- expect(r.coverage.ratio).toBe(1)
628
- expect(r.coverage.ratio).toBeLessThanOrEqual(1)
629
+ expect(r.coverage).toMatchObject({ handlersFired: 2, handlersTotal: 2, ratio: 1 })
629
630
  })
630
631
 
631
632
  test('a zero-turn run emits guidance pointing at a story file', () => {
@@ -28,6 +28,25 @@ function rootFor(src: string, componentName: string): IRNode {
28
28
  return node
29
29
  }
30
30
 
31
+ /** `keyAttr` of every flagged element, in document order. */
32
+ function portalKeyAttrs(node: IRNode): Array<IRElement['keyAttr']> {
33
+ const out: Array<IRElement['keyAttr']> = []
34
+ const visit = (n: IRNode): void => {
35
+ if (n.type === 'element' && (n as IRElement).ssrPortalOwnerScope) out.push((n as IRElement).keyAttr)
36
+ if ('children' in n && Array.isArray((n as { children?: IRNode[] }).children)) {
37
+ for (const c of (n as { children: IRNode[] }).children) visit(c)
38
+ }
39
+ }
40
+ visit(node)
41
+ return out
42
+ }
43
+
44
+ /** Error codes `compileJSX` reports for `src`. */
45
+ function errorCodes(src: string): string[] {
46
+ const result = compileJSX(src.trimStart(), 'T.tsx', { adapter: new TestAdapter() })
47
+ return result.errors.map(e => e.code)
48
+ }
49
+
31
50
  function flaggedRefs(node: IRNode): string[] {
32
51
  const out: string[] = []
33
52
  const visit = (n: IRNode): void => {
@@ -176,18 +195,12 @@ export function Overlay() {
176
195
  expect(flaggedRefs(rootFor(src, 'Overlay'))).toEqual(['handleMount'])
177
196
  })
178
197
 
179
- // BF063 resolves a `ref` name outward through every enclosing function
180
- // scope; the portal recognition keeps the pre-BF063 limit (the callback
181
- // must be declared in the ref's innermost function scope) so sharing the
182
- // resolution does not widen what is recognized. These two tests pin that
183
- // scope limit only. A portal element inside a `.map()` row is broken
184
- // either way — the second test's row-declared callback is still
185
- // recognized and still breaks the row's hydration — which is the
186
- // registered known limitation `loop-row-ref-portal`
187
- // (`packages/adapter-tests/limitations/loop-row-ref-portal.ts`, fixture
188
- // `row-portal-ref`): the control pins today's behaviour as a known gap,
189
- // not as intended behaviour.
190
- test('does not flag a .map() row ref naming a portal callback declared in the component body', () => {
198
+ // The portal recognition shares BF063's resolution, which walks outward
199
+ // through every enclosing function scope (#3318): a `.map()` row ref
200
+ // naming a component-body portal callback is recognized like a
201
+ // row-declared one, and the flagged element carries the row key so
202
+ // hydration can pair it with its row.
203
+ test('flags a .map() row ref naming a portal callback declared in the component body', () => {
191
204
  const ir = root(`
192
205
  'use client'
193
206
  import { createPortal } from '@barefootjs/client'
@@ -196,7 +209,8 @@ export function List(props: { rows: string[] }) {
196
209
  return <ul>{props.rows.map(r => (<li key={r}><div ref={mountContent}>{r}</div></li>))}</ul>
197
210
  }
198
211
  `)
199
- expect(flaggedRefs(ir)).toEqual([])
212
+ expect(flaggedRefs(ir)).toEqual(['mountContent'])
213
+ expect(portalKeyAttrs(ir)).toEqual([{ name: 'data-key', value: 'r' }])
200
214
  })
201
215
 
202
216
  test('still flags a .map() row ref naming a portal callback declared in the row callback itself', () => {
@@ -216,4 +230,65 @@ export function List(props: { rows: string[] }) {
216
230
  `)
217
231
  expect(flaggedRefs(ir)).toEqual(['mountContent'])
218
232
  })
233
+
234
+ describe('row portals (#3318)', () => {
235
+ const portalRow = (loop: string) => `
236
+ 'use client'
237
+ import { createPortal, createSignal } from '@barefootjs/client'
238
+ export function List(props: { rows: string[]; groups: string[][] }) {
239
+ const [open] = createSignal(true)
240
+ const mountContent = (el: HTMLElement) => { createPortal(el, document.body, { ownerScope: 'x' }) }
241
+ return <ul>{${loop}}</ul>
242
+ }
243
+ `
244
+
245
+ test('keys the portaled element of a keyed top-level row without an error', () => {
246
+ expect(errorCodes(portalRow(`props.rows.map(r => <li key={r}><button ref={mountContent}>{r}</button></li>)`))).toEqual([])
247
+ })
248
+
249
+ test('refuses an unkeyed row (BF064)', () => {
250
+ expect(errorCodes(portalRow(`props.rows.map(r => <li><button ref={mountContent}>{r}</button></li>)`))).toContain('BF064')
251
+ })
252
+
253
+ test('refuses a nested row (BF064)', () => {
254
+ expect(
255
+ errorCodes(portalRow(
256
+ `props.groups.map((g, i) => <li key={i}><ol>{g.map(r => <li key={r}><button ref={mountContent}>{r}</button></li>)}</ol></li>)`,
257
+ )),
258
+ ).toContain('BF064')
259
+ })
260
+
261
+ test('refuses a portaled row root (BF064)', () => {
262
+ expect(errorCodes(portalRow(`props.rows.map(r => <button key={r} ref={mountContent}>{r}</button>)`))).toContain('BF064')
263
+ })
264
+
265
+ test('refuses a portaled row root of a nested loop (BF064)', () => {
266
+ expect(
267
+ errorCodes(portalRow(
268
+ `props.groups.map((g, i) => <li key={i}>{g.map(r => <button key={r} ref={mountContent}>{r}</button>)}</li>)`,
269
+ )),
270
+ ).toContain('BF064')
271
+ })
272
+
273
+ test('refuses a portal inside a reactive conditional in the row (BF064)', () => {
274
+ expect(
275
+ errorCodes(portalRow(
276
+ `props.rows.map(r => <li key={r}>{open() ? <button ref={mountContent}>{r}</button> : null}</li>)`,
277
+ )),
278
+ ).toContain('BF064')
279
+ })
280
+
281
+ test('does not touch a portal element outside any loop', () => {
282
+ const ir = root(`
283
+ 'use client'
284
+ import { createPortal } from '@barefootjs/client'
285
+ export function P() {
286
+ const mountContent = (el: HTMLElement) => { createPortal(el, document.body, { ownerScope: 'x' }) }
287
+ return <div><div ref={mountContent} /></div>
288
+ }
289
+ `)
290
+ expect(flaggedRefs(ir)).toEqual(['mountContent'])
291
+ expect(portalKeyAttrs(ir)).toEqual([undefined])
292
+ })
293
+ })
219
294
  })
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Backend-neutral boolean-result classification shared by the adapters whose
3
+ * host language has no boolean type (Mojolicious, Xslate: Perl renders a
4
+ * comparison as `''` / `1` and the literal `false` as `0`). Both adapters
5
+ * route a boolean-shaped attribute value through their `bool_str` runtime
6
+ * helper; this module decides which `ParsedExpr` shapes are boolean-shaped
7
+ * and rewrites a ternary that only PARTLY is (#3349).
8
+ *
9
+ * Detected boolean-result shapes:
10
+ * - `binary` with a comparison operator (`<`, `>`, `<=`, `>=`, `==`,
11
+ * `===`, `!=`, `!==`)
12
+ * - `unary` with logical `!`
13
+ * - `literal` with `literalType: 'boolean'`
14
+ * - `logical` (`&&` / `||` / `??`) when both sides are boolean-result
15
+ * - `conditional` (`?:`) when both branches are boolean-result
16
+ */
17
+
18
+ import type { ParsedExpr } from '../expression-parser.ts'
19
+
20
+ const COMPARISON_OPS = new Set([
21
+ '<',
22
+ '>',
23
+ '<=',
24
+ '>=',
25
+ '==',
26
+ '===',
27
+ '!=',
28
+ '!==',
29
+ ])
30
+
31
+ /** Whether `node` structurally evaluates to a JS boolean. */
32
+ export function isBooleanResultParsed(node: ParsedExpr): boolean {
33
+ switch (node.kind) {
34
+ case 'literal':
35
+ return node.literalType === 'boolean'
36
+ case 'binary':
37
+ return COMPARISON_OPS.has(node.op)
38
+ case 'unary':
39
+ return node.op === '!'
40
+ case 'logical':
41
+ // `x > 0 && y < 10` is boolean; `x() || 'fallback'` is not.
42
+ // Only both-sides-boolean qualifies.
43
+ return (
44
+ isBooleanResultParsed(node.left) && isBooleanResultParsed(node.right)
45
+ )
46
+ case 'conditional':
47
+ // `cond ? bool : bool` is boolean; `cond ? 'a' : 'b'` is not.
48
+ return (
49
+ isBooleanResultParsed(node.consequent) &&
50
+ isBooleanResultParsed(node.alternate)
51
+ )
52
+ default:
53
+ return false
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Rewrites the boolean-result branches of a ternary whose OTHER branch is
59
+ * not boolean (`yes() ? false : s()`), so a taken boolean branch carries
60
+ * JS `String(boolean)` instead of Perl's `0` / `''` / `1` (#3349). The whole
61
+ * value isn't boolean-shaped, so `bool_str` can't wrap it; instead a literal
62
+ * `true` / `false` branch becomes the string literal `'true'` / `'false'`,
63
+ * and any other boolean-result branch `b` becomes `b ? 'true' : 'false'`.
64
+ * The existing ternary lowering then renders the rewritten tree unchanged.
65
+ * Nested ternary branches are rewritten recursively; anything that is not
66
+ * a mixed ternary is returned as is.
67
+ */
68
+ export function stringifyBooleanTernaryBranches(node: ParsedExpr): ParsedExpr {
69
+ if (node.kind !== 'conditional' || isBooleanResultParsed(node)) return node
70
+ return {
71
+ ...node,
72
+ consequent: stringifyBooleanBranch(node.consequent),
73
+ alternate: stringifyBooleanBranch(node.alternate),
74
+ }
75
+ }
76
+
77
+ function stringifyBooleanBranch(branch: ParsedExpr): ParsedExpr {
78
+ if (!isBooleanResultParsed(branch)) return stringifyBooleanTernaryBranches(branch)
79
+ if (branch.kind === 'literal') {
80
+ return { kind: 'literal', value: String(branch.value), literalType: 'string' }
81
+ }
82
+ return {
83
+ kind: 'conditional',
84
+ test: branch,
85
+ consequent: { kind: 'literal', value: 'true', literalType: 'string' },
86
+ alternate: { kind: 'literal', value: 'false', literalType: 'string' },
87
+ }
88
+ }
89
+
package/src/errors.ts CHANGED
@@ -165,6 +165,14 @@ export const ErrorCodes = {
165
165
  // `/* @client */` before the ref expression. See
166
166
  // `packages/adapter-tests/limitations/ref-effect-attr-state-ssr.ts`.
167
167
  REF_ATTR_ABSENT_AT_SSR: 'BF063',
168
+ // A `ref` callback portals an element out of a `.map()` row
169
+ // (`createPortal(el, document.body, { ownerScope })`), but the row cannot
170
+ // be paired with the portaled element at hydration: the loop is nested or
171
+ // unkeyed, or the element is forwarded as a child component's children.
172
+ // SSR would place the element at its portal outlet with nothing linking it
173
+ // back to its row, so its delegated event handlers would stop running
174
+ // after hydration (#3318). A keyed top-level row is supported.
175
+ ROW_PORTAL_UNPAIRABLE: 'BF064',
168
176
 
169
177
  // Inline JSX-callback synthesis errors (BF080-BF089) — raised by the
170
178
  // preprocess-inline-jsx-callbacks pass (#1211) when an inline JSX-
@@ -298,6 +306,9 @@ const errorMessages: Record<ErrorCode, string> = {
298
306
  [ErrorCodes.REF_ATTR_ABSENT_AT_SSR]:
299
307
  'A ref callback writes an attribute on mount that the element\'s JSX never renders. A ref callback never runs at SSR, so the server HTML lacks the attribute and hydration adds it — the DOM visibly changes at the hydrate boundary.',
300
308
 
309
+ [ErrorCodes.ROW_PORTAL_UNPAIRABLE]:
310
+ 'A ref callback portals an element out of a .map() row that hydration cannot pair with the element (the row root itself, a nested or unkeyed loop, an element inside a reactive conditional in the row, or an element inside a child component\'s children), so its event handlers would stop running after hydration.',
311
+
301
312
  [ErrorCodes.INLINE_JSX_CALLBACK_CAPTURE]:
302
313
  "Inline JSX-returning arrow function captures a non-module identifier. Extract the callback into a top-level 'use client' component (e.g. `function MyNode(n) { return <div/> }` then `renderNode={MyNode}`) or pass captured values via component props.",
303
314
 
package/src/index.ts CHANGED
@@ -120,14 +120,17 @@ export { rewriteImportsForTemplate, rewriteDynamicImportsInSource } from './adap
120
120
  export { emitParsedExpr, groupBinaryOperand, groupObjectLiteralSegments, isStringTypedOperand, isStringConcatBinary } from './adapters/parsed-expr-emitter.ts'
121
121
  export type { ParsedExprEmitter, LoweringEmitter, HigherOrderMethod, ArrayMethod, SortMethod, LiteralType } from './adapters/parsed-expr-emitter.ts'
122
122
  export { collectLoopBoundNames } from './adapters/loop-bound-names.ts'
123
+ export { isBooleanResultParsed, stringifyBooleanTernaryBranches } from './adapters/boolean-result.ts'
123
124
  export { derivesScopeFromSlot } from './adapters/child-scope.ts'
124
125
  export { evaluateStaticLiteral, isFullyStaticLiteral, resolveStaticLoopSource } from './static-literal.ts'
125
126
  export {
127
+ arithmeticOperandIsNull,
126
128
  attrValueMayBeNullish,
127
129
  collectNullableSignalGetters,
128
130
  collectNullishAttrContext,
129
131
  isNullableSignal,
130
132
  isNullishLiteral,
133
+ NULL_COERCING_ARITHMETIC_OPS,
131
134
  nullableSignalAttrGetter,
132
135
  type NullishAttrContext,
133
136
  } from './nullable-signal-attr.ts'
@@ -1253,9 +1253,16 @@ function collectFromElement(element: IRElement, ctx: ClientJsContext, insideCond
1253
1253
  */
1254
1254
  function collectBranchReactiveAttrs(node: IRNode, ctx: ClientJsContext): ConditionalBranchReactiveAttr[] {
1255
1255
  const attrs: ConditionalBranchReactiveAttr[] = []
1256
- walkIR(node, null, {
1257
- ...stopAt<null>('conditional', 'ifStatement', 'loop'),
1258
- element: ({ node: el, descend }) => {
1256
+ // Scope: the slot ids of the components whose `children` enclose the
1257
+ // current node — a parent-owned (`^sN`) element renders inside one of
1258
+ // them, which is how the runtime tells it from another component's
1259
+ // same-numbered forwarded element (#3324).
1260
+ walkIR<readonly string[]>(node, [], {
1261
+ ...stopAt<readonly string[]>('conditional', 'ifStatement', 'loop'),
1262
+ component: ({ node: c, scope, descend }) => {
1263
+ descend(c.slotId ? [...scope, c.slotId] : scope)
1264
+ },
1265
+ element: ({ node: el, scope, descend }) => {
1259
1266
  if (!el.slotId) {
1260
1267
  descend()
1261
1268
  return
@@ -1276,6 +1283,7 @@ function collectBranchReactiveAttrs(node: IRNode, ctx: ClientJsContext): Conditi
1276
1283
  if (!attr.clientOnly && !decideWrapForAttr(expanded.expr, ctx, attr).wrap) continue
1277
1284
  attrs.push({
1278
1285
  slotId: el.slotId,
1286
+ ...(el.slotId.startsWith('^') && { receiverSlotIds: scope }),
1279
1287
  attrName: attr.name,
1280
1288
  expression: expanded.expr,
1281
1289
  ...pickAttrMetaFromIR(attr),
@@ -62,6 +62,7 @@ export function buildTopLevelCompositePlan(elem: TopLevelLoop, profileComponentN
62
62
  outerLoopParam: elem.param,
63
63
  outerLoopParamBindings: elem.paramBindings,
64
64
  outerLoopIndex: elem.index,
65
+ rowHasPortal: elem.bindings.refs.some(r => r.ssrPortalOwner),
65
66
  }),
66
67
  loopParam: elem.param,
67
68
  loopParamBindings: elem.paramBindings,
@@ -125,6 +126,7 @@ export function buildBranchCompositePlan(loop: BranchLoop, cv: string, profileCo
125
126
  outerLoopParam: loop.param,
126
127
  outerLoopParamBindings: loop.paramBindings,
127
128
  outerLoopIndex: loop.index,
129
+ rowHasPortal: loop.bindings.refs.some(r => r.ssrPortalOwner),
128
130
  }),
129
131
  loopParam: loop.param,
130
132
  loopParamBindings: loop.paramBindings,
@@ -30,6 +30,7 @@ export function buildDynamicLoopDelegationPlan(
30
30
  events: elem.bindings.events,
31
31
  profileComponentName,
32
32
  ownHandlers,
33
+ ...(hasRowPortalRef(elem) && { relayRowPortals: true }),
33
34
  itemLookup: buildKeyedOrIndexLookup({
34
35
  // Chain `.filter()` / `.toSorted()` so the index-based lookup walks
35
36
  // the same array shape mapArray reconciled into the DOM (#1434).
@@ -69,6 +70,7 @@ export function buildBranchLoopDelegationPlan(
69
70
  containerVar: `__loop_${cv}`,
70
71
  events: loop.bindings.events,
71
72
  profileComponentName,
73
+ ...(hasRowPortalRef(loop) && { relayRowPortals: true }),
72
74
  itemLookup: buildKeyedOrIndexLookup({
73
75
  // See note on `buildDynamicLoopDelegationPlan` above (#1434).
74
76
  array: buildChainedArrayExpr(loop),
@@ -98,6 +100,12 @@ export function buildStaticArrayDelegationPlan(
98
100
  profileComponentName?: string,
99
101
  ownHandlers?: Map<string, ContainerOwnHandler>,
100
102
  ): EventDelegationPlan {
103
+ // A row-portaled element is not under its row, so the positional lookup
104
+ // cannot reach the row from it; the row key it carries can (#3318).
105
+ // BF064 guarantees a portaling loop is keyed.
106
+ if (hasRowPortalRef(elem) && elem.key !== null) {
107
+ return buildDynamicLoopDelegationPlan(elem, profileComponentName, ownHandlers)
108
+ }
101
109
  return {
102
110
  kind: 'event-delegation',
103
111
  containerVar: `_${varSlotId(elem.slotId)}`,
@@ -125,6 +133,11 @@ export function buildStaticArrayDelegationPlan(
125
133
  }
126
134
  }
127
135
 
136
+ /** A row `ref` callback of the loop portals its element out of the row (#3318). */
137
+ function hasRowPortalRef(loop: TopLevelLoop | BranchLoop): boolean {
138
+ return loop.bindings.refs.some(r => r.ssrPortalOwner)
139
+ }
140
+
128
141
  /**
129
142
  * Helper used by both the top-level and branch-scoped builders. Picks
130
143
  * `keyed` vs `dynamic-index` based on whether the loop has an explicit key.
@@ -88,6 +88,11 @@ export interface BuildInnerLoopsArgs {
88
88
  outerLoopParamBindings?: readonly LoopParamBinding[]
89
89
  /** Outer loop's index param name, when present (#2861). */
90
90
  outerLoopIndex?: string | null
91
+ /**
92
+ * The outer row portals an element out of itself (#3318), so a container
93
+ * inside it is looked up through the row's registered roots (`qsaItem`).
94
+ */
95
+ rowHasPortal?: boolean
91
96
  }
92
97
 
93
98
  /**
@@ -96,7 +101,7 @@ export interface BuildInnerLoopsArgs {
96
101
  * conditional branch are skipped (they're emitted by `stringifyBranchInnerLoops`).
97
102
  */
98
103
  export function buildInnerLoopsPlan(args: BuildInnerLoopsArgs): InnerLoopsPlan {
99
- const { levels, parentElVar, outerLoopParam, outerLoopParamBindings, outerLoopIndex } = args
104
+ const { levels, parentElVar, outerLoopParam, outerLoopParamBindings, outerLoopIndex, rowHasPortal } = args
100
105
  const wrapOuter = outerLoopParam
101
106
  ? (expr: string) => wrapLoopParamAsAccessor(expr, outerLoopParam, outerLoopParamBindings, outerLoopIndex)
102
107
  : (expr: string) => expr
@@ -119,7 +124,7 @@ export function buildInnerLoopsPlan(args: BuildInnerLoopsArgs): InnerLoopsPlan {
119
124
 
120
125
  const uidSuffix = `${inner.depth}_${i}`
121
126
  const containerExpr = inner.containerSlotId
122
- ? `qsa(${parentElVar}, '[bf="${inner.containerSlotId}"]')`
127
+ ? `${rowHasPortal ? 'qsaItem' : 'qsa'}(${parentElVar}, '[bf="${inner.containerSlotId}"]')`
123
128
  : parentElVar
124
129
 
125
130
  // #2865: every nested loop gets the full reactive `mapArray` emission,
@@ -46,6 +46,13 @@ export interface EventDelegationPlan {
46
46
  * (the common case: no collision) keeps the emitted listener unchanged.
47
47
  */
48
48
  ownHandlers?: Map<string, ContainerOwnHandler>
49
+ /**
50
+ * A row of this loop portals an element out of the container (#3318).
51
+ * The stringifier then also relays each listener to the adopted elements
52
+ * (`relayRowPortalEvents`) and accepts slot matches inside them
53
+ * (`isRowPortalOf`). `undefined` keeps the emitted listener unchanged.
54
+ */
55
+ relayRowPortals?: boolean
49
56
  }
50
57
 
51
58
  /**
@@ -117,6 +117,8 @@ export interface ArmTextEffect {
117
117
  */
118
118
  export interface ArmReactiveAttr extends AttrMeta {
119
119
  slotId: string
120
+ /** See `ConditionalBranchReactiveAttr.receiverSlotIds` (#3324). */
121
+ receiverSlotIds?: readonly string[]
120
122
  attrName: string
121
123
  expression: string
122
124
  }
@@ -112,6 +112,8 @@ export interface LoopChildRefBinding {
112
112
  * `reactiveAttrs` are already handled on the static path.
113
113
  */
114
114
  callback: string
115
+ /** The callback portals the element out of the row (#3318); see `LoopChildRef.ssrPortalOwner`. */
116
+ ssrPortalOwner?: boolean
115
117
  }
116
118
 
117
119
  /**
@@ -154,6 +154,7 @@ export function buildChildRefBindings(
154
154
  return refs.map(r => ({
155
155
  childSlotId: r.childSlotId,
156
156
  callback: wrapLoopParamAsAccessor(r.callback, loopParam, loopParamBindings, loopIndex),
157
+ ...(r.ssrPortalOwner && { ssrPortalOwner: true }),
157
158
  }))
158
159
  }
159
160
 
@@ -173,6 +174,7 @@ export function buildStaticChildRefBindings(
173
174
  return refs.map(r => ({
174
175
  childSlotId: r.childSlotId,
175
176
  callback: r.callback,
177
+ ...(r.ssrPortalOwner && { ssrPortalOwner: true }),
176
178
  }))
177
179
  }
178
180
 
@@ -14,7 +14,7 @@ import { stringifyCompositeLoop } from './composite-loop.ts'
14
14
  import { stringifyEventDelegation } from './event-delegation.ts'
15
15
  import { stringifyReactiveEffects } from './reactive-effects.ts'
16
16
  import { emitTemplateCloneInline, emitLoopItemElementSetup } from './template-parse.ts'
17
- import { emitLoopChildRefs } from './loop.ts'
17
+ import { emitLoopChildRefs, emitRowPortalClaim, rowPortalSlotIds } from './loop.ts'
18
18
  import { stringifyLazyRowLoop } from './lazy-row.ts'
19
19
  import type {
20
20
  BranchLoopPlan,
@@ -137,6 +137,9 @@ function emitPlain(lines: string[], plan: BranchPlainLoopPlan): void {
137
137
  indent: ' ',
138
138
  singleRootLayout: 'inline',
139
139
  })
140
+ // See `stringifyPlainLoop` (#3318).
141
+ emitRowPortalClaim(lines, childRefs, { indent: ' ', containerVar })
142
+ const itemLookup = bodyIsMultiRoot || rowPortalSlotIds(childRefs).length > 0
140
143
  if (reactiveEffects !== null || preambleRegions.length > 0) {
141
144
  // Row-granularity effects (§3(c)): mirrors `stringifyPlainLoop`'s
142
145
  // top-level call — attrs, outer texts, and preamble regions merge
@@ -144,12 +147,12 @@ function emitPlain(lines: string[], plan: BranchPlainLoopPlan): void {
144
147
  stringifyReactiveEffects(lines, reactiveEffects, {
145
148
  indent: ' ',
146
149
  elVar: '__el',
147
- bodyIsMultiRoot,
150
+ bodyIsMultiRoot: itemLookup,
148
151
  preambleRegions,
149
152
  mapPreambleWrapped,
150
153
  })
151
154
  }
152
- emitLoopChildRefs(lines, childRefs, { indent: ' ', elVar: '__el', bodyIsMultiRoot })
155
+ emitLoopChildRefs(lines, childRefs, { indent: ' ', elVar: '__el', bodyIsMultiRoot: itemLookup, containerVar })
153
156
  lines.push(` return __el`)
154
157
  lines.push(` }, '${markerId}'${loopBfId})`)
155
158
  }
@@ -34,7 +34,7 @@ import { emitComponentAndEventSetup } from '../shared.ts'
34
34
  import { stringifyInnerLoops } from './inner-loop.ts'
35
35
  import { stringifyReactiveEffects } from './reactive-effects.ts'
36
36
  import { emitLoopItemElementSetup } from './template-parse.ts'
37
- import { emitLoopChildRefs } from './loop.ts'
37
+ import { emitLoopChildRefs, emitRowPortalClaim, rowPortalSlotIds } from './loop.ts'
38
38
  import type { CompositeLoopPlan } from '../plan/types.ts'
39
39
 
40
40
  export function stringifyCompositeLoop(lines: string[], plan: CompositeLoopPlan): void {
@@ -125,16 +125,19 @@ export function stringifyCompositeLoop(lines: string[], plan: CompositeLoopPlan)
125
125
  // variant whose tail needs the row already connected.
126
126
  mountRow: true,
127
127
  })
128
- emitComponentAndEventSetup(lines, bodyIndent, '__el', compsArr, eventsArr, loopParam, loopParamBindings, bodyIsMultiRoot, loopIndex)
128
+ // See `stringifyPlainLoop` (#3318).
129
+ emitRowPortalClaim(lines, childRefs, { indent: bodyIndent, containerVar })
130
+ const itemLookup = bodyIsMultiRoot || rowPortalSlotIds(childRefs).length > 0
131
+ emitComponentAndEventSetup(lines, bodyIndent, '__el', compsArr, eventsArr, loopParam, loopParamBindings, itemLookup, loopIndex)
129
132
  if (innerLoops.length > 0) {
130
133
  stringifyInnerLoops(lines, innerLoops, bodyIndent, pc)
131
134
  }
132
135
 
133
136
  if (reactiveEffects) {
134
- stringifyReactiveEffects(lines, reactiveEffects, { indent: bodyIndent, elVar: '__el', bodyIsMultiRoot })
137
+ stringifyReactiveEffects(lines, reactiveEffects, { indent: bodyIndent, elVar: '__el', bodyIsMultiRoot: itemLookup })
135
138
  }
136
139
 
137
- emitLoopChildRefs(lines, childRefs, { indent: bodyIndent, elVar: '__el', bodyIsMultiRoot })
140
+ emitLoopChildRefs(lines, childRefs, { indent: bodyIndent, elVar: '__el', bodyIsMultiRoot: itemLookup, containerVar })
138
141
 
139
142
  lines.push(`${bodyIndent}return __el`)
140
143
  const loopBfId = profileLoopId ? `, ${JSON.stringify(profileLoopId)}` : ''