@barefootjs/jsx 0.35.4 → 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 (113) 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 +5306 -4949
  7. package/dist/ir-to-client-js/compute-inlinability.d.ts +8 -0
  8. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  9. package/dist/ir-to-client-js/compute-prop-usage.d.ts +6 -0
  10. package/dist/ir-to-client-js/compute-prop-usage.d.ts.map +1 -1
  11. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts +3 -2
  12. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  13. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts +12 -2
  14. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  15. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +40 -0
  16. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -0
  17. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +13 -0
  18. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts +45 -0
  20. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts.map +1 -0
  21. package/dist/ir-to-client-js/control-flow/plan/types.d.ts +2 -0
  22. package/dist/ir-to-client-js/control-flow/plan/types.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts +12 -0
  24. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/control-flow.d.ts +2 -1
  26. package/dist/ir-to-client-js/control-flow.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/emit-reactive.d.ts +7 -3
  28. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/imports.d.ts +2 -2
  31. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/index.d.ts +1 -0
  33. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/phases/event-handlers.d.ts +9 -1
  35. package/dist/ir-to-client-js/phases/event-handlers.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts +5 -0
  37. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/phases/props-extraction.d.ts +15 -13
  39. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/phases.d.ts +12 -1
  41. package/dist/ir-to-client-js/phases.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +50 -0
  45. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +29 -0
  47. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -0
  48. package/dist/ir-to-client-js/utils.d.ts +21 -1
  49. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  50. package/dist/jsx-to-ir.d.ts.map +1 -1
  51. package/dist/prop-rewrite.d.ts.map +1 -1
  52. package/dist/props-binding.d.ts +112 -1
  53. package/dist/props-binding.d.ts.map +1 -1
  54. package/dist/ssr-defaults.d.ts.map +1 -1
  55. package/dist/static-literal.d.ts +20 -8
  56. package/dist/static-literal.d.ts.map +1 -1
  57. package/dist/types.d.ts +38 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/package.json +2 -2
  60. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +31 -35
  61. package/src/__tests__/aliased-destructured-prop-csr.test.ts +19 -7
  62. package/src/__tests__/body-destructured-prop-default-propsparams.test.ts +153 -0
  63. package/src/__tests__/body-destructured-props-live.test.ts +245 -0
  64. package/src/__tests__/client-js-generation.test.ts +11 -4
  65. package/src/__tests__/client-only-date-lowering.test.ts +5 -2
  66. package/src/__tests__/destructured-from-props-localconst-value.test.ts +17 -6
  67. package/src/__tests__/destructured-props-live.test.ts +167 -0
  68. package/src/__tests__/doc-examples.test.ts +2 -4
  69. package/src/__tests__/event-delegation-container-collision-2930.test.ts +197 -0
  70. package/src/__tests__/format-error.test.ts +5 -3
  71. package/src/__tests__/issue-2910-mutated-const-not-inlined.test.ts +118 -0
  72. package/src/__tests__/issue-2910-own-scope-id-emission.test.ts +64 -0
  73. package/src/__tests__/live-only-props.test.ts +160 -0
  74. package/src/__tests__/prop-references.test.ts +26 -17
  75. package/src/__tests__/props-destructuring.test.ts +6 -275
  76. package/src/__tests__/prune-unused-prop-extractions.test.ts +11 -5
  77. package/src/__tests__/signal-getter-not-called.test.ts +5 -0
  78. package/src/__tests__/ssr-defaults.test.ts +83 -0
  79. package/src/__tests__/staged-ir/02-shadow-guards.test.ts +12 -5
  80. package/src/__tests__/static-literal.test.ts +39 -4
  81. package/src/analyzer-context.ts +8 -7
  82. package/src/analyzer.ts +233 -106
  83. package/src/errors.ts +7 -8
  84. package/src/ir-to-client-js/compute-inlinability.ts +8 -1
  85. package/src/ir-to-client-js/compute-prop-usage.ts +19 -0
  86. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +5 -0
  87. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +27 -11
  88. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +55 -0
  89. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +13 -0
  90. package/src/ir-to-client-js/control-flow/plan/loop-delegation-index.ts +79 -0
  91. package/src/ir-to-client-js/control-flow/plan/types.ts +2 -0
  92. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +50 -10
  93. package/src/ir-to-client-js/control-flow.ts +68 -31
  94. package/src/ir-to-client-js/emit-reactive.ts +12 -8
  95. package/src/ir-to-client-js/emit-registration.ts +2 -2
  96. package/src/ir-to-client-js/generate-init.ts +22 -2
  97. package/src/ir-to-client-js/imports.ts +6 -0
  98. package/src/ir-to-client-js/index.ts +51 -3
  99. package/src/ir-to-client-js/phases/event-handlers.ts +10 -0
  100. package/src/ir-to-client-js/phases/props-event-handlers.ts +6 -0
  101. package/src/ir-to-client-js/phases/props-extraction.ts +29 -48
  102. package/src/ir-to-client-js/phases.ts +17 -3
  103. package/src/ir-to-client-js/plan/build-declaration-emit.ts +6 -5
  104. package/src/ir-to-client-js/prop-handling.ts +9 -0
  105. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +31 -10
  106. package/src/ir-to-client-js/rewrite-destructured-props.ts +210 -0
  107. package/src/ir-to-client-js/utils.ts +29 -1
  108. package/src/jsx-to-ir.ts +110 -48
  109. package/src/prop-rewrite.ts +11 -0
  110. package/src/props-binding.ts +171 -6
  111. package/src/ssr-defaults.ts +10 -5
  112. package/src/static-literal.ts +21 -9
  113. package/src/types.ts +38 -0
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import type { LoopChildEvent, LoopOffset, TopLevelLoop } from '../../types.ts'
9
+ import type { ContainerOwnHandler } from './event-collision.ts'
9
10
 
10
11
  /**
11
12
  * Plan for a loop's event-delegation block. Covers three legacy emitters:
@@ -33,6 +34,18 @@ export interface EventDelegationPlan {
33
34
  * profiling is off, so the emitted dispatcher is unchanged (SR8).
34
35
  */
35
36
  profileComponentName?: string
37
+ /**
38
+ * The container's own directly-authored handler(s) to invoke after this
39
+ * plan's delegated dispatch(es) run — and only if none of them called
40
+ * `stopPropagation()`/`stopImmediatePropagation()` (#2930). Keyed by DOM
41
+ * event name (the `eventsByName` grouping key the stringifier already
42
+ * builds). Populated only on the ONE delegation plan chosen as "last" for
43
+ * a given (container slot, DOM event) pair — see `LoopDelegationIndex`
44
+ * (`plan/loop-delegation-index.ts`) — so every other plan sharing that
45
+ * pair keeps emitting its listener byte-identical to before. `undefined`
46
+ * (the common case: no collision) keeps the emitted listener unchanged.
47
+ */
48
+ ownHandlers?: Map<string, ContainerOwnHandler>
36
49
  }
37
50
 
38
51
  /**
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Precompute which `.map()` loops will emit a delegated event listener for
3
+ * which (container slot, DOM event) pairs — the fact both the direct-handler
4
+ * phase and the loop-delegation phase need to agree on when a container also
5
+ * carries its own handler for the same event (#2930).
6
+ *
7
+ * Built once (independent of the phases that actually emit code, and before
8
+ * either of them runs — `event-handlers` precedes `loop-updates` in
9
+ * `phases.ts`) from `ClientJsContext.loopElements` alone, via
10
+ * `classifyLoopKind` — the same predicates `buildLoopPlan` uses, without
11
+ * building the full `LoopPlan`.
12
+ */
13
+
14
+ import type { TopLevelLoop, LoopChildEvent } from '../../types.ts'
15
+ import { toDomEventName } from '../../utils.ts'
16
+ import { classifyLoopKind, type LoopVariantKind } from './build-loop.ts'
17
+
18
+ export interface LoopDelegationIndex {
19
+ /**
20
+ * True when SOME loop under `containerSlotId` delegates `domEventName`.
21
+ * The direct listener in `phases/event-handlers.ts` must be suppressed
22
+ * whenever this is true, regardless of how many loops share the pair —
23
+ * only one of them (see `isLastDelegator`) actually invokes the
24
+ * container's own handler; the others must not also emit it separately.
25
+ */
26
+ isDelegated(containerSlotId: string, domEventName: string): boolean
27
+ /**
28
+ * True when the loop at `loopIndex` (its position in `loopElements`,
29
+ * matching emission order) is the LAST loop delegating this pair. Only
30
+ * that loop's dispatcher can safely gate the container's own handler: an
31
+ * earlier delegated listener sharing the pair may still see a row call
32
+ * `stopPropagation()` after its own dispatch has already run and decided
33
+ * whether to fire the container's own handler.
34
+ */
35
+ isLastDelegator(containerSlotId: string, domEventName: string, loopIndex: number): boolean
36
+ }
37
+
38
+ export function buildLoopDelegationIndex(loopElements: readonly TopLevelLoop[]): LoopDelegationIndex {
39
+ const lastIndexForPair = new Map<string, number>()
40
+ loopElements.forEach((elem, index) => {
41
+ if (!loopEventDelegationVariant(elem, classifyLoopKind(elem))) return
42
+ for (const domEventName of domEventNamesOf(elem.bindings.events)) {
43
+ lastIndexForPair.set(pairKey(elem.slotId, domEventName), index)
44
+ }
45
+ })
46
+ return {
47
+ isDelegated: (containerSlotId, domEventName) =>
48
+ lastIndexForPair.has(pairKey(containerSlotId, domEventName)),
49
+ isLastDelegator: (containerSlotId, domEventName, loopIndex) =>
50
+ lastIndexForPair.get(pairKey(containerSlotId, domEventName)) === loopIndex,
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Which delegation builder (`control-flow.ts`'s `emitLoopEventDelegation`)
56
+ * would use for `elem`, or `null` if it doesn't delegate at all —
57
+ * `'component'`/`'composite'` loops' events ride on the child component's
58
+ * own event surface instead. The single shared gate so this index and the
59
+ * actual emission can't silently diverge (#2930 review) — previously each
60
+ * re-implemented the same `kind === 'static' && !childComponent` /
61
+ * `kind === 'plain' && !useElementReconciliation` check inline.
62
+ */
63
+ export function loopEventDelegationVariant(
64
+ elem: TopLevelLoop,
65
+ kind: LoopVariantKind,
66
+ ): 'static' | 'dynamic' | null {
67
+ if (elem.bindings.events.length === 0) return null
68
+ if (kind === 'static') return elem.childComponent ? null : 'static'
69
+ if (kind === 'plain') return elem.useElementReconciliation ? null : 'dynamic'
70
+ return null
71
+ }
72
+
73
+ function domEventNamesOf(events: readonly LoopChildEvent[]): string[] {
74
+ return [...new Set(events.map(ev => toDomEventName(ev.eventName)))]
75
+ }
76
+
77
+ function pairKey(containerSlotId: string, domEventName: string): string {
78
+ return `${containerSlotId}:${domEventName}`
79
+ }
@@ -14,6 +14,7 @@
14
14
  * `CompositeLoopPlan`, `StaticLoopPlan`),
15
15
  * `NestedComponentInit`
16
16
  * event-delegation.ts — `EventDelegationPlan`, `ItemLookup` family
17
+ * event-collision.ts — `ContainerOwnHandler`
17
18
  *
18
19
  * This file lets callers continue to write
19
20
  * `import type { ... } from '../plan/types.ts'` without caring which file
@@ -54,6 +55,7 @@ export type {
54
55
  DynamicIndexItemLookup,
55
56
  StaticIndexItemLookup,
56
57
  } from './event-delegation.ts'
58
+ export type { ContainerOwnHandler } from './event-collision.ts'
57
59
 
58
60
  // Re-export legacy types referenced from Plan-level code paths.
59
61
  export type {
@@ -30,9 +30,21 @@
30
30
  *
31
31
  * Each shape has a `hasBindings` variant that lands on a `__bfLoopItem`
32
32
  * sentinel before destructuring (#951 TDZ-safe).
33
+ *
34
+ * When `plan.ownHandlers` has an entry for the group's DOM event name
35
+ * (#2930 — the container itself also carries a directly-authored handler for
36
+ * this event), the shape above grows two additions, BOTH gated on
37
+ * `!__bfEvt.cancelBubble`: right after `<handlerCall>` (so a row's own
38
+ * `stopPropagation()` suppresses it), and again after the last event in the
39
+ * group (so a sibling `.map()` loop sharing this container/event — whose
40
+ * listener already ran, matched one of ITS rows, and called
41
+ * `stopPropagation()` — also suppresses it here, even though none of THIS
42
+ * loop's rows matched). A dispatch nothing has stopped (e.g. a click on the
43
+ * container's own background) still fires it, same as today's separate
44
+ * listener would.
33
45
  */
34
46
 
35
- import { toDomEventName, varSlotId, substituteLoopBindings, buildLoopChildIndexSubtraction, DATA_KEY, keyAttrName } from '../../utils.ts'
47
+ import { toDomEventName, varSlotId, substituteLoopBindings, buildLoopChildIndexSubtraction, DATA_KEY, keyAttrName, NON_BUBBLING_EVENTS } from '../../utils.ts'
36
48
  import { extractFreeIdentifiersFromText } from '../../csr-substitute.ts'
37
49
  import { identifierPattern } from '../../../identifier-pattern.ts'
38
50
  import type {
@@ -43,13 +55,6 @@ import type {
43
55
  LoopChildEvent,
44
56
  } from '../plan/types.ts'
45
57
 
46
- /** Non-bubbling events that require addEventListener with capture for delegation. */
47
- const NON_BUBBLING_EVENTS = new Set([
48
- 'blur', 'focus', 'load', 'unload',
49
- 'mouseenter', 'mouseleave',
50
- 'pointerenter', 'pointerleave',
51
- ])
52
-
53
58
  /**
54
59
  * Profile mode (#1690, SR3): bracket a delegated handler call with turn
55
60
  * markers so a profiling run attributes the reactive work it triggers to one
@@ -96,7 +101,7 @@ function preambleLineForHandler(
96
101
  }
97
102
 
98
103
  export function stringifyEventDelegation(lines: string[], plan: EventDelegationPlan): void {
99
- const { containerVar, events, itemLookup, profileComponentName } = plan
104
+ const { containerVar, events, itemLookup, profileComponentName, ownHandlers } = plan
100
105
  const eventsByName = new Map<string, LoopChildEvent[]>()
101
106
  for (const ev of events) {
102
107
  if (!eventsByName.has(ev.eventName)) eventsByName.set(ev.eventName, [])
@@ -107,10 +112,19 @@ export function stringifyEventDelegation(lines: string[], plan: EventDelegationP
107
112
  // Sort deepest-first so child elements are checked before parents (#774)
108
113
  evs.sort((a, b) => b.domDepth - a.domDepth)
109
114
  const useCapture = NON_BUBBLING_EVENTS.has(eventName)
115
+ const domEventName = toDomEventName(eventName)
116
+ // Container's own directly-authored handler for this event, folded into
117
+ // THIS listener instead of a separate `addEventListener` call (#2930):
118
+ // `undefined` when there's no collision, which keeps every line below
119
+ // byte-identical to before.
120
+ const ownHandler = ownHandlers?.get(domEventName)
121
+ const ownHandlerCall = ownHandler
122
+ ? withTurn(`(${ownHandler.handler.trim()})(__bfEvt)`, profileComponentName, ownHandler.slotId, ownHandler.eventName)
123
+ : null
110
124
  if (useCapture) {
111
125
  lines.push(` if (${containerVar}) ${containerVar}.addEventListener('${eventName}', (__bfEvt) => {`)
112
126
  } else {
113
- lines.push(` if (${containerVar}) ${containerVar}.addEventListener('${toDomEventName(eventName)}', (__bfEvt) => {`)
127
+ lines.push(` if (${containerVar}) ${containerVar}.addEventListener('${domEventName}', (__bfEvt) => {`)
114
128
  }
115
129
  lines.push(` const target = __bfEvt.target`)
116
130
  for (const ev of evs) {
@@ -136,9 +150,35 @@ export function stringifyEventDelegation(lines: string[], plan: EventDelegationP
136
150
  emitStaticIndexLookup(lines, ev, handlerCall, itemLookup, containerVar)
137
151
  break
138
152
  }
153
+ // Row `stopPropagation()`/`stopImmediatePropagation()` blocks the
154
+ // container's own handler too (#2930). `cancelBubble` reflects either
155
+ // call per the DOM Standard, so a single flag read is enough — once
156
+ // merged into this one listener there is exactly one BarefootJS
157
+ // listener left on the container for this event, so the two APIs have
158
+ // nothing left to distinguish (native bubbling to real ancestors, and
159
+ // any listener attached directly via `ref`, are unaffected either
160
+ // way). A row that never matches (e.g. a stale-DOM race) leaves
161
+ // `cancelBubble` false, so the own handler still fires — unchanged
162
+ // from today's always-fires behavior for that case.
163
+ if (ownHandlerCall) {
164
+ lines.push(` if (!__bfEvt.cancelBubble) { ${ownHandlerCall} }`)
165
+ }
139
166
  lines.push(` return`)
140
167
  lines.push(` }`)
141
168
  }
169
+ if (ownHandlerCall) {
170
+ // No row in THIS loop matched. Still gated on `cancelBubble` (#2930
171
+ // review): when a sibling `.map()` loop shares this container/event,
172
+ // its listener runs first (registration order) and may have already
173
+ // matched one of ITS rows and called `stopPropagation()` — same-node
174
+ // listeners aren't stopped by that, so this loop's listener still
175
+ // runs, finds no match among its own rows, and reaches here. Without
176
+ // the guard that reproduces the exact bug this PR fixes, just for the
177
+ // multi-sibling-loop configuration. A genuine "click on the
178
+ // container's own background" leaves `cancelBubble` false, so the
179
+ // own handler still fires — same as today's separate listener.
180
+ lines.push(` if (!__bfEvt.cancelBubble) { ${ownHandlerCall} }`)
181
+ }
142
182
  if (useCapture) {
143
183
  lines.push(` }, true)`)
144
184
  } else {
@@ -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
@@ -6,7 +6,7 @@
6
6
 
7
7
  import type { ComponentIR, IRFragment, IRNode, ReferencesGraph, SignalInfo } from '../types.ts'
8
8
  import type { ClientJsContext } from './types.ts'
9
- import { PROPS_PARAM } from './utils.ts'
9
+ import { PROPS_PARAM, isCommentScopedRoot } from './utils.ts'
10
10
  import { computeInlinability, toLegacyInlinability } from './compute-inlinability.ts'
11
11
  import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate, createStringProtector } from './html-template.ts'
12
12
  import { markupSlotIdsOf } from './markup-slots.ts'
@@ -215,7 +215,7 @@ export function emitRegistrationAndHydration(
215
215
  // DOM presence of its own, and `materializeComponent` must leave
216
216
  // `scopeId` null so it doesn't stamp over (or duplicate) the child's.
217
217
  const isFragmentRoot = _ir.root.type === 'fragment' && !!(_ir.root as IRFragment).needsScopeComment
218
- const isCommentScope = isFragmentRoot || _ir.root.type === 'component'
218
+ const isCommentScope = isCommentScopedRoot(_ir.root)
219
219
 
220
220
  // Build ComponentDef object for hydrate()
221
221
  const defParts: string[] = [`init: init${name}`]
@@ -10,7 +10,7 @@
10
10
 
11
11
  import type { ComponentIR } from '../types.ts'
12
12
  import type { ClientJsContext } from './types.ts'
13
- import { PROPS_PARAM } from './utils.ts'
13
+ import { PROPS_PARAM, isCommentScopedRoot } from './utils.ts'
14
14
  import { buildReferencesGraph } from './build-references.ts'
15
15
  import { computePropUsage } from './compute-prop-usage.ts'
16
16
  import { IMPORT_PLACEHOLDER, MODULE_CONSTANTS_PLACEHOLDER } from './imports.ts'
@@ -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
 
@@ -44,7 +45,21 @@ export function generateInitFunction(
44
45
  // Host scope id for (bf-h, bf-m) child lookups inside this init body
45
46
  // (#1249). Compile-time selectors emit
46
47
  // `[bf-h="${__scopeId}"][bf-m="<slotId>"]` against this value.
47
- lines.push(` const __scopeId = __scope.getAttribute('${BF_SCOPE}')`)
48
+ //
49
+ // A comment-scoped root (`comment: true` — a `needsScopeComment` fragment
50
+ // root, or a root that is itself a single child-component call, #2649) is
51
+ // mounted on a PROXY element whose OWN `bf-s` attribute names its
52
+ // host/parent scope, not this component's — this component's real id
53
+ // lives in the comment-scope registry the proxy was registered under
54
+ // (`ownScopeId`, #2910). Reading the raw attribute there resolves to the
55
+ // wrong id, so every `.map()`-produced child this component's init tries
56
+ // to find via `[bf-h="${__scopeId}"]` silently matches nothing. An
57
+ // element-scoped root keeps reading the attribute directly.
58
+ lines.push(
59
+ isCommentScopedRoot(ir.root)
60
+ ? ` const __scopeId = ownScopeId(__scope)`
61
+ : ` const __scopeId = __scope.getAttribute('${BF_SCOPE}')`,
62
+ )
48
63
  lines.push('')
49
64
 
50
65
  // --- Analysis: one graph, many queries; scope routing as data ---
@@ -98,6 +113,11 @@ export function generateInitFunction(
98
113
  // `PropRewritten<T>` brand type so missing the rewrite becomes a
99
114
  // compile-time error. ---
100
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)
101
121
  generatedCode += '\n' + hydrateLine
102
122
 
103
123
  // Substitute module-level declarations BEFORE import detection: a
@@ -61,6 +61,12 @@ export const RUNTIME_IMPORT_CANDIDATES = [
61
61
  // rewrite targets `formatDate(recv, pattern, tz)`, so the emitted code
62
62
  // needs the runtime export when the component didn't import it itself.
63
63
  'formatDate',
64
+ // A comment-scoped component's own scope id (#2910) — reads the
65
+ // `commentScopeRegistry` entry the proxy element was registered under
66
+ // (falling back to its `bf-s` attribute for an element-scoped root), so
67
+ // `[bf-h="${__scopeId}"]` child lookups target THIS component's children
68
+ // rather than the proxy's host/parent scope. See `generate-init.ts`.
69
+ 'ownScopeId',
64
70
  ] as const
65
71
 
66
72
  /** @deprecated Use RUNTIME_IMPORT_CANDIDATES */
@@ -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. */
@@ -256,6 +298,12 @@ function hasInitScopeOnlyConstant(ctx: ClientJsContext): boolean {
256
298
  for (const c of ctx.localConstants) {
257
299
  if (c.isModule || c.isJsx || c.containsArrow || c.systemConstructKind) continue
258
300
  if (!c.value) continue
301
+ // A mutated binding's value is a pre-mutation snapshot (#2910) —
302
+ // `isInlinableInTemplate` would happily pass a value like `{}` that
303
+ // looks safe on its own, but the mutating statement that gives it its
304
+ // real value only runs in init scope, so the const needs init scope
305
+ // exactly as if the value itself had failed the check.
306
+ if (c.mutatedAfterDeclaration) return true
259
307
  if (!isInlinableInTemplate(c.value, env).ok) return true
260
308
  }
261
309
  return false
@@ -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),