@barefootjs/jsx 0.35.5 → 0.35.7

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 (106) 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 +6745 -6488
  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/html-template.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/index.d.ts +1 -0
  30. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/phases/event-handlers.d.ts +9 -1
  32. package/dist/ir-to-client-js/phases/event-handlers.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts +5 -0
  34. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/phases/props-extraction.d.ts +15 -13
  36. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/phases.d.ts +12 -1
  38. package/dist/ir-to-client-js/phases.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +50 -0
  41. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +29 -0
  43. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -0
  44. package/dist/ir-to-client-js/utils.d.ts +9 -0
  45. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  46. package/dist/jsx-to-ir.d.ts.map +1 -1
  47. package/dist/prop-rewrite.d.ts.map +1 -1
  48. package/dist/props-binding.d.ts +123 -1
  49. package/dist/props-binding.d.ts.map +1 -1
  50. package/dist/ssr-defaults.d.ts.map +1 -1
  51. package/dist/static-literal.d.ts +20 -8
  52. package/dist/static-literal.d.ts.map +1 -1
  53. package/dist/types.d.ts +7 -0
  54. package/dist/types.d.ts.map +1 -1
  55. package/package.json +2 -2
  56. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +31 -35
  57. package/src/__tests__/aliased-destructured-prop-csr.test.ts +19 -7
  58. package/src/__tests__/body-destructured-prop-default-arrow.test.ts +142 -0
  59. package/src/__tests__/body-destructured-prop-default-propsparams.test.ts +153 -0
  60. package/src/__tests__/body-destructured-props-live.test.ts +245 -0
  61. package/src/__tests__/client-js-generation.test.ts +11 -4
  62. package/src/__tests__/client-only-date-lowering.test.ts +5 -2
  63. package/src/__tests__/destructured-from-props-localconst-value.test.ts +17 -6
  64. package/src/__tests__/destructured-props-live.test.ts +167 -0
  65. package/src/__tests__/doc-examples.test.ts +2 -4
  66. package/src/__tests__/event-delegation-container-collision-2930.test.ts +197 -0
  67. package/src/__tests__/format-error.test.ts +5 -3
  68. package/src/__tests__/issue-2960-multi-root-cond-same-tag.test.ts +141 -0
  69. package/src/__tests__/live-only-props.test.ts +160 -0
  70. package/src/__tests__/prop-references.test.ts +26 -17
  71. package/src/__tests__/props-destructuring.test.ts +6 -275
  72. package/src/__tests__/prune-unused-prop-extractions.test.ts +11 -5
  73. package/src/__tests__/signal-getter-not-called.test.ts +5 -0
  74. package/src/__tests__/ssr-defaults.test.ts +83 -0
  75. package/src/__tests__/staged-ir/02-shadow-guards.test.ts +12 -5
  76. package/src/__tests__/static-literal.test.ts +39 -4
  77. package/src/analyzer-context.ts +8 -7
  78. package/src/analyzer.ts +88 -89
  79. package/src/errors.ts +7 -8
  80. package/src/ir-to-client-js/compute-prop-usage.ts +19 -0
  81. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +5 -0
  82. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +27 -11
  83. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +55 -0
  84. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +13 -0
  85. package/src/ir-to-client-js/control-flow/plan/loop-delegation-index.ts +79 -0
  86. package/src/ir-to-client-js/control-flow/plan/types.ts +2 -0
  87. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +50 -10
  88. package/src/ir-to-client-js/control-flow.ts +68 -31
  89. package/src/ir-to-client-js/emit-reactive.ts +12 -8
  90. package/src/ir-to-client-js/generate-init.ts +6 -0
  91. package/src/ir-to-client-js/html-template.ts +65 -9
  92. package/src/ir-to-client-js/index.ts +45 -3
  93. package/src/ir-to-client-js/phases/event-handlers.ts +10 -0
  94. package/src/ir-to-client-js/phases/props-event-handlers.ts +6 -0
  95. package/src/ir-to-client-js/phases/props-extraction.ts +29 -48
  96. package/src/ir-to-client-js/phases.ts +17 -3
  97. package/src/ir-to-client-js/plan/build-declaration-emit.ts +6 -5
  98. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +31 -10
  99. package/src/ir-to-client-js/rewrite-destructured-props.ts +222 -0
  100. package/src/ir-to-client-js/utils.ts +14 -0
  101. package/src/jsx-to-ir.ts +96 -48
  102. package/src/prop-rewrite.ts +11 -0
  103. package/src/props-binding.ts +185 -6
  104. package/src/ssr-defaults.ts +10 -5
  105. package/src/static-literal.ts +21 -9
  106. package/src/types.ts +7 -0
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Find a container's own directly-authored event handler that collides with
3
+ * a `.map()` row's delegated dispatcher for the same DOM event (#2930).
4
+ *
5
+ * `.map()` rows compiled via delegation share their delegated listener's
6
+ * node with the loop's static container — the compiler registers ONE
7
+ * `addEventListener` on the container, resolving `event.target` back to a
8
+ * row. When the container ALSO carries its own handler for the same event,
9
+ * both end up as separate `addEventListener` calls on the identical DOM
10
+ * node, so a row's `stopPropagation()` can't stop the container's own
11
+ * handler: native DOM `stopPropagation()` only blocks bubbling to *other
12
+ * nodes*, never other listeners already registered on the *same* node.
13
+ *
14
+ * This is the one place that answers "does this container slot have its own
15
+ * handler for this event" — both `phases/event-handlers.ts` (which must
16
+ * suppress the direct listener when the answer is yes) and
17
+ * `control-flow.ts` (which must fold that handler into the delegated
18
+ * dispatcher instead) call it, rather than answering the question twice.
19
+ */
20
+
21
+ import type { InteractiveElement } from '../../types.ts'
22
+ import { toDomEventName, NON_BUBBLING_EVENTS } from '../../utils.ts'
23
+
24
+ export interface ContainerOwnHandler {
25
+ /** The container element's own slot id (used for profile-mode turn ids). */
26
+ slotId: string
27
+ /** Original (pre-DOM-mapped) event name, e.g. 'contextmenu'. */
28
+ eventName: string
29
+ handler: string
30
+ }
31
+
32
+ /**
33
+ * Find the container's own handler for `domEventName`, if any.
34
+ *
35
+ * Returns `null` for a non-bubbling event (focus/blur/…) — those delegate
36
+ * in capture mode, and a container's own bubble-phase handler there only
37
+ * ever fires when the container itself is the event target, never for a
38
+ * descendant row, so there is no collision to resolve. Also returns `null`
39
+ * when `containerSlotId` lives inside a conditional branch — that slot's
40
+ * own handler (if any) is bound by `insert()`'s `bindEvents` in a separate
41
+ * scope this check doesn't cover.
42
+ */
43
+ export function findContainerOwnHandler(
44
+ interactiveElements: InteractiveElement[],
45
+ conditionalSlotIds: Set<string>,
46
+ containerSlotId: string,
47
+ domEventName: string,
48
+ ): ContainerOwnHandler | null {
49
+ if (NON_BUBBLING_EVENTS.has(domEventName)) return null
50
+ if (conditionalSlotIds.has(containerSlotId)) return null
51
+ const elem = interactiveElements.find(e => e.slotId === containerSlotId)
52
+ if (!elem) return null
53
+ const match = elem.events.find(event => toDomEventName(event.name) === domEventName)
54
+ return match ? { slotId: containerSlotId, eventName: match.name, handler: match.handler } : null
55
+ }
@@ -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
@@ -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
@@ -1621,17 +1621,73 @@ export function addCondAttrToTemplate(html: string, condId: string): string {
1621
1621
  return `<!--bf-cond-start:${condId}-->${html}<!--bf-cond-end:${condId}-->`
1622
1622
  }
1623
1623
 
1624
- /** Check if HTML string has a single root element (not multiple siblings). */
1624
+ /**
1625
+ * Check if HTML string has a single root element (not multiple siblings).
1626
+ *
1627
+ * Walks top-level tags tracking nesting depth rather than checking only
1628
+ * "does the string end with a closing tag of the root's tag name" — that
1629
+ * lexical shortcut matches `<div id="before">before</div><div id="after">after</div>`
1630
+ * (two sibling `<div>`s) as a false single root, because the STRING happens
1631
+ * to end in `</div>`, the same tag name the root opened with, even though
1632
+ * that closing tag belongs to the second, unrelated div (#2960). A
1633
+ * multi-root branch wrongly classified here gets `bf-c="<id>"` stamped
1634
+ * onto only its first element instead of being comment-wrapped, and
1635
+ * `insert()`'s runtime then drops every sibling but the first on a branch
1636
+ * swap (`updateElementConditional`'s `fragment.firstChild`).
1637
+ */
1625
1638
  function isSingleRootElement(html: string): boolean {
1626
- // Match the opening tag name, then find its closing tag
1627
- const match = html.match(/^<(\w+)[\s>]/)
1639
+ const trimmed = html.trim()
1640
+ // Same gate as before this fix: only a tag name matching `\w+`,
1641
+ // followed immediately by whitespace or `>`, is recognized here — that
1642
+ // is exactly the shape `addCondAttrToTemplate`'s splice regex
1643
+ // (`html.replace(/^(<\w+)(\s|>)/, ...)`) can stamp `bf-c` onto. A root
1644
+ // this gate doesn't recognize (a self-closing tag's own `/`, a
1645
+ // hyphenated custom-element tag) falls through to `false`
1646
+ // (comment-wrap) unchanged from before — widening this gate without
1647
+ // also teaching the splice regex the same shapes would silently drop
1648
+ // BOTH the `bf-c` stamp and the comment-wrap fallback for those roots.
1649
+ const match = trimmed.match(/^<(\w+)[\s>]/)
1628
1650
  if (!match) return false
1629
- const tag = match[1]
1630
- // Self-closing tags like <br/>, <input/>
1631
- if (/^<\w+[^>]*\/>$/.test(html.trim())) return true
1632
- // Check that the last closing tag matches and nothing follows it
1633
- const closingPattern = new RegExp(`</${tag}>\\s*$`)
1634
- return closingPattern.test(html.trim())
1651
+ // Self-closing tags like <br/>, <input/> with nothing else.
1652
+ if (/^<\w+[^>]*\/>$/.test(trimmed)) return true
1653
+
1654
+ // Walk top-level tags tracking nesting depth — see the docstring above
1655
+ // for why (#2960). The comment alternative must come first so it wins at a `<!--`
1656
+ // position — without it, a BarefootJS marker comment like
1657
+ // `<!--bf:s1-->`/`<!--/-->` (a reactive text slot nested inside a
1658
+ // genuine single root) matches the generic tag alternative too (its
1659
+ // body has no `\s`, `/` or `>` before the closing `-->`) and gets
1660
+ // miscounted as an opening tag, throwing off the depth count for
1661
+ // perfectly ordinary single-root branches.
1662
+ const tagPattern = /<!--[\s\S]*?-->|<\/?[^\s/>]+[^>]*>/g
1663
+ let depth = 0
1664
+ let tagMatch: RegExpExecArray | null
1665
+ while ((tagMatch = tagPattern.exec(trimmed))) {
1666
+ const raw = tagMatch[0]
1667
+ if (raw.startsWith('<!--')) continue // HTML comment, not a tag: depth unchanged
1668
+ if (raw.endsWith('/>')) {
1669
+ // Self-closing/void tag (e.g. `<input .../>`). The whole-string
1670
+ // check above only catches a self-closing tag with NOTHING else in
1671
+ // the string — a self-closing root FOLLOWED by more content (e.g.
1672
+ // `<input .../><label>...</label>`, a genuine two-root branch) still
1673
+ // reaches here with the guard above already satisfied (it only
1674
+ // looks at the tag name and the very next character, not whether
1675
+ // the tag turns out to self-close). At depth 0 this tag completes a
1676
+ // whole top-level unit by itself, so treat it exactly like any
1677
+ // other tag's closing point: single root only if nothing follows.
1678
+ // Nested inside another element (depth > 0) it's just an ordinary
1679
+ // child and doesn't affect depth.
1680
+ if (depth === 0) return tagPattern.lastIndex === trimmed.length
1681
+ continue
1682
+ }
1683
+ depth += raw.startsWith('</') ? -1 : 1
1684
+ if (depth === 0) {
1685
+ // Back to depth 0: the root element's own closing tag. Single root
1686
+ // only if nothing else follows it.
1687
+ return tagPattern.lastIndex === trimmed.length
1688
+ }
1689
+ }
1690
+ return false
1635
1691
  }
1636
1692
 
1637
1693
  /**
@@ -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. */