@barefootjs/jsx 0.39.2 → 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 (98) 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/line-statement-text.d.ts +17 -0
  4. package/dist/adapters/line-statement-text.d.ts.map +1 -0
  5. package/dist/analyzer.d.ts +1 -0
  6. package/dist/analyzer.d.ts.map +1 -1
  7. package/dist/augment-inherited-props.d.ts +20 -0
  8. package/dist/augment-inherited-props.d.ts.map +1 -1
  9. package/dist/errors.d.ts +1 -0
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/html-types.d.ts +15 -0
  12. package/dist/html-types.d.ts.map +1 -1
  13. package/dist/index.d.ts +6 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +595 -140
  16. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/control-flow/plan/build-composite-loop.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +5 -0
  20. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +7 -0
  22. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  24. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +2 -0
  26. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/composite-loop.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts +14 -0
  31. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/imports.d.ts +2 -2
  34. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts +3 -1
  36. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/safe-html.d.ts +6 -0
  39. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/types.d.ts +12 -0
  41. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/nullable-signal-attr.d.ts +94 -0
  44. package/dist/nullable-signal-attr.d.ts.map +1 -0
  45. package/dist/profiler.d.ts +9 -1
  46. package/dist/profiler.d.ts.map +1 -1
  47. package/dist/scope/root-prop-alias.d.ts +43 -0
  48. package/dist/scope/root-prop-alias.d.ts.map +1 -0
  49. package/package.json +2 -2
  50. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +3 -3
  51. package/src/__tests__/attribute-fallback-wrap.test.ts +24 -0
  52. package/src/__tests__/boolean-result.test.ts +27 -0
  53. package/src/__tests__/compiler-stress-1244.test.ts +10 -13
  54. package/src/__tests__/conditional-fallback-wrap.test.ts +20 -0
  55. package/src/__tests__/csr-template-loop-shadow.test.ts +83 -0
  56. package/src/__tests__/html-event-handler-names.test.ts +107 -0
  57. package/src/__tests__/line-statement-text.test.ts +25 -0
  58. package/src/__tests__/lookup-literal-const.test.ts +46 -0
  59. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +66 -19
  60. package/src/__tests__/nullable-signal-attr.test.ts +124 -0
  61. package/src/__tests__/profile-binding-ids.test.ts +102 -0
  62. package/src/__tests__/profile-turn-markers.test.ts +22 -0
  63. package/src/__tests__/profiler.test.ts +10 -9
  64. package/src/__tests__/root-prop-alias.test.ts +62 -0
  65. package/src/__tests__/ssr-portal-ref-callback.test.ts +88 -13
  66. package/src/adapters/boolean-result.ts +89 -0
  67. package/src/adapters/line-statement-text.ts +24 -0
  68. package/src/analyzer.ts +50 -26
  69. package/src/augment-inherited-props.ts +49 -0
  70. package/src/errors.ts +11 -0
  71. package/src/html-types.ts +15 -0
  72. package/src/index.ts +16 -2
  73. package/src/ir-to-client-js/collect-elements.ts +18 -4
  74. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +2 -2
  75. package/src/ir-to-client-js/control-flow/plan/build-composite-loop.ts +2 -0
  76. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +13 -0
  77. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +7 -2
  78. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +7 -0
  79. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  80. package/src/ir-to-client-js/control-flow/plan/loop.ts +2 -0
  81. package/src/ir-to-client-js/control-flow/shared.ts +2 -0
  82. package/src/ir-to-client-js/control-flow/stringify/branch-loop.ts +6 -3
  83. package/src/ir-to-client-js/control-flow/stringify/composite-loop.ts +7 -4
  84. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +21 -6
  85. package/src/ir-to-client-js/control-flow/stringify/insert.ts +6 -1
  86. package/src/ir-to-client-js/control-flow/stringify/loop.ts +55 -8
  87. package/src/ir-to-client-js/html-template.ts +59 -8
  88. package/src/ir-to-client-js/imports.ts +3 -1
  89. package/src/ir-to-client-js/phases/rest-attr-applications.ts +8 -2
  90. package/src/ir-to-client-js/reactivity.ts +1 -0
  91. package/src/ir-to-client-js/safe-html.ts +10 -0
  92. package/src/ir-to-client-js/stringify/declaration-emit.ts +5 -5
  93. package/src/ir-to-client-js/types.ts +12 -0
  94. package/src/ir-to-client-js/utils.ts +88 -117
  95. package/src/jsx-to-ir.ts +145 -32
  96. package/src/nullable-signal-attr.ts +202 -0
  97. package/src/profiler.ts +79 -10
  98. package/src/scope/root-prop-alias.ts +81 -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
 
@@ -88,7 +88,7 @@ function emitSignal(lines: string[], plan: SignalEmitPlan): void {
88
88
  lines.push(` const [${bindings}] = ${plan.initializerOverride}`)
89
89
  return
90
90
  }
91
- const id = bfIdArg(plan.bfId)
91
+ const args = `${plan.initialValueExpr}${bfIdArg(plan.bfId)}`
92
92
  if (plan.branchCondition) {
93
93
  // #1414 cell #8: signal declared inside an early-return `if`-block.
94
94
  // Hoist as `let` so closures and event handlers hoisted to outer
@@ -99,12 +99,12 @@ function emitSignal(lines: string[], plan: SignalEmitPlan): void {
99
99
  if (plan.setter) {
100
100
  lines.push(plan.getterElided ? ` let ${plan.setter}` : ` let ${plan.getter}, ${plan.setter}`)
101
101
  lines.push(` if (${plan.branchCondition}) {`)
102
- lines.push(` ;[${getterSlot}, ${plan.setter}] = createSignal(${plan.initialValueExpr}${id})`)
102
+ lines.push(` ;[${getterSlot}, ${plan.setter}] = createSignal(${args})`)
103
103
  lines.push(` }`)
104
104
  } else {
105
105
  lines.push(` let ${plan.getter}`)
106
106
  lines.push(` if (${plan.branchCondition}) {`)
107
- lines.push(` ;[${plan.getter}] = createSignal(${plan.initialValueExpr}${id})`)
107
+ lines.push(` ;[${plan.getter}] = createSignal(${args})`)
108
108
  lines.push(` }`)
109
109
  }
110
110
  // Controlled effects don't apply to branch-conditioned signals — a
@@ -113,9 +113,9 @@ function emitSignal(lines: string[], plan: SignalEmitPlan): void {
113
113
  return
114
114
  }
115
115
  if (plan.setter) {
116
- lines.push(` const [${getterSlot}, ${plan.setter}] = createSignal(${plan.initialValueExpr}${id})`)
116
+ lines.push(` const [${getterSlot}, ${plan.setter}] = createSignal(${args})`)
117
117
  } else {
118
- lines.push(` const [${plan.getter}] = createSignal(${plan.initialValueExpr}${id})`)
118
+ lines.push(` const [${plan.getter}] = createSignal(${args})`)
119
119
  }
120
120
  if (plan.controlledEffect) {
121
121
  emitControlledEffect(lines, plan.controlledEffect)
@@ -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. */
@@ -9,12 +9,10 @@ import type { TopLevelLoop, BranchLoop, LoopOffset } from './types.ts'
9
9
  import { isNonReferenceIdentifierPosition } from '../analyzer.ts'
10
10
  import { buildLoopChainExpr } from '../loop-chain.ts'
11
11
  import { templatePartsToJsExpr } from '../template-parts.ts'
12
- import { escapeIdentifierForRegex, ID_BOUNDARY_BEFORE, ID_BOUNDARY_AFTER } from '../identifier-pattern.ts'
13
12
  import {
14
13
  iterateJsTokens,
15
14
  isIdentifierLikeToken,
16
15
  isTriviaKind,
17
- replaceInExprContexts,
18
16
  } from '../scanner/js-scanner.ts'
19
17
  import {
20
18
  BF_KEY as DATA_KEY,
@@ -756,8 +754,9 @@ export function wrapIndexParamAsAccessor(expr: string, indexParam: string): stri
756
754
  * merely SPELLS `name` without referencing it — an object-literal key
757
755
  * (`{ name: 1 }`), a shorthand property (`{ name }`, expanded to
758
756
  * `{ name: name() }` in one edit — the same transformation #1244 gave the
759
- * destructured-binding path via `expandShorthandBindings`), and a
760
- * member/property name (`obj.name`, `obj?.name`).
757
+ * destructured-binding path), and a member/property name (`obj.name`,
758
+ * `obj?.name`). The walk itself is `rewriteIdentifierReferences`, shared
759
+ * with that destructured-binding path (#3260).
761
760
  *
762
761
  * The previous implementation was a `\bname\b`-style regex
763
762
  * (`ID_BOUNDARY_BEFORE`/`AFTER` only know about identifier-character
@@ -765,9 +764,8 @@ export function wrapIndexParamAsAccessor(expr: string, indexParam: string): stri
765
764
  * a key or shorthand rewrite produces invalid JS (`{ name(): 1 }`,
766
765
  * `{ name() }`) that fails at parse time; a member-name rewrite produces
767
766
  * valid-but-wrong JS (`obj.name()`) that throws `TypeError: obj.name is not
768
- * a function` at row-creation time (#3239). Parsing the real AST — the same
769
- * technique `expandShorthandBindings` already uses below — makes each of
770
- * those positions a type of AST node this function can name and skip,
767
+ * a function` at row-creation time (#3239). Parsing the real AST makes each
768
+ * of those positions a type of AST node this function can name and skip,
771
769
  * instead of a regex guessing from surrounding characters.
772
770
  *
773
771
  * A nested declaration that re-binds `name` (a parameter, a `const`/`let`,
@@ -800,25 +798,67 @@ export function wrapIndexParamAsAccessor(expr: string, indexParam: string): stri
800
798
  * references reachable from within or after it).
801
799
  */
802
800
  function rewriteIdentifierAsAccessor(expr: string, name: string): string {
803
- // Fast path: `name` doesn't occur in the text at all → nothing to rewrite.
804
- // A cheap substring check only ever causes an unnecessary parse below
805
- // (e.g. `name` occurs only as part of a longer identifier), never a wrong
801
+ return rewriteIdentifierReferences(expr, new Map([[name, `${name}()`]]), { skipCallee: true })
802
+ }
803
+
804
+ /**
805
+ * The AST walk shared by `rewriteIdentifierAsAccessor` (one name → `name()`)
806
+ * and `rewriteLoopBindingRefs` (each destructured binding → its
807
+ * `renderLoopBindingAccess` form): replace every genuine value reference to
808
+ * a name in `replacements` with its replacement text, in one pass. See
809
+ * `rewriteIdentifierAsAccessor`'s docstring for which positions count as a
810
+ * reference and why; both callers answer that question here, so they cannot
811
+ * drift apart (#3260).
812
+ *
813
+ * `skipCallee` leaves `name()` / `new name()` and a `function name()`
814
+ * declaration's own name alone. It is the accessor rewrite's no-double-wrap
815
+ * rule (#2592): there `name()` already IS the accessor call, and the old
816
+ * regex's "followed by (" lookahead skipped all three. A destructured
817
+ * binding has no such shape — `handler()` with `({ handler })` calls the
818
+ * item's field, so it must become `__bfItem().handler()` — and its caller
819
+ * passes `false`, which also leaves a shadowing function declaration to
820
+ * fail loudly, as it did under the old destructured regex.
821
+ *
822
+ * One pass over the AST, so a replacement is never re-scanned: a binding
823
+ * `a` with path `.a` cannot cascade into `__bfItem().__bfItem().a`.
824
+ */
825
+ function rewriteIdentifierReferences(
826
+ expr: string,
827
+ replacements: ReadonlyMap<string, string>,
828
+ opts: { skipCallee: boolean },
829
+ ): string {
830
+ // Fast path: no name occurs in the text at all → nothing to rewrite. A
831
+ // cheap substring check only ever causes an unnecessary parse below
832
+ // (e.g. a name occurs only as part of a longer identifier), never a wrong
806
833
  // answer, since the AST walk re-checks the exact identifier text.
807
- if (!expr.includes(name)) return expr
834
+ let any = false
835
+ for (const name of replacements.keys()) {
836
+ if (expr.includes(name)) { any = true; break }
837
+ }
838
+ if (!any) return expr
808
839
 
809
840
  const wrapped = `(${expr})`
810
841
  const sf = ts.createSourceFile('__bf_expr.ts', wrapped, ts.ScriptTarget.Latest, /* setParentNodes */ true)
811
842
  const edits: Array<{ start: number; end: number; replacement: string }> = []
812
843
 
813
- const visit = (node: ts.Node): void => {
844
+ const visit = (node: ts.Node, active: ReadonlyMap<string, string>): void => {
814
845
  // A named function expression's own name is scoped to exactly its own
815
- // body, so nothing reachable inside it can refer to the outer `name` —
816
- // skip the whole subtree instead of only its declaration-name
817
- // identifier (see this function's docstring for why a `function`/
818
- // `class` DECLARATION can't get the same treatment this cheaply).
819
- if (ts.isFunctionExpression(node) && node.name?.text === name) return
846
+ // body, so nothing reachable inside it can refer to the outer binding of
847
+ // that name — drop it for the whole subtree instead of only its
848
+ // declaration-name identifier (see `rewriteIdentifierAsAccessor`'s
849
+ // docstring for why a `function`/`class` DECLARATION can't get the same
850
+ // treatment this cheaply). Other names stay active inside.
851
+ if (ts.isFunctionExpression(node) && node.name && active.has(node.name.text)) {
852
+ const inner = new Map(active)
853
+ inner.delete(node.name.text)
854
+ if (inner.size === 0) return
855
+ ts.forEachChild(node, child => visit(child, inner))
856
+ return
857
+ }
820
858
 
821
- if (ts.isIdentifier(node) && node.text === name) {
859
+ if (ts.isIdentifier(node)) {
860
+ const replacement = active.get(node.text)
861
+ if (replacement === undefined) return
822
862
  const p = node.parent
823
863
  // Pure-key / non-reference positions — never rewrite. Shared with
824
864
  // `analyzer.ts`'s factory-rename `classify()`, which answers the same
@@ -834,26 +874,33 @@ function rewriteIdentifierAsAccessor(expr: string, name: string): string {
834
874
  // old regex did NOT protect it either — wrapping it is a pre-existing
835
875
  // syntax break, not a regression, so it's left to the shadowing-decl
836
876
  // path below like any other declaration name.
837
- if (ts.isFunctionDeclaration(p) && p.name === node) return
838
- if (ts.isCallExpression(p) && p.expression === node) return // already `name()` — no double-wrap (#2592)
839
- if (ts.isNewExpression(p) && p.expression === node) return // `new name()` — same "followed by (" shape as a call
877
+ //
878
+ // Accessor mode only: the old destructured-binding regex had no such
879
+ // exemption, so there a shadowing `function color() {}` broke the
880
+ // declaration loudly. Skipping its name here would keep the local
881
+ // function while rewriting its calls to `__bfItem().color()` — valid
882
+ // JS that calls the wrong value (#3260 review).
883
+ if (opts.skipCallee) {
884
+ if (ts.isFunctionDeclaration(p) && p.name === node) return
885
+ if (ts.isCallExpression(p) && p.expression === node) return // already `name()` — no double-wrap (#2592)
886
+ if (ts.isNewExpression(p) && p.expression === node) return // `new name()` — same "followed by (" shape as a call
887
+ }
840
888
 
841
- // Shorthand property (`{ name }`) expands key + wraps value in one
842
- // edit — the plain-param analogue of `expandShorthandBindings` below.
843
- // Every other reachable position here is a genuine value reference —
844
- // OR a shadowing declaration name (nested parameter/`const`/`let`/
845
- // destructured local): both get wrapped, per this function's
846
- // docstring on why a shadow is left to fail loudly rather than
847
- // silently misrewritten.
889
+ // Shorthand property (`{ name }`) expands key + rewrites value in one
890
+ // edit (#1244). Every other reachable position here is a genuine
891
+ // value reference — OR a shadowing declaration name (nested
892
+ // parameter/`const`/`let`/destructured local): both get rewritten,
893
+ // per `rewriteIdentifierAsAccessor`'s docstring on why a shadow is
894
+ // left to fail loudly rather than silently misrewritten.
848
895
  const isShorthand = ts.isShorthandPropertyAssignment(p) && p.name === node
849
896
  const start = node.getStart(sf) - 1
850
897
  const end = node.getEnd() - 1
851
- edits.push({ start, end, replacement: isShorthand ? `${name}: ${name}()` : `${name}()` })
898
+ edits.push({ start, end, replacement: isShorthand ? `${node.text}: ${replacement}` : replacement })
852
899
  return
853
900
  }
854
- ts.forEachChild(node, visit)
901
+ ts.forEachChild(node, child => visit(child, active))
855
902
  }
856
- visit(sf)
903
+ visit(sf, replacements)
857
904
 
858
905
  if (edits.length === 0) return expr
859
906
  // Apply right-to-left so earlier offsets stay valid as later ones grow.
@@ -867,99 +914,23 @@ function rewriteIdentifierAsAccessor(expr: string, name: string): string {
867
914
 
868
915
  /**
869
916
  * Rewrite each reference to a destructured loop-param binding in
870
- * `expr` to the corresponding `${accessor}${path}` form.
917
+ * `expr` to the corresponding `${accessor}${path}` form
918
+ * (`renderLoopBindingAccess`).
871
919
  *
872
- * Single alternation regex so rewriting is one-pass — iterating per
873
- * binding risks re-matching the replacement text (a binding named
874
- * `a` with path `.a` would cascade into `__bfItem().a` then back
875
- * into `__bfItem().__bfItem().a`).
876
- *
877
- * `expandShorthandBindings` runs first so object-literal shorthand
878
- * references (`{ name }`) are lifted to a string-key form before
879
- * the identifier regex hits them — otherwise the rewrite would land
880
- * `${accessor}` in a position JS reserves for bare identifiers
881
- * (`{ __bfItem().name }` ⇒ SyntaxError). (#1244)
920
+ * Shares `rewriteIdentifierReferences`'s AST walk with the plain-param
921
+ * accessor rewrite, so an object-literal key (`{ color: 1 }`) or a member
922
+ * name (`obj.color`) that merely spells a binding name stays as written
923
+ * (#3260), and a shorthand property (`{ color }`) becomes
924
+ * `{ color: __bfItem().color }` (#1244).
882
925
  */
883
926
  function rewriteLoopBindingRefs(
884
927
  expr: string,
885
928
  bindings: readonly LoopParamBinding[],
886
929
  accessor: string,
887
930
  ): string {
888
- const byName = new Map<string, LoopParamBinding>()
889
- for (const b of bindings) byName.set(b.name, b)
890
- const preprocessed = expandShorthandBindings(expr, new Set(byName.keys()))
891
- const alt = bindings.map(b => escapeIdentifierForRegex(b.name)).join('|')
892
- const re = new RegExp(`${ID_BOUNDARY_BEFORE}(${alt})${ID_BOUNDARY_AFTER}`, 'gu')
893
- return replaceInExprContexts(preprocessed, re, (_m: string, name: string) =>
894
- renderLoopBindingAccess(byName.get(name)!, accessor),
895
- )
896
- }
897
-
898
- /**
899
- * Expand object-literal shorthand properties whose name matches a
900
- * destructured loop-param binding into the equivalent
901
- * `"name": name` form (string-literal key + identifier value).
902
- *
903
- * Why: JS only accepts a bare identifier as a shorthand property
904
- * name, so the downstream `${accessor}` rewrite of `{ color }` would
905
- * produce `{ __bfItem().color }` — a SyntaxError that takes down the
906
- * whole compiled component at module load time, before any runtime
907
- * code runs. (#1244)
908
- *
909
- * Why string-literal key (not `name: name`): the subsequent
910
- * identifier-replacement regex (`replaceInExprContexts`) skips string
911
- * literal contents, so the key stays as the literal `"color"` while
912
- * the value-position `color` gets rewritten to `__bfItem().color`.
913
- * The alternative `name: name` would have the regex match BOTH
914
- * occurrences and produce `{ __bfItem().color: __bfItem().color }`
915
- * — same SyntaxError, just one indirection deeper.
916
- *
917
- * AST-based detection (TS `ShorthandPropertyAssignment`) is
918
- * intentionally chosen over character-by-character lookbehind on the
919
- * raw expression text — the codebase's recurring "hand-rolled JS
920
- * source scanners" pattern (#1244 §D) explicitly flags that approach
921
- * as drift-prone (computed keys, comments, nested template literals
922
- * all need separate handling). The TS scanner already knows what a
923
- * shorthand prop is.
924
- *
925
- * The `(${expr})` wrap forces TS to parse a bare object literal as
926
- * an expression — otherwise `{ color }` would be a block statement
927
- * containing an expression statement, with no `ShorthandPropertyAssignment`
928
- * node to find.
929
- */
930
- function expandShorthandBindings(expr: string, bindingNames: ReadonlySet<string>): string {
931
- // Fast path: no `{` means no object literal means no shorthand to
932
- // expand. Skip the parser cost on the common case.
933
- if (!expr.includes('{')) return expr
934
- const wrapped = `(${expr})`
935
- const sf = ts.createSourceFile('__bf_expr.ts', wrapped, ts.ScriptTarget.Latest, /* setParentNodes */ true)
936
- const edits: Array<{ start: number; end: number; replacement: string }> = []
937
- const visit = (node: ts.Node): void => {
938
- if (
939
- ts.isShorthandPropertyAssignment(node)
940
- && ts.isIdentifier(node.name)
941
- && bindingNames.has(node.name.text)
942
- ) {
943
- // `node` spans just the bare identifier on the shorthand entry.
944
- // Position offsets are in `wrapped`; subtract the leading `(`
945
- // to map back to `expr`.
946
- const start = node.getStart(sf) - 1
947
- const end = node.getEnd() - 1
948
- const name = node.name.text
949
- edits.push({ start, end, replacement: `${JSON.stringify(name)}: ${name}` })
950
- }
951
- ts.forEachChild(node, visit)
952
- }
953
- visit(sf)
954
- if (edits.length === 0) return expr
955
- // Apply right-to-left so earlier offsets stay valid as later ones
956
- // grow.
957
- edits.sort((a, b) => b.start - a.start)
958
- let out = expr
959
- for (const e of edits) {
960
- out = out.slice(0, e.start) + e.replacement + out.slice(e.end)
961
- }
962
- return out
931
+ const replacements = new Map<string, string>()
932
+ for (const b of bindings) replacements.set(b.name, renderLoopBindingAccess(b, accessor))
933
+ return rewriteIdentifierReferences(expr, replacements, { skipCallee: false })
963
934
  }
964
935
 
965
936
  /**