@barefootjs/jsx 0.35.5 → 0.35.6

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 (102) hide show
  1. package/dist/analyzer-context.d.ts +5 -4
  2. package/dist/analyzer-context.d.ts.map +1 -1
  3. package/dist/analyzer.d.ts.map +1 -1
  4. package/dist/errors.d.ts +0 -1
  5. package/dist/errors.d.ts.map +1 -1
  6. package/dist/index.js +6711 -6471
  7. package/dist/ir-to-client-js/compute-prop-usage.d.ts +6 -0
  8. package/dist/ir-to-client-js/compute-prop-usage.d.ts.map +1 -1
  9. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts +3 -2
  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-loop.d.ts +12 -2
  12. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  13. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +40 -0
  14. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -0
  15. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +13 -0
  16. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts +45 -0
  18. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts.map +1 -0
  19. package/dist/ir-to-client-js/control-flow/plan/types.d.ts +2 -0
  20. package/dist/ir-to-client-js/control-flow/plan/types.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts +12 -0
  22. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow.d.ts +2 -1
  24. package/dist/ir-to-client-js/control-flow.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/emit-reactive.d.ts +7 -3
  26. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/index.d.ts +1 -0
  29. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/phases/event-handlers.d.ts +9 -1
  31. package/dist/ir-to-client-js/phases/event-handlers.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts +5 -0
  33. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/phases/props-extraction.d.ts +15 -13
  35. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/phases.d.ts +12 -1
  37. package/dist/ir-to-client-js/phases.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +50 -0
  40. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +29 -0
  42. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -0
  43. package/dist/ir-to-client-js/utils.d.ts +9 -0
  44. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  45. package/dist/jsx-to-ir.d.ts.map +1 -1
  46. package/dist/prop-rewrite.d.ts.map +1 -1
  47. package/dist/props-binding.d.ts +112 -1
  48. package/dist/props-binding.d.ts.map +1 -1
  49. package/dist/ssr-defaults.d.ts.map +1 -1
  50. package/dist/static-literal.d.ts +20 -8
  51. package/dist/static-literal.d.ts.map +1 -1
  52. package/dist/types.d.ts +7 -0
  53. package/dist/types.d.ts.map +1 -1
  54. package/package.json +2 -2
  55. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +31 -35
  56. package/src/__tests__/aliased-destructured-prop-csr.test.ts +19 -7
  57. package/src/__tests__/body-destructured-prop-default-propsparams.test.ts +153 -0
  58. package/src/__tests__/body-destructured-props-live.test.ts +245 -0
  59. package/src/__tests__/client-js-generation.test.ts +11 -4
  60. package/src/__tests__/client-only-date-lowering.test.ts +5 -2
  61. package/src/__tests__/destructured-from-props-localconst-value.test.ts +17 -6
  62. package/src/__tests__/destructured-props-live.test.ts +167 -0
  63. package/src/__tests__/doc-examples.test.ts +2 -4
  64. package/src/__tests__/event-delegation-container-collision-2930.test.ts +197 -0
  65. package/src/__tests__/format-error.test.ts +5 -3
  66. package/src/__tests__/live-only-props.test.ts +160 -0
  67. package/src/__tests__/prop-references.test.ts +26 -17
  68. package/src/__tests__/props-destructuring.test.ts +6 -275
  69. package/src/__tests__/prune-unused-prop-extractions.test.ts +11 -5
  70. package/src/__tests__/signal-getter-not-called.test.ts +5 -0
  71. package/src/__tests__/ssr-defaults.test.ts +83 -0
  72. package/src/__tests__/staged-ir/02-shadow-guards.test.ts +12 -5
  73. package/src/__tests__/static-literal.test.ts +39 -4
  74. package/src/analyzer-context.ts +8 -7
  75. package/src/analyzer.ts +76 -84
  76. package/src/errors.ts +7 -8
  77. package/src/ir-to-client-js/compute-prop-usage.ts +19 -0
  78. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +5 -0
  79. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +27 -11
  80. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +55 -0
  81. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +13 -0
  82. package/src/ir-to-client-js/control-flow/plan/loop-delegation-index.ts +79 -0
  83. package/src/ir-to-client-js/control-flow/plan/types.ts +2 -0
  84. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +50 -10
  85. package/src/ir-to-client-js/control-flow.ts +68 -31
  86. package/src/ir-to-client-js/emit-reactive.ts +12 -8
  87. package/src/ir-to-client-js/generate-init.ts +6 -0
  88. package/src/ir-to-client-js/index.ts +45 -3
  89. package/src/ir-to-client-js/phases/event-handlers.ts +10 -0
  90. package/src/ir-to-client-js/phases/props-event-handlers.ts +6 -0
  91. package/src/ir-to-client-js/phases/props-extraction.ts +29 -48
  92. package/src/ir-to-client-js/phases.ts +17 -3
  93. package/src/ir-to-client-js/plan/build-declaration-emit.ts +6 -5
  94. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +31 -10
  95. package/src/ir-to-client-js/rewrite-destructured-props.ts +210 -0
  96. package/src/ir-to-client-js/utils.ts +14 -0
  97. package/src/jsx-to-ir.ts +96 -48
  98. package/src/prop-rewrite.ts +11 -0
  99. package/src/props-binding.ts +171 -6
  100. package/src/ssr-defaults.ts +10 -5
  101. package/src/static-literal.ts +21 -9
  102. package/src/types.ts +7 -0
@@ -32,6 +32,9 @@ import {
32
32
  buildStaticArrayDelegationPlan,
33
33
  } from './control-flow/plan/build-event-delegation.ts'
34
34
  import { stringifyEventDelegation } from './control-flow/stringify/event-delegation.ts'
35
+ import { findContainerOwnHandler, type ContainerOwnHandler } from './control-flow/plan/event-collision.ts'
36
+ import { loopEventDelegationVariant, type LoopDelegationIndex } from './control-flow/plan/loop-delegation-index.ts'
37
+ import { toDomEventName } from './utils.ts'
35
38
 
36
39
  /** Emit insert() calls for server-rendered reactive conditionals with branch configs. */
37
40
  export function emitConditionalUpdates(lines: string[], ctx: ClientJsContext): void {
@@ -66,14 +69,21 @@ export function emitClientOnlyConditionals(lines: string[], ctx: ClientJsContext
66
69
  * - `'component' / 'composite'` → events ride on the component's own
67
70
  * event surface, no delegation pass needed
68
71
  */
69
- export function emitLoopUpdates(lines: string[], ctx: ClientJsContext, unsafeLocalNames: Set<string>): void {
72
+ export function emitLoopUpdates(
73
+ lines: string[],
74
+ ctx: ClientJsContext,
75
+ unsafeLocalNames: Set<string>,
76
+ conditionalSlotIds: Set<string>,
77
+ loopDelegationIndex: LoopDelegationIndex,
78
+ ): void {
70
79
  // Lazy row graph (§9.4) name facts — built once per component, consulted
71
80
  // by every plain loop's eligibility gate.
72
81
  const lazyScope = buildLazyRowScopeInfo(ctx)
73
- for (const elem of ctx.loopElements) {
82
+ const profileComponentName = ctx.profile ? ctx.componentName : undefined
83
+ ctx.loopElements.forEach((elem, loopIndex) => {
74
84
  const plan = buildLoopPlan(elem, {
75
85
  unsafeLocalNames,
76
- profileComponentName: ctx.profile ? ctx.componentName : undefined,
86
+ profileComponentName,
77
87
  lazyScope,
78
88
  })
79
89
  // Stage 3 root cure — a JSX-bearing preamble can only be spliced into a
@@ -99,40 +109,67 @@ export function emitLoopUpdates(lines: string[], ctx: ClientJsContext, unsafeLoc
99
109
  `loop variant '${plan.kind}' has a preamble with declared names (${elem.preamble?.declaredNames.join(', ')}) but its plan's mapPreambleWrapped is empty — wire it up or the emitted call site references a name nothing declares`,
100
110
  )
101
111
  stringifyLoop(lines, plan)
102
- emitLoopEventDelegation(lines, elem, plan.kind, ctx.profile ? ctx.componentName : undefined)
103
- }
112
+ emitLoopEventDelegation(lines, elem, plan.kind, profileComponentName, {
113
+ loopIndex,
114
+ loopDelegationIndex,
115
+ interactiveElements: ctx.interactiveElements,
116
+ conditionalSlotIds,
117
+ })
118
+ })
119
+ }
120
+
121
+ interface CollisionInputs {
122
+ loopIndex: number
123
+ loopDelegationIndex: LoopDelegationIndex
124
+ interactiveElements: ClientJsContext['interactiveElements']
125
+ conditionalSlotIds: Set<string>
104
126
  }
105
127
 
106
128
  function emitLoopEventDelegation(
107
129
  lines: string[],
108
130
  elem: TopLevelLoop,
109
131
  kind: 'plain' | 'component' | 'composite' | 'static',
110
- profileComponentName?: string,
132
+ profileComponentName: string | undefined,
133
+ collision: CollisionInputs,
111
134
  ): void {
112
- if (kind === 'static') {
113
- // Event delegation for plain elements in static arrays (#537). Static
114
- // arrays have no data-key/bf-i markers, so walk up from target to the
115
- // container's direct child and use indexOf for index lookup.
116
- if (!elem.childComponent && elem.bindings.events.length > 0) {
117
- stringifyEventDelegation(lines, buildStaticArrayDelegationPlan(elem, profileComponentName))
118
- }
119
- return
120
- }
121
- // Dynamic plain-element body: keyed delegation by data-key/bf-i marker.
122
- //
123
- // `!elem.useElementReconciliation` is preserved here even though the
124
- // decision tree only routes to `'plain'` when `useElementReconciliation`
125
- // is false OR `hasInnerStructure` is false. The hand-constructed boundary
126
- // shape (`useElementReconciliation=true` AND empty nestedComponents /
127
- // innerLoops) is unreachable from real IR — the collector sets
128
- // `useElementReconciliation` only when it has at least one of those —
129
- // but the explicit guard keeps the legacy behaviour byte-equal even if a
130
- // future collector change makes that combination valid.
131
- if (
132
- kind === 'plain'
133
- && !elem.useElementReconciliation
134
- && elem.bindings.events.length > 0
135
- ) {
136
- stringifyEventDelegation(lines, buildDynamicLoopDelegationPlan(elem, profileComponentName))
135
+ // `loopEventDelegationVariant` (`plan/loop-delegation-index.ts`) is the
136
+ // single shared gate for "does this loop delegate, and via which
137
+ // builder" — also consulted by `LoopDelegationIndex` when precomputing
138
+ // collisions, so the two can't silently diverge (#2930 review). Static
139
+ // arrays have no data-key/bf-i markers, so 'static' walks up from target
140
+ // to the container's direct child and uses indexOf for index lookup;
141
+ // 'dynamic' (the `'plain'` kind, non-reconciled) does keyed delegation by
142
+ // data-key/bf-i marker instead. `'component'`/`'composite'` loops' events
143
+ // ride on the child component's own event surface, so they return `null`.
144
+ const variant = loopEventDelegationVariant(elem, kind)
145
+ if (!variant) return
146
+ const ownHandlers = collectOwnHandlers(elem, collision)
147
+ const plan = variant === 'static'
148
+ ? buildStaticArrayDelegationPlan(elem, profileComponentName, ownHandlers)
149
+ : buildDynamicLoopDelegationPlan(elem, profileComponentName, ownHandlers)
150
+ stringifyEventDelegation(lines, plan)
151
+ }
152
+
153
+ /**
154
+ * Collect, for THIS loop's container slot, which of its delegated DOM event
155
+ * names should also carry the container's own directly-authored handler
156
+ * (#2930) — only the loop `loopDelegationIndex` marks as "last" for a given
157
+ * (container slot, DOM event) pair may claim it; every other loop sharing
158
+ * the pair returns `undefined` for that entry and keeps emitting its
159
+ * listener unchanged.
160
+ */
161
+ function collectOwnHandlers(
162
+ elem: TopLevelLoop,
163
+ { loopIndex, loopDelegationIndex, interactiveElements, conditionalSlotIds }: CollisionInputs,
164
+ ): Map<string, ContainerOwnHandler> | undefined {
165
+ let ownHandlers: Map<string, ContainerOwnHandler> | undefined
166
+ const domEventNames = new Set(elem.bindings.events.map(ev => toDomEventName(ev.eventName)))
167
+ for (const domEventName of domEventNames) {
168
+ if (!loopDelegationIndex.isLastDelegator(elem.slotId, domEventName, loopIndex)) continue
169
+ const own = findContainerOwnHandler(interactiveElements, conditionalSlotIds, elem.slotId, domEventName)
170
+ if (!own) continue
171
+ ownHandlers ??= new Map()
172
+ ownHandlers.set(domEventName, own)
137
173
  }
174
+ return ownHandlers
138
175
  }
@@ -17,6 +17,7 @@ import { toLocaleDatePlugin, foldedArgToClientJs } from '../to-locale-date-lower
17
17
  import { tsNodeToParsedExpr } from '../expression-parser.ts'
18
18
  import type { LoweringMatcher } from '../lowering-registry.ts'
19
19
  import { rewriteBarePropRefs } from '../prop-rewrite.ts'
20
+ import { livePropReadExpr } from '../props-binding.ts'
20
21
 
21
22
  /**
22
23
  * Profile mode (#1690, SR3/SR4): the id appended to a DOM-binding effect so the
@@ -214,9 +215,13 @@ export function emitDedupedAttrUpdate(
214
215
  * or a name shadowed by an inner binding (`items.map((tag) => tag.x)`).
215
216
  * This function used to run its own `\btag\b`-style regex over the raw
216
217
  * expression text with no such distinction, so `queryHref(base, { tag: tag })`
217
- * rewrote the KEY too (`{ _p.tag: _p.tag }`, a syntax error) — #2741. Only
218
- * the default-value `(_p.x ?? <default>)` wrapping is specific to this call
219
- * site, supplied via `replacementFor` rather than a second copy of the walk.
218
+ * rewrote the KEY too (`{ _p.tag: _p.tag }`, a syntax error) — #2741.
219
+ *
220
+ * No `usage`/`usedAsCondition` is passed to `livePropReadExpr`: an attribute
221
+ * read is never a loop-array source or a conditional guard, so only the
222
+ * explicit destructure default applies here. The result survives the later
223
+ * whole-init-body rewrite (`rewriteDestructuredPropReads`) untouched — the
224
+ * `.name` slot of the `_p.x` it produces is a non-value position.
220
225
  */
221
226
  export function rewriteDestructuredPropsInExpr(expr: string, ctx: ClientJsContext): string {
222
227
  if (ctx.propsObjectName) return expr
@@ -233,11 +238,10 @@ export function rewriteDestructuredPropsInExpr(expr: string, ctx: ClientJsContex
233
238
  }
234
239
  if (propNames.size === 0) return expr
235
240
 
236
- const replacementFor = (localName: string, callerKey: string): string => {
237
- const defaultVal = propsByName.get(localName)?.defaultValue
238
- if (!defaultVal) return `${PROPS_PARAM}.${callerKey}`
239
- const defaultContainsArrow = propsByName.get(localName)?.defaultContainsArrow
240
- return `(${PROPS_PARAM}.${callerKey} ?? ${defaultContainsArrow ? `(${defaultVal})` : defaultVal})`
241
+ const replacementFor = (localName: string): string => {
242
+ const prop = propsByName.get(localName)
243
+ if (!prop) return `${PROPS_PARAM}.${localName}`
244
+ return livePropReadExpr(prop, undefined, false)
241
245
  }
242
246
 
243
247
  // Parenthesized so an object-literal or arrow-function expression parses
@@ -22,6 +22,7 @@ import { emitModuleLevelDeclarations, resolveFinalImports } from './emit-module-
22
22
  import { pruneUnusedPropExtractions } from './prune-unused-prop-extractions.ts'
23
23
  import { buildPhaseCtx, PHASES, runPhases } from './phases.ts'
24
24
  import { rewritePropsObjectRef } from './rewrite-props-object.ts'
25
+ import { rewriteDestructuredPropReads } from './rewrite-destructured-props.ts'
25
26
  import { buildInlinableConstants } from './emit-registration.ts'
26
27
  import { BF_SCOPE } from '@barefootjs/shared'
27
28
 
@@ -112,6 +113,11 @@ export function generateInitFunction(
112
113
  // `PropRewritten<T>` brand type so missing the rewrite becomes a
113
114
  // compile-time error. ---
114
115
  let generatedCode = rewritePropsObjectRef(lines.join('\n'), ctx.propsObjectName, ctx.restPropsName)
116
+ // Must run AFTER `rewritePropsObjectRef` (so `_p` is already the real
117
+ // parameter name) and BEFORE the hydrate line / module-constants splice:
118
+ // both live at module scope, where a per-instance `_p` read would be
119
+ // wrong.
120
+ generatedCode = rewriteDestructuredPropReads(generatedCode, ctx, propUsage)
115
121
  generatedCode += '\n' + hydrateLine
116
122
 
117
123
  // Substitute module-level declarations BEFORE import detection: a
@@ -24,6 +24,7 @@ import { resolveRestSpreadNames } from './prop-handling.ts'
24
24
  import { IMPORT_PLACEHOLDER, RUNTIME_MODULE, detectUsedImports, collectExternalImports } from './imports.ts'
25
25
  import { isInlinableInTemplate } from '../relocate.ts'
26
26
  import { buildSourceMapFromIR, type SourceMapV3 } from './source-map.ts'
27
+ import { resolvePropDeclaredType, baseTypeName } from '../rich-type-evidence.ts'
27
28
 
28
29
  export interface ClientJsResult {
29
30
  code: string
@@ -125,18 +126,59 @@ export function generateClientJsWithSourceMap(
125
126
  }
126
127
  }
127
128
 
129
+ /**
130
+ * Props the component's own client code needs LIVE rather than JSON-shaped:
131
+ * declared type resolves to a function (`() => number`, or object-form
132
+ * `Function`). Keyed by CALLER-FACING name (`sourceName ?? name`) to match
133
+ * the `bf-p` blob key a renaming destructure serializes under
134
+ * (`hono-adapter.ts`'s `callerKey`), valued by the declared type's printable
135
+ * text so a hydration-boundary error can name the real shape.
136
+ *
137
+ * Classification only. Whether it matters depends on how a given mount is
138
+ * used, which is a runtime fact (`__bfChild`) invisible here — a
139
+ * function-typed prop is perfectly fine for a component that is always a
140
+ * compiled child. That is why this is not BF049
141
+ * (`checkRichTypePropSerialization`), which must answer at declaration time.
142
+ *
143
+ * Known conservative miss: an ALIASED function type
144
+ * (`type Filter = (s: string) => boolean`) resolves to `kind: 'interface'`
145
+ * with no member walk, so it is not classified and falls back to the old
146
+ * silent drop. Same limitation BF049 has for aliased rich types.
147
+ */
148
+ function computeLiveOnlyProps(ir: ComponentIR, neededProps: ReadonlySet<string>): Record<string, string> {
149
+ const liveOnlyProps: Record<string, string> = {}
150
+ for (const param of ir.metadata.propsParams) {
151
+ // Same exclusions `propsToSerialize` (hono-adapter.ts) applies: `on*` is
152
+ // the event-handler convention, wired through the listener path rather
153
+ // than prop serialization, and `__*` is hydration plumbing that never
154
+ // round-trips through `bf-p`.
155
+ if (param.isRest || param.name.startsWith('on') || param.name.startsWith('__')) continue
156
+ if (!neededProps.has(param.name)) continue
157
+ const declared = resolvePropDeclaredType(param.sourceName ?? param.name, ir.metadata)
158
+ const isFunctionTyped =
159
+ declared?.kind === 'function' ||
160
+ (declared?.kind === 'interface' && baseTypeName(declared.raw) === 'Function')
161
+ if (!isFunctionTyped) continue
162
+ const callerKey = param.sourceName ?? param.name
163
+ liveOnlyProps[callerKey] = declared!.raw
164
+ }
165
+ return liveOnlyProps
166
+ }
167
+
128
168
  /**
129
169
  * Pre-pass analysis: determine whether a component needs a client JS init function,
130
170
  * and which props the init function actually reads. This runs BEFORE the adapter
131
171
  * so the adapter can use the results to optimize bf-p serialization.
132
172
  */
133
- export function analyzeClientNeeds(ir: ComponentIR): { needsInit: boolean; usedProps: string[] } {
173
+ export function analyzeClientNeeds(
174
+ ir: ComponentIR,
175
+ ): { needsInit: boolean; usedProps: string[]; liveOnlyProps: Record<string, string> } {
134
176
  const ctx = createContext(ir, undefined)
135
177
  const siblingOffsets = computeLoopSiblingOffsets(ir.root)
136
178
  collectElements(ir.root, ctx, siblingOffsets)
137
179
 
138
180
  if (!needsClientJs(ctx)) {
139
- return { needsInit: false, usedProps: [] }
181
+ return { needsInit: false, usedProps: [], liveOnlyProps: {} }
140
182
  }
141
183
 
142
184
  // Use the shared reference graph instead of replicating the extraction
@@ -162,7 +204,7 @@ export function analyzeClientNeeds(ir: ComponentIR): { needsInit: boolean; usedP
162
204
  }
163
205
  }
164
206
 
165
- return { needsInit: true, usedProps: [...neededProps] }
207
+ return { needsInit: true, usedProps: [...neededProps], liveOnlyProps: computeLiveOnlyProps(ir, neededProps) }
166
208
  }
167
209
 
168
210
  /** Initialize an empty ClientJsContext from component IR metadata. */
@@ -7,20 +7,30 @@
7
7
  *
8
8
  * `__scope` is the synthetic root slot id used when the component's
9
9
  * root element carries the listener (no `bf=` slot).
10
+ *
11
+ * A slot that is ALSO a `.map()` loop's container, with its own handler for
12
+ * the same DOM event a loop delegates, is skipped here too (#2930):
13
+ * `loopDelegationIndex` says so, and `control-flow.ts`'s `emitLoopUpdates`
14
+ * folds that handler into the delegated listener instead — emitting it here
15
+ * too would double-wire it back onto a separate `addEventListener` call,
16
+ * which is exactly the bug this split avoids.
10
17
  */
11
18
 
12
19
  import type { ClientJsContext } from '../types.ts'
13
20
  import { toDomEventName, varSlotId, wrapHandlerInBlock, wrapHandlerForTurn } from '../utils.ts'
21
+ import type { LoopDelegationIndex } from '../control-flow/plan/loop-delegation-index.ts'
14
22
 
15
23
  export function emitEventHandlers(
16
24
  lines: string[],
17
25
  ctx: ClientJsContext,
18
26
  conditionalSlotIds: Set<string>,
27
+ loopDelegationIndex: LoopDelegationIndex,
19
28
  ): void {
20
29
  for (const elem of ctx.interactiveElements) {
21
30
  if (conditionalSlotIds.has(elem.slotId)) continue
22
31
  for (const event of elem.events) {
23
32
  const eventName = toDomEventName(event.name)
33
+ if (loopDelegationIndex.isDelegated(elem.slotId, eventName)) continue
24
34
  // Profile mode (#1690, SR3): bracket the handler with turn markers so a
25
35
  // profiling run attributes the reactive work it triggers to this turn.
26
36
  const wrappedHandler = ctx.profile
@@ -6,6 +6,11 @@
6
6
  * function / constant or destructured prop), emit
7
7
  * `const handlerName = _p.handlerName`. Subsequent emission can call
8
8
  * `handlerName(...)` without writing the prop accessor inline.
9
+ *
10
+ * Only for props-object mode, where a bare `handlerName` would otherwise be
11
+ * a `ReferenceError`. In destructured mode `rewriteDestructuredPropReads`
12
+ * already turns every handler-name read into a live `_p.handlerName`, so the
13
+ * alias would only be emitted to be left unused.
9
14
  */
10
15
 
11
16
  import type { ClientJsContext } from '../types.ts'
@@ -17,6 +22,7 @@ export function emitPropsEventHandlers(
17
22
  usedFunctions: Set<string>,
18
23
  neededProps: Set<string>,
19
24
  ): void {
25
+ if (ctx.propsObjectName === null) return
20
26
  const localNames = new Set<string>([
21
27
  ...ctx.localFunctions.map(f => f.name),
22
28
  ...ctx.localConstants.map(c => c.name),
@@ -1,67 +1,48 @@
1
1
  /**
2
- * `props-extraction` phase — emit `const propName = _p.propName ?? <default>`
3
- * declarations at the top of the init body.
2
+ * `props-extraction` phase — emit the one surviving one-time prop
3
+ * extraction, `const children = _p.children [?? <default>]`.
4
4
  *
5
- * The default value depends on usage:
6
- * - prop has explicit default → use it (wrap arrow defaults
7
- * in parens for syntax safety)
8
- * - prop is consumed as a loop array → `?? []`
9
- * - prop has property/index access → `?? {}` (skipped when the
10
- * prop is a conditional guard
11
- * so falsy values stay falsy)
12
- * - otherwise → no default
5
+ * `children` must stay a ONE-TIME read: a prop's slot-children value is a
6
+ * getter that INSTANTIATES child components when read (see
7
+ * `prune-unused-prop-extractions.ts`), so reading it live at every
8
+ * `{children}` reference would re-mount the children each time. Every
9
+ * other destructured prop is rewritten to a live read instead, by
10
+ * `rewriteDestructuredPropReads` (`generate-init.ts`).
13
11
  *
14
- * Skipped entirely when the component uses an opaque props object name
15
- * (`propsObjectName != null`) — in that case downstream code reads
16
- * `_p.X` directly via the late-stage rename.
12
+ * The line is composed from `propReadBase`/`propReadFallback` rather than
13
+ * `livePropReadExpr` so it stays unparenthesized — that exact
14
+ * `const X = _p.X [?? d]` shape is what `pruneUnusedPropExtractions`'s AST
15
+ * matcher recognizes when the init body never reads `children`.
16
+ *
17
+ * Skipped entirely for an opaque props object (`propsObjectName != null`):
18
+ * downstream code there reads `_p.X` directly via the late-stage rename.
17
19
  */
18
20
 
19
21
  import type { PropUsage } from '../../types.ts'
20
- import { propHasPropertyAccess } from '../compute-prop-usage.ts'
22
+ import { computePropsUsedAsConditions } from '../compute-prop-usage.ts'
23
+ import { propReadBase, propReadFallback } from '../../props-binding.ts'
21
24
  import type { ClientJsContext } from '../types.ts'
22
25
  import { PROPS_PARAM } from '../utils.ts'
23
26
 
27
+ const CHILDREN = 'children'
28
+
24
29
  export function emitPropsExtraction(
25
30
  lines: string[],
26
31
  ctx: ClientJsContext,
27
32
  neededProps: Set<string>,
28
33
  propUsage: Map<string, PropUsage>,
29
34
  ): void {
30
- if (neededProps.size === 0 || ctx.propsObjectName) return
35
+ if (ctx.propsObjectName) return
36
+ if (!neededProps.has(CHILDREN)) return
31
37
 
32
- // Props that guard a conditional branch must remain falsy when undefined,
33
- // so `{}` (truthy) is the wrong default for them — track and exclude.
34
- const propsUsedAsConditions = new Set<string>()
35
- for (const cond of ctx.conditionalElements) {
36
- if (neededProps.has(cond.condition)) propsUsedAsConditions.add(cond.condition)
37
- }
38
- for (const cond of ctx.clientOnlyConditionals) {
39
- if (neededProps.has(cond.condition)) propsUsedAsConditions.add(cond.condition)
38
+ const prop = ctx.propsParams.find(p => p.name === CHILDREN)
39
+ if (!prop) {
40
+ lines.push(` const ${CHILDREN} = ${PROPS_PARAM}.${CHILDREN}`, '')
41
+ return
40
42
  }
41
43
 
42
- for (const propName of neededProps) {
43
- const prop = ctx.propsParams.find(p => p.name === propName)
44
- // `_p` is always keyed by the caller-facing name (#2524 CSR half); the
45
- // local binding on the left of `const` stays `propName`.
46
- const callerKey = prop?.sourceName ?? propName
47
- const usage = propUsage.get(propName)
48
- const defaultVal = prop?.defaultValue
49
- if (defaultVal) {
50
- // `props.onInput ?? () => {}` is a syntax error — `??` binds tighter
51
- // than the arrow head. Wrap arrow defaults in parens.
52
- const wrappedDefault = prop?.defaultContainsArrow ? `(${defaultVal})` : defaultVal
53
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey} ?? ${wrappedDefault}`)
54
- } else if (usage?.usedAsLoopArray) {
55
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey} ?? []`)
56
- } else if (propHasPropertyAccess(usage) && !propsUsedAsConditions.has(propName)) {
57
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey} ?? {}`)
58
- } else {
59
- // No synthesized default for a defaultless optional (`{ size }:
60
- // { size?: number }`): the JS binding is `undefined` when absent, and
61
- // a zero default would diverge from SSR (`size ?? 1` seeds 1
62
- // server-side; a `_p.size ?? 0` extraction would hydrate to 0).
63
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey}`)
64
- }
65
- }
66
- lines.push('')
44
+ const usedAsCondition = computePropsUsedAsConditions(ctx, neededProps).has(CHILDREN)
45
+ const fallback = propReadFallback(prop, propUsage.get(CHILDREN), usedAsCondition)
46
+ const read = propReadBase(prop) + (fallback === null ? '' : ` ?? ${fallback}`)
47
+ lines.push(` const ${CHILDREN} = ${read}`, '')
67
48
  }
@@ -17,6 +17,7 @@ import type { ComponentIR, PropUsage, ReferencesGraph } from '../types.ts'
17
17
  import type { ClientJsContext } from './types.ts'
18
18
  import type { LocalClassification } from './init-declarations.ts'
19
19
  import { collectConditionalSlotIds } from './phases/conditional-slot-ids.ts'
20
+ import { buildLoopDelegationIndex, type LoopDelegationIndex } from './control-flow/plan/loop-delegation-index.ts'
20
21
  import { emitEffectsAndOnMounts } from './phases/effects-and-on-mounts.ts'
21
22
  import { emitEventHandlers } from './phases/event-handlers.ts'
22
23
  import { emitInitStatements } from './phases/init-statements.ts'
@@ -51,6 +52,16 @@ export interface PhaseCtx {
51
52
  /** Slots that live inside a conditional branch (handled via `insert()`).
52
53
  * Cached so `event-handlers` and `ref-callbacks` don't recompute. */
53
54
  conditionalSlotIds: Set<string>
55
+ /**
56
+ * Which (container slot, DOM event) pairs a top-level `.map()` loop will
57
+ * delegate, and which loop is last among those sharing a pair (#2930).
58
+ * Computed once, ahead of both `event-handlers` (which must suppress a
59
+ * container's own listener for a delegated pair) and `loop-updates`
60
+ * (which folds that handler into the delegated listener instead) — those
61
+ * two phases run in that order, so this can't be computed by either one
62
+ * lazily on first use.
63
+ */
64
+ loopDelegationIndex: LoopDelegationIndex
54
65
  /** Local names that resolve to component-scope expressions and therefore
55
66
  * become `[]` / `undefined` when referenced from the CSR template (the
56
67
  * same set the registration emitter feeds `generateCsrTemplate`).
@@ -60,10 +71,13 @@ export interface PhaseCtx {
60
71
  }
61
72
 
62
73
  /** Build the read-only carrier that every phase consumes. */
63
- export function buildPhaseCtx(args: Omit<PhaseCtx, 'conditionalSlotIds'>): PhaseCtx {
74
+ export function buildPhaseCtx(
75
+ args: Omit<PhaseCtx, 'conditionalSlotIds' | 'loopDelegationIndex'>,
76
+ ): PhaseCtx {
64
77
  return {
65
78
  ...args,
66
79
  conditionalSlotIds: collectConditionalSlotIds(args.ctx),
80
+ loopDelegationIndex: buildLoopDelegationIndex(args.ctx.loopElements),
67
81
  }
68
82
  }
69
83
 
@@ -222,7 +236,7 @@ export const PHASES: readonly EmitPhase[] = [
222
236
  {
223
237
  id: 'event-handlers',
224
238
  dependsOn: ['rest-attr-applications'],
225
- run: (lines, p) => emitEventHandlers(lines, p.ctx, p.conditionalSlotIds),
239
+ run: (lines, p) => emitEventHandlers(lines, p.ctx, p.conditionalSlotIds, p.loopDelegationIndex),
226
240
  },
227
241
  {
228
242
  id: 'reactive-prop-bindings',
@@ -256,7 +270,7 @@ export const PHASES: readonly EmitPhase[] = [
256
270
  // contract is enforceable at registry-validation time.
257
271
  id: 'loop-updates',
258
272
  dependsOn: ['provider-and-child-inits'],
259
- run: (lines, p) => emitLoopUpdates(lines, p.ctx, p.unsafeLocalNames),
273
+ run: (lines, p) => emitLoopUpdates(lines, p.ctx, p.unsafeLocalNames, p.conditionalSlotIds, p.loopDelegationIndex),
260
274
  },
261
275
  {
262
276
  id: 'static-array-child-inits',
@@ -13,6 +13,7 @@ import type { Declaration } from '../declaration-sort.ts'
13
13
  import type { ClientJsContext } from '../types.ts'
14
14
  import type { ParamInfo, SignalInfo } from '../../types.ts'
15
15
  import { inferDefaultValue, PROPS_PARAM } from '../utils.ts'
16
+ import { livePropReadExpr } from '../../props-binding.ts'
16
17
  import { ENV_SIGNAL_CLIENT_FACTORY } from '../../adapters/env-signal.ts'
17
18
  import type {
18
19
  ControlledSignalEffectPlan,
@@ -182,11 +183,11 @@ function buildControlledSignalEffect(
182
183
  if (!signal.setter) return null // read-only — no sync needed
183
184
 
184
185
  const prop = lookups.propByName.get(controlled.propName)
185
- // `_p` is always keyed by the caller-facing name (#2524 CSR half).
186
- const callerKey = prop?.sourceName ?? controlled.propName
187
- const accessorExpr = prop?.defaultValue
188
- ? `(${PROPS_PARAM}.${callerKey} ?? ${prop.defaultValue})`
189
- : `${PROPS_PARAM}.${callerKey}`
186
+ // No `usage`/`usedAsCondition`: a controlled prop's sync effect reads it
187
+ // as a plain value, never as a loop array or a conditional guard.
188
+ const accessorExpr = prop
189
+ ? livePropReadExpr(prop, undefined, false)
190
+ : `${PROPS_PARAM}.${controlled.propName}`
190
191
 
191
192
  return { setter: signal.setter, accessorExpr }
192
193
  }
@@ -36,6 +36,35 @@ import ts from 'typescript'
36
36
  import { collectValueReferencedNames } from '../value-references.ts'
37
37
  import { PROPS_PARAM } from './utils.ts'
38
38
 
39
+ /**
40
+ * Does `init` read `<objectName>.<key>` or `<objectName>.<key> ?? <fallback>`?
41
+ * The one recognizer for "a prop read initializer", shared by
42
+ * `propExtractionName` below (which additionally requires the bound name to
43
+ * equal `key`, and always reads off `_p`), `rewriteBodyAliasReads`
44
+ * (`rewrite-destructured-props.ts`, which does not require the name match —
45
+ * a renamed alias's bound name differs from `key` by definition, but also
46
+ * always reads off `_p`), and `resolveBodyPropAliases` (`props-binding.ts`,
47
+ * which reads off the SOURCE-level props object name, e.g. `props` —
48
+ * `objectName` defaults to `_p` for the first two, post-rename, callers).
49
+ */
50
+ export function parsePropReadInitializer(
51
+ init: ts.Expression,
52
+ objectName: string = PROPS_PARAM,
53
+ ): { key: string; fallback: ts.Expression | null } | null {
54
+ let core: ts.Expression = init
55
+ let fallback: ts.Expression | null = null
56
+ if (
57
+ ts.isBinaryExpression(core) &&
58
+ core.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken
59
+ ) {
60
+ fallback = core.right
61
+ core = core.left
62
+ }
63
+ if (!ts.isPropertyAccessExpression(core)) return null
64
+ if (!ts.isIdentifier(core.expression) || core.expression.text !== objectName) return null
65
+ return { key: core.name.text, fallback }
66
+ }
67
+
39
68
  /** Is `stmt` a single-declarator `const X = _p.X…` prop extraction whose
40
69
  * initializer is `_p.X` or `_p.X ?? <default>`? Returns the bound name, or
41
70
  * null when the statement is anything else. */
@@ -46,16 +75,8 @@ function propExtractionName(stmt: ts.Statement): string | null {
46
75
  const decl = decls[0]!
47
76
  if (!ts.isIdentifier(decl.name) || !decl.initializer) return null
48
77
 
49
- let core: ts.Expression = decl.initializer
50
- if (
51
- ts.isBinaryExpression(core) &&
52
- core.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken
53
- ) {
54
- core = core.left
55
- }
56
- if (!ts.isPropertyAccessExpression(core)) return null
57
- if (!ts.isIdentifier(core.expression) || core.expression.text !== PROPS_PARAM) return null
58
- if (core.name.text !== decl.name.text) return null
78
+ const parsed = parsePropReadInitializer(decl.initializer)
79
+ if (parsed === null || parsed.key !== decl.name.text) return null
59
80
  return decl.name.text
60
81
  }
61
82