@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
package/src/analyzer.ts CHANGED
@@ -25,7 +25,7 @@ import {
25
25
  isArrowComponentFunction,
26
26
  collectReactiveGetterNames,
27
27
  } from './analyzer-context.ts'
28
- import { createError, createWarning, ErrorCodes, type ErrorCode } from './errors.ts'
28
+ import { createError, ErrorCodes, type ErrorCode } from './errors.ts'
29
29
  import { baseTypeName } from './rich-type-evidence.ts'
30
30
  import { CATALOGUED_RICH_TYPE_NAMES } from './date-lowering.ts'
31
31
  import path from 'node:path'
@@ -3130,6 +3130,30 @@ function getSystemConstructKind(node: ts.Node): 'createContext' | 'weakMap' | un
3130
3130
  return undefined
3131
3131
  }
3132
3132
 
3133
+ /**
3134
+ * The default-value-shaped fields a binding element's own `initializer`
3135
+ * contributes to a `ParamInfo` — `defaultValue`'s source text, `parsed`'s
3136
+ * structured mirror (from the initializer's OWN AST node, no re-parse),
3137
+ * and `defaultContainsArrow`. Shared by the parameter-destructured path
3138
+ * (`extractProps`'s Pattern 1, below) and the BODY-destructure-from-props
3139
+ * path (`collectConstant`'s object-binding-pattern branch, #2943) so "what
3140
+ * does this default look like structurally" has one implementation, not
3141
+ * two independently-drifting ones.
3142
+ */
3143
+ function bindingElementDefaultFields(
3144
+ initializer: ts.Expression | undefined,
3145
+ ctx: AnalyzerContext,
3146
+ ): Pick<ParamInfo, 'defaultValue' | 'parsed' | 'defaultContainsArrow'> {
3147
+ const defaultValue = initializer ? ctx.getJS(initializer) : undefined
3148
+ const defaultContainsArrow = initializer ? nodeContainsArrow(initializer) : false
3149
+ const parsedDefault = initializer ? tsNodeToParsedExpr(initializer) : undefined
3150
+ return {
3151
+ defaultValue,
3152
+ ...(parsedDefault && parsedDefault.kind !== 'unsupported' && { parsed: parsedDefault }),
3153
+ defaultContainsArrow: defaultContainsArrow || undefined,
3154
+ }
3155
+ }
3156
+
3133
3157
  function collectConstant(
3134
3158
  node: ts.VariableDeclaration,
3135
3159
  ctx: AnalyzerContext,
@@ -3191,6 +3215,55 @@ function collectConstant(
3191
3215
  // _isModule === false; binding lives in init scope.
3192
3216
  origin: { phase: 'hydrate', scope: 'init', effect: 'pure' },
3193
3217
  })
3218
+
3219
+ // #2943: a BODY destructure's default (`const { label = 'none' } =
3220
+ // props`) has no other way to reach `ParamInfo.defaultValue` —
3221
+ // `extractPropsFromTypeMembers` builds `propsParams` purely from the
3222
+ // TYPE annotation, which has no notion of a body-level default. Every
3223
+ // downstream consumer that reads `ParamInfo.defaultValue`/`.optional`
3224
+ // (each adapter's "does this attribute need a presence guard"
3225
+ // classification, `extractSsrDefaults`'s SSR-stash seed, the
3226
+ // CSR-fresh-mount `template:` lambda) needs the default visible here,
3227
+ // on the SAME shared `ParamInfo` the parameter-destructured form
3228
+ // already populates via `bindingElementDefaultFields` above — not on
3229
+ // a second, parallel structure only the CSR lambda used to consult.
3230
+ //
3231
+ // A `let` binding or one `markMutatedConstants` later flags as
3232
+ // mutated is still a perfectly valid default AT its declaration —
3233
+ // this is a static, compile-time fact about the source, not a
3234
+ // liveness question, so (unlike `resolveBodyPropAliases`'s
3235
+ // `requireLiveRewriteSafe` gate) nothing here excludes them.
3236
+ if (el.initializer) {
3237
+ const defaultFields = bindingElementDefaultFields(el.initializer, ctx)
3238
+ const existing = ctx.propsParams.find(p => !p.isRest && p.sourceName === undefined && p.name === sourceKey)
3239
+ if (localName === sourceKey) {
3240
+ // Unrenamed: overlay onto the type-member entry `sourceKey`
3241
+ // already has (or synthesize one for an untyped `props` param,
3242
+ // matching the parameter-destructured form's own `unknown`
3243
+ // fallback for an unannotated `{ x = 1 }`). Never clobber a
3244
+ // default some earlier binding element already established.
3245
+ if (existing) {
3246
+ if (existing.defaultValue === undefined) Object.assign(existing, { optional: true, ...defaultFields })
3247
+ } else {
3248
+ ctx.propsParams.push({ name: localName, type: { kind: 'unknown', raw: 'unknown' }, optional: true, ...defaultFields })
3249
+ }
3250
+ } else if (!ctx.propsParams.some(p => p.name === localName)) {
3251
+ // Renamed (`const { label: text = 'none' } = props`): ADD a
3252
+ // second entry rather than replacing `sourceKey`'s — a bare
3253
+ // `props.label` read elsewhere in the same component is still a
3254
+ // real, separately-classified binding (no default, needs its own
3255
+ // presence guard / stash entry), and `text` needs `sourceName` so
3256
+ // every `sourceName ?? name` consumer resolves the caller-facing
3257
+ // key correctly.
3258
+ ctx.propsParams.push({
3259
+ name: localName,
3260
+ type: existing?.type ?? { kind: 'unknown', raw: 'unknown' },
3261
+ optional: true,
3262
+ sourceName: sourceKey,
3263
+ ...defaultFields,
3264
+ })
3265
+ }
3266
+ }
3194
3267
  }
3195
3268
  return
3196
3269
  }
@@ -3431,57 +3504,6 @@ function collectConstant(
3431
3504
  })
3432
3505
  }
3433
3506
 
3434
- // =============================================================================
3435
- // Ignore Directive Detection
3436
- // =============================================================================
3437
-
3438
- /**
3439
- * Check if a node has an ignore directive comment for the specified rule.
3440
- * Supports: // @bf-ignore rule-id
3441
- *
3442
- * For arrow function components, also checks the parent VariableStatement.
3443
- */
3444
- function hasIgnoreDirective(
3445
- node: ts.Node,
3446
- sourceFile: ts.SourceFile,
3447
- ruleId: string
3448
- ): boolean {
3449
- const checkComments = (targetNode: ts.Node): boolean => {
3450
- const fullStart = targetNode.getFullStart()
3451
- const leadingComments = ts.getLeadingCommentRanges(
3452
- sourceFile.getFullText(),
3453
- fullStart
3454
- )
3455
- if (!leadingComments) return false
3456
-
3457
- for (const range of leadingComments) {
3458
- const text = sourceFile.getFullText().slice(range.pos, range.end)
3459
- if (text.includes(`@bf-ignore ${ruleId}`)) {
3460
- return true
3461
- }
3462
- }
3463
- return false
3464
- }
3465
-
3466
- // Check the node itself
3467
- if (checkComments(node)) return true
3468
-
3469
- // For arrow functions, check the parent VariableStatement
3470
- // AST structure: VariableStatement > VariableDeclarationList > VariableDeclaration > ArrowFunction
3471
- if (ts.isArrowFunction(node)) {
3472
- let current: ts.Node | undefined = node.parent
3473
- while (current) {
3474
- if (ts.isVariableStatement(current)) {
3475
- if (checkComments(current)) return true
3476
- break
3477
- }
3478
- current = current.parent
3479
- }
3480
- }
3481
-
3482
- return false
3483
- }
3484
-
3485
3507
  // =============================================================================
3486
3508
  // Props Extraction
3487
3509
  // =============================================================================
@@ -3489,13 +3511,7 @@ function hasIgnoreDirective(
3489
3511
  function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): void {
3490
3512
  // Pattern 1: Destructured props - { prop1, prop2 }
3491
3513
  if (ts.isObjectBindingPattern(param.name)) {
3492
- // Record destructuring info for deferred BF043 emission (stateful components only)
3493
- const componentNode = ctx.componentNode
3494
- const ignored = !!(componentNode && hasIgnoreDirective(componentNode, ctx.sourceFile, 'props-destructuring'))
3495
- ctx.propsDestructuring = {
3496
- loc: getSourceLocation(param, ctx.sourceFile, ctx.filePath),
3497
- hasIgnoreDirective: ignored,
3498
- }
3514
+ ctx.propsDestructuring = { loc: getSourceLocation(param, ctx.sourceFile, ctx.filePath) }
3499
3515
 
3500
3516
  // Resolve each destructured binding's declared type from the param's type
3501
3517
  // annotation, so `{ value }: Props` keeps the same per-prop TypeInfo as the
@@ -3506,7 +3522,6 @@ function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): voi
3506
3522
  for (const element of param.name.elements) {
3507
3523
  if (ts.isBindingElement(element) && ts.isIdentifier(element.name)) {
3508
3524
  const localName = element.name.text
3509
- const defaultValue = element.initializer ? ctx.getJS(element.initializer) : undefined
3510
3525
 
3511
3526
  // Handle rest props: { ...props }
3512
3527
  if (element.dotDotDotToken) {
@@ -3523,22 +3538,13 @@ function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): voi
3523
3538
  const member = memberTypes?.get(sourcePropName)
3524
3539
  const resolvedType: TypeInfo = member?.type ?? { kind: 'unknown', raw: 'unknown' }
3525
3540
 
3526
- const defaultContainsArrow = element.initializer ? nodeContainsArrow(element.initializer) : false
3527
- // Structured mirror of `defaultValue`, from the binding element's OWN
3528
- // `initializer` node — `tsNodeToParsedExpr` converts the already-parsed
3529
- // AST directly, no re-parse of the `defaultValue` text (same convention
3530
- // as `SignalInfo.parsed`). An unsupported shape leaves `parsed` unset;
3531
- // consumers fall back to `defaultValue` text.
3532
- const parsedDefault = element.initializer ? tsNodeToParsedExpr(element.initializer) : undefined
3533
3541
  ctx.propsParams.push({
3534
3542
  name: localName,
3535
3543
  type: resolvedType,
3536
3544
  // The type's `?` and a destructure default (`{ x = 1 }`) both mean
3537
3545
  // the caller may omit the prop.
3538
3546
  optional: !!member?.optional || !!element.initializer,
3539
- defaultValue,
3540
- ...(parsedDefault && parsedDefault.kind !== 'unsupported' && { parsed: parsedDefault }),
3541
- defaultContainsArrow: defaultContainsArrow || undefined,
3547
+ ...bindingElementDefaultFields(element.initializer, ctx),
3542
3548
  // Only aliased bindings carry the source key — see ParamInfo.sourceName.
3543
3549
  ...(sourcePropName !== localName && { sourceName: sourcePropName }),
3544
3550
  })
@@ -3965,20 +3971,6 @@ function extractDependencies(code: string, ctx: AnalyzerContext): string[] {
3965
3971
  // =============================================================================
3966
3972
 
3967
3973
  function validateContext(ctx: AnalyzerContext): void {
3968
- // BF043: Emit props destructuring warning only for stateful components.
3969
- // Stateless components can safely destructure props since values are static.
3970
- const isStateful = ctx.signals.length > 0 || ctx.memos.length > 0 ||
3971
- ctx.effects.length > 0 || ctx.onMounts.length > 0
3972
- if (ctx.propsDestructuring && isStateful && !ctx.propsDestructuring.hasIgnoreDirective) {
3973
- ctx.errors.push(
3974
- createWarning(ErrorCodes.PROPS_DESTRUCTURING, ctx.propsDestructuring.loc, {
3975
- suggestion: {
3976
- message: 'Use props object directly: function Component(props: Props) { ... props.checked ... }',
3977
- },
3978
- })
3979
- )
3980
- }
3981
-
3982
3974
  // Check for 'use client' directive if any browser-only API is used.
3983
3975
  // Browser-only APIs include signals AND context/portal runtime hooks:
3984
3976
  // their implementations live in `@barefootjs/client/runtime` and require
package/src/errors.ts CHANGED
@@ -51,8 +51,9 @@ export const ErrorCodes = {
51
51
  // to resolve the identifier at return position too.
52
52
  RETURN_VALUE_NOT_JSX: 'BF027',
53
53
 
54
- // Component errors (BF043-BF049)
55
- PROPS_DESTRUCTURING: 'BF043',
54
+ // Component errors (BF043-BF049). BF043 is retired (it warned that props
55
+ // destructuring broke reactivity, which it no longer does) and is the next
56
+ // free slot.
56
57
  SIGNAL_GETTER_NOT_CALLED: 'BF044',
57
58
  JSX_IN_LOCAL_FUNCTION: 'BF045',
58
59
  COMPONENT_REQUIRED_PROP_MISSING: 'BF046',
@@ -181,8 +182,6 @@ const errorMessages: Record<ErrorCode, string> = {
181
182
  [ErrorCodes.RETURN_VALUE_NOT_JSX]:
182
183
  "Component's return value is not recognized as JSX — return the JSX expression directly instead of binding it to a local variable first.",
183
184
 
184
- [ErrorCodes.PROPS_DESTRUCTURING]:
185
- 'Props destructuring in function parameters breaks reactivity. Use props object directly.',
186
185
  [ErrorCodes.SIGNAL_GETTER_NOT_CALLED]:
187
186
  'Signal/memo getter passed without calling it. Use getter() to read the value.',
188
187
  [ErrorCodes.JSX_IN_LOCAL_FUNCTION]:
@@ -382,10 +381,10 @@ export function formatError(
382
381
  options?: { projectDir?: string },
383
382
  ): string {
384
383
  // Lowercase severity matches the prose convention in
385
- // `docs/core/advanced/error-codes.md` (`error[BF001]:`,
386
- // `warning[BF043]:`) — that doc IS the rendering contract referenced
387
- // by `bf guide advanced/error-codes`, so keep the wire format aligned
388
- // with the reference rather than the function's old uppercase shape.
384
+ // `docs/core/advanced/error-codes.md` (`error[BF001]:`) — that doc IS the
385
+ // rendering contract referenced by `bf guide advanced/error-codes`, so
386
+ // keep the wire format aligned with the reference rather than the
387
+ // function's old uppercase shape.
389
388
  const severityLabel = error.severity
390
389
  const lines: string[] = []
391
390
 
@@ -67,3 +67,22 @@ export function propHasPropertyAccess(u: PropUsage | undefined): boolean {
67
67
  if (!u) return false
68
68
  return u.accessKinds.has('property') || u.accessKinds.has('index')
69
69
  }
70
+
71
+ /**
72
+ * Which of `propNames` guard a conditional branch. A prop in this set must
73
+ * NOT get a `{}` fallback even when it has property access — `{}` is truthy,
74
+ * so the branch would always render when the caller omits the prop.
75
+ */
76
+ export function computePropsUsedAsConditions(
77
+ ctx: Pick<ClientJsContext, 'conditionalElements' | 'clientOnlyConditionals'>,
78
+ propNames: ReadonlySet<string>,
79
+ ): Set<string> {
80
+ const result = new Set<string>()
81
+ for (const cond of ctx.conditionalElements) {
82
+ if (propNames.has(cond.condition)) result.add(cond.condition)
83
+ }
84
+ for (const cond of ctx.clientOnlyConditionals) {
85
+ if (propNames.has(cond.condition)) result.add(cond.condition)
86
+ }
87
+ return result
88
+ }
@@ -17,16 +17,19 @@ import type {
17
17
  EventDelegationPlan,
18
18
  ItemLookup,
19
19
  } from './types.ts'
20
+ import type { ContainerOwnHandler } from './event-collision.ts'
20
21
 
21
22
  export function buildDynamicLoopDelegationPlan(
22
23
  elem: TopLevelLoop,
23
24
  profileComponentName?: string,
25
+ ownHandlers?: Map<string, ContainerOwnHandler>,
24
26
  ): EventDelegationPlan {
25
27
  return {
26
28
  kind: 'event-delegation',
27
29
  containerVar: `_${varSlotId(elem.slotId)}`,
28
30
  events: elem.bindings.events,
29
31
  profileComponentName,
32
+ ownHandlers,
30
33
  itemLookup: buildKeyedOrIndexLookup({
31
34
  // Chain `.filter()` / `.toSorted()` so the index-based lookup walks
32
35
  // the same array shape mapArray reconciled into the DOM (#1434).
@@ -93,12 +96,14 @@ export function buildBranchLoopDelegationPlan(
93
96
  export function buildStaticArrayDelegationPlan(
94
97
  elem: TopLevelLoop,
95
98
  profileComponentName?: string,
99
+ ownHandlers?: Map<string, ContainerOwnHandler>,
96
100
  ): EventDelegationPlan {
97
101
  return {
98
102
  kind: 'event-delegation',
99
103
  containerVar: `_${varSlotId(elem.slotId)}`,
100
104
  events: elem.bindings.events,
101
105
  profileComponentName,
106
+ ownHandlers,
102
107
  itemLookup: {
103
108
  kind: 'static-index',
104
109
  // Static arrays render through the same `.filter()`/`.toSorted()`
@@ -62,29 +62,45 @@ export interface BuildLoopPlanOptions {
62
62
  lazyScope?: LazyRowScopeInfo
63
63
  }
64
64
 
65
+ /** Which `LoopPlan` variant `buildLoopPlan` would build for a given loop. */
66
+ export type LoopVariantKind = 'plain' | 'static' | 'composite' | 'component'
67
+
65
68
  /**
66
- * The single public builder. Selects the variant via the decision tree
67
- * described above and returns the discriminated `LoopPlan`.
69
+ * Classify which variant `buildLoopPlan` would build for `elem`, without
70
+ * building it. Mirrors the decision tree below exactly — pulled out so a
71
+ * caller that only needs the classification (e.g. the event-delegation
72
+ * eligibility precompute, #2930) doesn't have to duplicate these predicates
73
+ * or pay for building the full `LoopPlan`.
68
74
  */
69
- export function buildLoopPlan(elem: TopLevelLoop, opts: BuildLoopPlanOptions): LoopPlan {
75
+ export function classifyLoopKind(elem: TopLevelLoop): LoopVariantKind {
70
76
  // Whole-item conditional bodies (#1665) render 0-or-1 element per item, so
71
77
  // they need anchored `mapArrayAnchored` emission regardless of whether the
72
78
  // array is static or dynamic. Routing both through the plain (anchored)
73
79
  // path keeps `const arr` and `signal()` behaviour identical — a static
74
80
  // array's per-item conditional still toggles reactively instead of freezing
75
81
  // in the SSR-time `forEach` (which has no conditional handling at all).
76
- if (elem.bodyIsItemConditional) {
77
- return buildPlainLoopPlan(elem, opts.profileComponentName, opts.lazyScope)
78
- }
79
- if (elem.isStaticArray) {
80
- return buildStaticLoopPlan(elem, opts.unsafeLocalNames, opts.profileComponentName)
81
- }
82
+ if (elem.bodyIsItemConditional) return 'plain'
83
+ if (elem.isStaticArray) return 'static'
82
84
  const hasInnerStructure = (elem.nestedComponents?.length ?? 0) > 0
83
85
  || (elem.innerLoops?.length ?? 0) > 0
84
- if (elem.useElementReconciliation && hasInnerStructure) {
86
+ if (elem.useElementReconciliation && hasInnerStructure) return 'composite'
87
+ if (elem.childComponent) return 'component'
88
+ return 'plain'
89
+ }
90
+
91
+ /**
92
+ * The single public builder. Dispatches via `classifyLoopKind` and returns
93
+ * the discriminated `LoopPlan`.
94
+ */
95
+ export function buildLoopPlan(elem: TopLevelLoop, opts: BuildLoopPlanOptions): LoopPlan {
96
+ const kind = classifyLoopKind(elem)
97
+ if (kind === 'static') {
98
+ return buildStaticLoopPlan(elem, opts.unsafeLocalNames, opts.profileComponentName)
99
+ }
100
+ if (kind === 'composite') {
85
101
  return buildTopLevelCompositePlan(elem, opts.profileComponentName)
86
102
  }
87
- if (elem.childComponent) {
103
+ if (kind === 'component') {
88
104
  return buildComponentLoopPlan(elem, opts.profileComponentName)
89
105
  }
90
106
  return buildPlainLoopPlan(elem, opts.profileComponentName, opts.lazyScope)
@@ -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 {