@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
@@ -7,20 +7,30 @@
7
7
  *
8
8
  * `__scope` is the synthetic root slot id used when the component's
9
9
  * root element carries the listener (no `bf=` slot).
10
+ *
11
+ * A slot that is ALSO a `.map()` loop's container, with its own handler for
12
+ * the same DOM event a loop delegates, is skipped here too (#2930):
13
+ * `loopDelegationIndex` says so, and `control-flow.ts`'s `emitLoopUpdates`
14
+ * folds that handler into the delegated listener instead — emitting it here
15
+ * too would double-wire it back onto a separate `addEventListener` call,
16
+ * which is exactly the bug this split avoids.
10
17
  */
11
18
 
12
19
  import type { ClientJsContext } from '../types.ts'
13
20
  import { toDomEventName, varSlotId, wrapHandlerInBlock, wrapHandlerForTurn } from '../utils.ts'
21
+ import type { LoopDelegationIndex } from '../control-flow/plan/loop-delegation-index.ts'
14
22
 
15
23
  export function emitEventHandlers(
16
24
  lines: string[],
17
25
  ctx: ClientJsContext,
18
26
  conditionalSlotIds: Set<string>,
27
+ loopDelegationIndex: LoopDelegationIndex,
19
28
  ): void {
20
29
  for (const elem of ctx.interactiveElements) {
21
30
  if (conditionalSlotIds.has(elem.slotId)) continue
22
31
  for (const event of elem.events) {
23
32
  const eventName = toDomEventName(event.name)
33
+ if (loopDelegationIndex.isDelegated(elem.slotId, eventName)) continue
24
34
  // Profile mode (#1690, SR3): bracket the handler with turn markers so a
25
35
  // profiling run attributes the reactive work it triggers to this turn.
26
36
  const wrappedHandler = ctx.profile
@@ -6,6 +6,11 @@
6
6
  * function / constant or destructured prop), emit
7
7
  * `const handlerName = _p.handlerName`. Subsequent emission can call
8
8
  * `handlerName(...)` without writing the prop accessor inline.
9
+ *
10
+ * Only for props-object mode, where a bare `handlerName` would otherwise be
11
+ * a `ReferenceError`. In destructured mode `rewriteDestructuredPropReads`
12
+ * already turns every handler-name read into a live `_p.handlerName`, so the
13
+ * alias would only be emitted to be left unused.
9
14
  */
10
15
 
11
16
  import type { ClientJsContext } from '../types.ts'
@@ -17,6 +22,7 @@ export function emitPropsEventHandlers(
17
22
  usedFunctions: Set<string>,
18
23
  neededProps: Set<string>,
19
24
  ): void {
25
+ if (ctx.propsObjectName === null) return
20
26
  const localNames = new Set<string>([
21
27
  ...ctx.localFunctions.map(f => f.name),
22
28
  ...ctx.localConstants.map(c => c.name),
@@ -1,67 +1,48 @@
1
1
  /**
2
- * `props-extraction` phase — emit `const propName = _p.propName ?? <default>`
3
- * declarations at the top of the init body.
2
+ * `props-extraction` phase — emit the one surviving one-time prop
3
+ * extraction, `const children = _p.children [?? <default>]`.
4
4
  *
5
- * The default value depends on usage:
6
- * - prop has explicit default → use it (wrap arrow defaults
7
- * in parens for syntax safety)
8
- * - prop is consumed as a loop array → `?? []`
9
- * - prop has property/index access → `?? {}` (skipped when the
10
- * prop is a conditional guard
11
- * so falsy values stay falsy)
12
- * - otherwise → no default
5
+ * `children` must stay a ONE-TIME read: a prop's slot-children value is a
6
+ * getter that INSTANTIATES child components when read (see
7
+ * `prune-unused-prop-extractions.ts`), so reading it live at every
8
+ * `{children}` reference would re-mount the children each time. Every
9
+ * other destructured prop is rewritten to a live read instead, by
10
+ * `rewriteDestructuredPropReads` (`generate-init.ts`).
13
11
  *
14
- * Skipped entirely when the component uses an opaque props object name
15
- * (`propsObjectName != null`) — in that case downstream code reads
16
- * `_p.X` directly via the late-stage rename.
12
+ * The line is composed from `propReadBase`/`propReadFallback` rather than
13
+ * `livePropReadExpr` so it stays unparenthesized — that exact
14
+ * `const X = _p.X [?? d]` shape is what `pruneUnusedPropExtractions`'s AST
15
+ * matcher recognizes when the init body never reads `children`.
16
+ *
17
+ * Skipped entirely for an opaque props object (`propsObjectName != null`):
18
+ * downstream code there reads `_p.X` directly via the late-stage rename.
17
19
  */
18
20
 
19
21
  import type { PropUsage } from '../../types.ts'
20
- import { propHasPropertyAccess } from '../compute-prop-usage.ts'
22
+ import { computePropsUsedAsConditions } from '../compute-prop-usage.ts'
23
+ import { propReadBase, propReadFallback } from '../../props-binding.ts'
21
24
  import type { ClientJsContext } from '../types.ts'
22
25
  import { PROPS_PARAM } from '../utils.ts'
23
26
 
27
+ const CHILDREN = 'children'
28
+
24
29
  export function emitPropsExtraction(
25
30
  lines: string[],
26
31
  ctx: ClientJsContext,
27
32
  neededProps: Set<string>,
28
33
  propUsage: Map<string, PropUsage>,
29
34
  ): void {
30
- if (neededProps.size === 0 || ctx.propsObjectName) return
35
+ if (ctx.propsObjectName) return
36
+ if (!neededProps.has(CHILDREN)) return
31
37
 
32
- // Props that guard a conditional branch must remain falsy when undefined,
33
- // so `{}` (truthy) is the wrong default for them — track and exclude.
34
- const propsUsedAsConditions = new Set<string>()
35
- for (const cond of ctx.conditionalElements) {
36
- if (neededProps.has(cond.condition)) propsUsedAsConditions.add(cond.condition)
37
- }
38
- for (const cond of ctx.clientOnlyConditionals) {
39
- if (neededProps.has(cond.condition)) propsUsedAsConditions.add(cond.condition)
38
+ const prop = ctx.propsParams.find(p => p.name === CHILDREN)
39
+ if (!prop) {
40
+ lines.push(` const ${CHILDREN} = ${PROPS_PARAM}.${CHILDREN}`, '')
41
+ return
40
42
  }
41
43
 
42
- for (const propName of neededProps) {
43
- const prop = ctx.propsParams.find(p => p.name === propName)
44
- // `_p` is always keyed by the caller-facing name (#2524 CSR half); the
45
- // local binding on the left of `const` stays `propName`.
46
- const callerKey = prop?.sourceName ?? propName
47
- const usage = propUsage.get(propName)
48
- const defaultVal = prop?.defaultValue
49
- if (defaultVal) {
50
- // `props.onInput ?? () => {}` is a syntax error — `??` binds tighter
51
- // than the arrow head. Wrap arrow defaults in parens.
52
- const wrappedDefault = prop?.defaultContainsArrow ? `(${defaultVal})` : defaultVal
53
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey} ?? ${wrappedDefault}`)
54
- } else if (usage?.usedAsLoopArray) {
55
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey} ?? []`)
56
- } else if (propHasPropertyAccess(usage) && !propsUsedAsConditions.has(propName)) {
57
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey} ?? {}`)
58
- } else {
59
- // No synthesized default for a defaultless optional (`{ size }:
60
- // { size?: number }`): the JS binding is `undefined` when absent, and
61
- // a zero default would diverge from SSR (`size ?? 1` seeds 1
62
- // server-side; a `_p.size ?? 0` extraction would hydrate to 0).
63
- lines.push(` const ${propName} = ${PROPS_PARAM}.${callerKey}`)
64
- }
65
- }
66
- lines.push('')
44
+ const usedAsCondition = computePropsUsedAsConditions(ctx, neededProps).has(CHILDREN)
45
+ const fallback = propReadFallback(prop, propUsage.get(CHILDREN), usedAsCondition)
46
+ const read = propReadBase(prop) + (fallback === null ? '' : ` ?? ${fallback}`)
47
+ lines.push(` const ${CHILDREN} = ${read}`, '')
67
48
  }
@@ -17,6 +17,7 @@ import type { ComponentIR, PropUsage, ReferencesGraph } from '../types.ts'
17
17
  import type { ClientJsContext } from './types.ts'
18
18
  import type { LocalClassification } from './init-declarations.ts'
19
19
  import { collectConditionalSlotIds } from './phases/conditional-slot-ids.ts'
20
+ import { buildLoopDelegationIndex, type LoopDelegationIndex } from './control-flow/plan/loop-delegation-index.ts'
20
21
  import { emitEffectsAndOnMounts } from './phases/effects-and-on-mounts.ts'
21
22
  import { emitEventHandlers } from './phases/event-handlers.ts'
22
23
  import { emitInitStatements } from './phases/init-statements.ts'
@@ -51,6 +52,16 @@ export interface PhaseCtx {
51
52
  /** Slots that live inside a conditional branch (handled via `insert()`).
52
53
  * Cached so `event-handlers` and `ref-callbacks` don't recompute. */
53
54
  conditionalSlotIds: Set<string>
55
+ /**
56
+ * Which (container slot, DOM event) pairs a top-level `.map()` loop will
57
+ * delegate, and which loop is last among those sharing a pair (#2930).
58
+ * Computed once, ahead of both `event-handlers` (which must suppress a
59
+ * container's own listener for a delegated pair) and `loop-updates`
60
+ * (which folds that handler into the delegated listener instead) — those
61
+ * two phases run in that order, so this can't be computed by either one
62
+ * lazily on first use.
63
+ */
64
+ loopDelegationIndex: LoopDelegationIndex
54
65
  /** Local names that resolve to component-scope expressions and therefore
55
66
  * become `[]` / `undefined` when referenced from the CSR template (the
56
67
  * same set the registration emitter feeds `generateCsrTemplate`).
@@ -60,10 +71,13 @@ export interface PhaseCtx {
60
71
  }
61
72
 
62
73
  /** Build the read-only carrier that every phase consumes. */
63
- export function buildPhaseCtx(args: Omit<PhaseCtx, 'conditionalSlotIds'>): PhaseCtx {
74
+ export function buildPhaseCtx(
75
+ args: Omit<PhaseCtx, 'conditionalSlotIds' | 'loopDelegationIndex'>,
76
+ ): PhaseCtx {
64
77
  return {
65
78
  ...args,
66
79
  conditionalSlotIds: collectConditionalSlotIds(args.ctx),
80
+ loopDelegationIndex: buildLoopDelegationIndex(args.ctx.loopElements),
67
81
  }
68
82
  }
69
83
 
@@ -222,7 +236,7 @@ export const PHASES: readonly EmitPhase[] = [
222
236
  {
223
237
  id: 'event-handlers',
224
238
  dependsOn: ['rest-attr-applications'],
225
- run: (lines, p) => emitEventHandlers(lines, p.ctx, p.conditionalSlotIds),
239
+ run: (lines, p) => emitEventHandlers(lines, p.ctx, p.conditionalSlotIds, p.loopDelegationIndex),
226
240
  },
227
241
  {
228
242
  id: 'reactive-prop-bindings',
@@ -256,7 +270,7 @@ export const PHASES: readonly EmitPhase[] = [
256
270
  // contract is enforceable at registry-validation time.
257
271
  id: 'loop-updates',
258
272
  dependsOn: ['provider-and-child-inits'],
259
- run: (lines, p) => emitLoopUpdates(lines, p.ctx, p.unsafeLocalNames),
273
+ run: (lines, p) => emitLoopUpdates(lines, p.ctx, p.unsafeLocalNames, p.conditionalSlotIds, p.loopDelegationIndex),
260
274
  },
261
275
  {
262
276
  id: 'static-array-child-inits',
@@ -13,6 +13,7 @@ import type { Declaration } from '../declaration-sort.ts'
13
13
  import type { ClientJsContext } from '../types.ts'
14
14
  import type { ParamInfo, SignalInfo } from '../../types.ts'
15
15
  import { inferDefaultValue, PROPS_PARAM } from '../utils.ts'
16
+ import { livePropReadExpr } from '../../props-binding.ts'
16
17
  import { ENV_SIGNAL_CLIENT_FACTORY } from '../../adapters/env-signal.ts'
17
18
  import type {
18
19
  ControlledSignalEffectPlan,
@@ -182,11 +183,11 @@ function buildControlledSignalEffect(
182
183
  if (!signal.setter) return null // read-only — no sync needed
183
184
 
184
185
  const prop = lookups.propByName.get(controlled.propName)
185
- // `_p` is always keyed by the caller-facing name (#2524 CSR half).
186
- const callerKey = prop?.sourceName ?? controlled.propName
187
- const accessorExpr = prop?.defaultValue
188
- ? `(${PROPS_PARAM}.${callerKey} ?? ${prop.defaultValue})`
189
- : `${PROPS_PARAM}.${callerKey}`
186
+ // No `usage`/`usedAsCondition`: a controlled prop's sync effect reads it
187
+ // as a plain value, never as a loop array or a conditional guard.
188
+ const accessorExpr = prop
189
+ ? livePropReadExpr(prop, undefined, false)
190
+ : `${PROPS_PARAM}.${controlled.propName}`
190
191
 
191
192
  return { setter: signal.setter, accessorExpr }
192
193
  }
@@ -36,6 +36,35 @@ import ts from 'typescript'
36
36
  import { collectValueReferencedNames } from '../value-references.ts'
37
37
  import { PROPS_PARAM } from './utils.ts'
38
38
 
39
+ /**
40
+ * Does `init` read `<objectName>.<key>` or `<objectName>.<key> ?? <fallback>`?
41
+ * The one recognizer for "a prop read initializer", shared by
42
+ * `propExtractionName` below (which additionally requires the bound name to
43
+ * equal `key`, and always reads off `_p`), `rewriteBodyAliasReads`
44
+ * (`rewrite-destructured-props.ts`, which does not require the name match —
45
+ * a renamed alias's bound name differs from `key` by definition, but also
46
+ * always reads off `_p`), and `resolveBodyPropAliases` (`props-binding.ts`,
47
+ * which reads off the SOURCE-level props object name, e.g. `props` —
48
+ * `objectName` defaults to `_p` for the first two, post-rename, callers).
49
+ */
50
+ export function parsePropReadInitializer(
51
+ init: ts.Expression,
52
+ objectName: string = PROPS_PARAM,
53
+ ): { key: string; fallback: ts.Expression | null } | null {
54
+ let core: ts.Expression = init
55
+ let fallback: ts.Expression | null = null
56
+ if (
57
+ ts.isBinaryExpression(core) &&
58
+ core.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken
59
+ ) {
60
+ fallback = core.right
61
+ core = core.left
62
+ }
63
+ if (!ts.isPropertyAccessExpression(core)) return null
64
+ if (!ts.isIdentifier(core.expression) || core.expression.text !== objectName) return null
65
+ return { key: core.name.text, fallback }
66
+ }
67
+
39
68
  /** Is `stmt` a single-declarator `const X = _p.X…` prop extraction whose
40
69
  * initializer is `_p.X` or `_p.X ?? <default>`? Returns the bound name, or
41
70
  * null when the statement is anything else. */
@@ -46,16 +75,8 @@ function propExtractionName(stmt: ts.Statement): string | null {
46
75
  const decl = decls[0]!
47
76
  if (!ts.isIdentifier(decl.name) || !decl.initializer) return null
48
77
 
49
- let core: ts.Expression = decl.initializer
50
- if (
51
- ts.isBinaryExpression(core) &&
52
- core.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken
53
- ) {
54
- core = core.left
55
- }
56
- if (!ts.isPropertyAccessExpression(core)) return null
57
- if (!ts.isIdentifier(core.expression) || core.expression.text !== PROPS_PARAM) return null
58
- if (core.name.text !== decl.name.text) return null
78
+ const parsed = parsePropReadInitializer(decl.initializer)
79
+ if (parsed === null || parsed.key !== decl.name.text) return null
59
80
  return decl.name.text
60
81
  }
61
82
 
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Live-read rewrite for destructured props.
3
+ *
4
+ * A destructured name can appear bare in a dozen raw-captured text shapes
5
+ * (effect bodies, memo computations, signal initials, handler bodies,
6
+ * `mapArray` row bodies, conditional thunks, …), so rewriting it per
7
+ * emitter would mean N places to keep in sync; the single door is the
8
+ * joined init body, same precedent as `rewritePropsObjectRef`
9
+ * (`rewrite-props-object.ts`) one step earlier in the same pipeline.
10
+ *
11
+ * Two shapes reach this door, dispatched on `ctx.propsObjectName`:
12
+ *
13
+ * - PARAMETER destructuring (`function Child({ value })`,
14
+ * `propsObjectName === null`) — `rewriteParamDestructuredReads`, Move
15
+ * B's original mechanism (#2932).
16
+ * - a BODY destructure or bare-member alias off the whole props object
17
+ * (`function Child(props) { const { value } = props; ... }`,
18
+ * `propsObjectName` set) — `rewriteBodyAliasReads` (#2934). Move B left
19
+ * this branch a no-op: `rewritePropsObjectRef` (the pass immediately
20
+ * before this one) already turns `props.value` into `_p.value`
21
+ * wherever the SOURCE wrote it as a member access, but a body
22
+ * destructure's downstream USES are bare identifiers (`value`, not
23
+ * `props.value`), which that rename never touches — they stayed
24
+ * captured at the local's ONE declaration-time read forever.
25
+ */
26
+
27
+ import ts from 'typescript'
28
+ import type { PropUsage } from '../types.ts'
29
+ import { computePropsUsedAsConditions } from './compute-prop-usage.ts'
30
+ import { boundPropLocalNames, livePropReadExpr, resolveBodyPropAliases, type LivePropReadInfo } from '../props-binding.ts'
31
+ import { parsePropReadInitializer } from './prune-unused-prop-extractions.ts'
32
+ import { rewriteScopedValueRefs } from '../prop-rewrite.ts'
33
+ import { identifierPattern } from '../identifier-pattern.ts'
34
+ import { PROPS_PARAM } from './utils.ts'
35
+ import type { ClientJsContext } from './types.ts'
36
+
37
+ export function rewriteDestructuredPropReads(
38
+ code: string,
39
+ ctx: ClientJsContext,
40
+ propUsage: ReadonlyMap<string, PropUsage>,
41
+ ): string {
42
+ return ctx.propsObjectName === null
43
+ ? rewriteParamDestructuredReads(code, ctx, propUsage)
44
+ : rewriteBodyAliasReads(code, ctx)
45
+ }
46
+
47
+ /**
48
+ * Rewrite every bare value-position read of a PARAMETER-destructured prop in
49
+ * `code` (the joined `init*` body, already past `rewritePropsObjectRef`) to a
50
+ * live `_p.<key>` read.
51
+ *
52
+ * The walk is `rewriteScopedValueRefs` (`prop-rewrite.ts`), which carries a
53
+ * binding-scope stack, so `items.map((title) => title.a)` and a
54
+ * handler-local `const title = 'local'` keep their own binding even when
55
+ * `title` is also a prop name.
56
+ *
57
+ * Excluding `children`: reading `_p.children` live re-invokes a getter that
58
+ * instantiates child components (see `emitPropsExtraction`) — `children`
59
+ * must stay a captured-once read, by design.
60
+ *
61
+ * A null result can only mean `code` did not parse — never that a
62
+ * substitution broke it, since the walk parses the pristine input and every
63
+ * substituted string is a well-formed expression spliced where the walk
64
+ * already proved an identifier sat. The one shape that trips it is a
65
+ * tracked pre-existing hole (`map-body-no-silent-divergence.test.ts`'s
66
+ * `KNOWN_HOLES`): a `.map()` preamble leaking raw JSX, which is already a
67
+ * browser `SyntaxError` with or without this rewrite. Warning and passing
68
+ * the code through keeps that a tracked silent hole instead of promoting it
69
+ * to a compiler crash — same precedent as `pruneUnusedPropExtractions`.
70
+ */
71
+ function rewriteParamDestructuredReads(
72
+ code: string,
73
+ ctx: ClientJsContext,
74
+ propUsage: ReadonlyMap<string, PropUsage>,
75
+ ): string {
76
+ const names = new Set(boundPropLocalNames(ctx))
77
+ names.delete('children')
78
+ if (names.size === 0) return code
79
+
80
+ const propsUsedAsConditions = computePropsUsedAsConditions(ctx, names)
81
+ const propByName = new Map<string, LivePropReadInfo>()
82
+ for (const p of ctx.propsParams) propByName.set(p.name, p)
83
+
84
+ const replacementFor = (name: string): string => {
85
+ // `names` comes from `ctx.propsParams`, so the fallback is unreachable —
86
+ // kept over a non-null assertion.
87
+ const prop = propByName.get(name)
88
+ if (!prop) return `${PROPS_PARAM}.${name}`
89
+ return livePropReadExpr(prop, propUsage.get(name), propsUsedAsConditions.has(name))
90
+ }
91
+
92
+ const result = rewriteScopedValueRefs(code, names, replacementFor, { allowStatements: true })
93
+ if (result === null) {
94
+ console.warn(
95
+ `[barefootjs] rewriteDestructuredPropReads: the generated init body for ` +
96
+ `component "${ctx.componentName}" did not parse as JS/TSX (most likely a ` +
97
+ `pre-existing raw-JSX leak — see this function's docstring); skipping the ` +
98
+ `live-prop-read rewrite for it.`,
99
+ )
100
+ return code
101
+ }
102
+ return result
103
+ }
104
+
105
+ /**
106
+ * Rewrite every bare value-position read of a BODY-destructured (or
107
+ * bare-member-alias) prop local in `code` to a live `_p.<key>` read, for a
108
+ * bare-props-form component (`function Foo(props: Props)`).
109
+ *
110
+ * `resolveBodyPropAliases` can't distinguish `const { value } = props` from
111
+ * `const value = props.value` (the analyzer's IR is identical for both —
112
+ * see its docstring), so this rewrite treats them identically too. That's
113
+ * the correct call, not a shortcut: BOTH are pure single-prop passthroughs
114
+ * with no computation of their own, so both should read live, matching
115
+ * `props.value` used directly (which already reads live via
116
+ * `rewritePropsObjectRef`).
117
+ *
118
+ * A body alias's declaration is a REAL statement in `code` (unlike a
119
+ * parameter-destructured name, which never had one) — `const value =
120
+ * _p.value;`, physically sitting in the init body. Left in place, it would
121
+ * shadow every reference the rewrite is trying to make live (the walk sees
122
+ * it as a `Block`-scope declaration and treats every use as already
123
+ * correctly bound, exactly as it should for a genuine local). So this pass
124
+ * locates and DELETES each qualifying declaration BEFORE walking, rather
125
+ * than relying on `pruneUnusedPropExtractions` (which runs after this pass
126
+ * and only prunes an EXACT `const X = _p.X` shape — never a renamed alias's
127
+ * `const v = _p.value`, since its bound name doesn't match the read key).
128
+ *
129
+ * Only a declaration whose initializer is *exactly* `_p.<key>` [`?? <d>`] is
130
+ * touched — matched via `parsePropReadInitializer`, the same recognizer
131
+ * `pruneUnusedPropExtractions` uses for its narrower same-name case. A local
132
+ * this pass can't re-locate in that exact shape is left alone entirely
133
+ * (conservative false-keep: it stays captured, i.e. today's behavior, never
134
+ * a half-rewrite).
135
+ *
136
+ * Excluding `key === 'children'`: same hazard as the parameter form above,
137
+ * keyed by the CALLER-FACING name (`const { children: kids } = props`
138
+ * aliases `kids -> children` and must stay captured-once too).
139
+ */
140
+ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
141
+ const aliases = resolveBodyPropAliases(ctx.localConstants, ctx.propsObjectName)
142
+ for (const [local, alias] of aliases) {
143
+ if (alias.key === 'children') aliases.delete(local)
144
+ }
145
+ if (aliases.size === 0) return code
146
+ // Quick exit when none of the candidate local names appear at all.
147
+ if (![...aliases.keys()].some((name) => identifierPattern(name).test(code))) return code
148
+
149
+ const sourceFile = ts.createSourceFile('init-body.ts', code, ts.ScriptTarget.Latest, /*setParentNodes*/ true, ts.ScriptKind.TS)
150
+
151
+ const spans: Array<readonly [number, number]> = []
152
+ const located = new Map<string, { key: string; defaultValue?: string; defaultContainsArrow?: boolean }>()
153
+ for (const stmt of sourceFile.statements) {
154
+ if (!ts.isFunctionDeclaration(stmt) || !stmt.name?.text.startsWith('init') || !stmt.body) continue
155
+ for (const inner of stmt.body.statements) {
156
+ if (!ts.isVariableStatement(inner)) continue
157
+ if ((inner.declarationList.flags & ts.NodeFlags.Const) === 0) continue
158
+ const decls = inner.declarationList.declarations
159
+ if (decls.length !== 1) continue
160
+ const decl = decls[0]!
161
+ if (!ts.isIdentifier(decl.name) || !decl.initializer) continue
162
+ const alias = aliases.get(decl.name.text)
163
+ if (!alias) continue
164
+ const parsedInit = parsePropReadInitializer(decl.initializer)
165
+ if (parsedInit === null || parsedInit.key !== alias.key) continue
166
+ if ((parsedInit.fallback !== null) !== alias.hasDefault) continue
167
+ located.set(decl.name.text, {
168
+ key: alias.key,
169
+ defaultValue: parsedInit.fallback?.getText(sourceFile),
170
+ // `alias.defaultContainsArrow` mirrors `c.containsArrow`, computed
171
+ // against the ORIGINAL initializer before #2940's fix wrapped an
172
+ // arrow/function-expression default in its own protective parens
173
+ // (`coalesceDefaultText`, `analyzer.ts`). `parsedInit.fallback`
174
+ // here re-parses that ALREADY-wrapped `ConstantInfo.value` text, so
175
+ // when the fallback is itself a `ParenthesizedExpression` the wrap
176
+ // has already happened — `livePropReadExpr` below must not apply
177
+ // `coalesceDefaultText` a second time, or a live handler-scoped
178
+ // read doubles up (`(_p.fmt ?? (((v) => ...)))(1)` instead of the
179
+ // minimal `(_p.fmt ?? ((v) => ...))(1)`).
180
+ defaultContainsArrow: alias.defaultContainsArrow && !(
181
+ parsedInit.fallback && ts.isParenthesizedExpression(parsedInit.fallback)
182
+ ),
183
+ })
184
+ spans.push([inner.getFullStart(), inner.getEnd()])
185
+ }
186
+ }
187
+ if (located.size === 0) return code
188
+
189
+ // Delete the located declarations first (back-to-front) so the walk below
190
+ // never sees them as a shadowing local binding.
191
+ let stripped = code
192
+ for (const [start, end] of [...spans].sort((a, b) => b[0] - a[0])) {
193
+ stripped = stripped.slice(0, start) + stripped.slice(end)
194
+ }
195
+
196
+ const names = new Set(located.keys())
197
+ const replacementFor = (name: string): string => {
198
+ // `names` comes from `located`, so the fallback is unreachable — kept
199
+ // over a non-null assertion.
200
+ const info = located.get(name)
201
+ if (!info) return `${PROPS_PARAM}.${name}`
202
+ const prop: LivePropReadInfo = {
203
+ name,
204
+ sourceName: info.key,
205
+ defaultValue: info.defaultValue,
206
+ defaultContainsArrow: info.defaultContainsArrow,
207
+ }
208
+ return livePropReadExpr(prop, undefined, false)
209
+ }
210
+
211
+ const result = rewriteScopedValueRefs(stripped, names, replacementFor, { allowStatements: true })
212
+ if (result === null) {
213
+ console.warn(
214
+ `[barefootjs] rewriteDestructuredPropReads: the generated init body for ` +
215
+ `component "${ctx.componentName}" did not parse as JS/TSX after removing its ` +
216
+ `body-destructured prop-alias declarations; skipping the live-prop-read ` +
217
+ `rewrite for it.`,
218
+ )
219
+ return code
220
+ }
221
+ return result
222
+ }
@@ -278,6 +278,20 @@ export function toDomEventName(eventName: string): string {
278
278
  return jsxToDomEventMap[eventName] ?? eventName
279
279
  }
280
280
 
281
+ /**
282
+ * Non-bubbling events that require `addEventListener` with capture for
283
+ * delegation. Shared between the delegation stringifier and the own-handler
284
+ * collision check (#2930) so both agree on which events a container's own
285
+ * bubble-phase handler can never collide with in the first place — a
286
+ * container's own non-capturing `onFocus`, say, only fires when the
287
+ * container itself is the target, never for a descendant row.
288
+ */
289
+ export const NON_BUBBLING_EVENTS = new Set([
290
+ 'blur', 'focus', 'load', 'unload',
291
+ 'mouseenter', 'mouseleave',
292
+ 'pointerenter', 'pointerleave',
293
+ ])
294
+
281
295
  /**
282
296
  * Quote a prop name if it is not a valid JS identifier.
283
297
  * Returns the name as-is for valid identifiers (e.g., "checked"),