@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
@@ -82,7 +82,17 @@ describe('destructured-from-props-object → localConstants value rewrite', () =
82
82
  expect(content).not.toMatch(/const\s+doubled\s*=\s*_p\.count\(\)/)
83
83
  })
84
84
 
85
- test('shadow guard: earlier local that shadows a prop is NOT rewritten', () => {
85
+ // #2934: `const label = props.label ?? 'fallback'` is a PURE single-prop
86
+ // alias — the analyzer's IR can't distinguish it from a destructure
87
+ // (`const { label = 'fallback' } = props`), and `resolveBodyPropAliases`
88
+ // deliberately treats both identically (see its docstring). So `label`'s
89
+ // own declaration is now removed and every reference to it — including
90
+ // from a DEPENDENT local's own initializer, `upper` here — becomes a
91
+ // live `_p.label` read. This used to be named a "shadow guard" test, back
92
+ // when `label` was expected to stay a captured-once local distinct from
93
+ // the prop; that framing no longer applies now that a same-named pure
94
+ // alias IS made live rather than left as its own local.
95
+ test('a plain member-access prop alias is rewritten live, including from a dependent local', () => {
86
96
  const source = `
87
97
  'use client'
88
98
 
@@ -102,10 +112,11 @@ describe('destructured-from-props-object → localConstants value rewrite', () =
102
112
  const clientJs = result.files.find((f) => f.type === 'clientJs')
103
113
  const content = clientJs?.content ?? ''
104
114
 
105
- // `label` here is the local const (shadowing the prop). The init body
106
- // emits `const label = _p.label ?? 'fallback'` (late-stage rename),
107
- // and `upper` should reference the LOCAL `label`, not `_p.label`.
108
- expect(content).toMatch(/const\s+upper\s*=\s*label\.toUpperCase\(\)/)
109
- expect(content).not.toMatch(/const\s+upper\s*=\s*_p\.label\.toUpperCase\(\)/)
115
+ // `label`'s own extraction is gone — it was a pure alias, not a real
116
+ // computation of its own.
117
+ expect(content).not.toMatch(/const\s+label\s*=/)
118
+ // `upper` (still a real once-evaluated local — `.toUpperCase()` is a
119
+ // computation) now sources its value directly from the live prop read.
120
+ expect(content).toMatch(/const\s+upper\s*=\s*\(_p\.label\s*\?\?\s*'fallback'\)\.toUpperCase\(\)/)
110
121
  })
111
122
  })
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Destructured props stay reactive: every value-position read of a
3
+ * destructured prop name in the compiled `init*` body is a live `_p.<key>`
4
+ * read (or `(_p.<key> ?? <fallback>)`), the same shape `props.xxx` access
5
+ * compiles to. See `props-binding.ts`'s `livePropReadExpr` and
6
+ * `ir-to-client-js/rewrite-destructured-props.ts`.
7
+ */
8
+
9
+ import { describe, test, expect } from 'bun:test'
10
+ import { compileJSX } from '../compiler'
11
+ import { TestAdapter } from '../adapters/test-adapter'
12
+ import { ErrorCodes } from '../errors'
13
+
14
+ const adapter = new TestAdapter()
15
+
16
+ function compileClientJs(source: string, filename = 'Component.tsx') {
17
+ const result = compileJSX(source, filename, { adapter })
18
+ const errors = result.errors.filter((e) => e.severity === 'error')
19
+ expect(errors).toEqual([])
20
+ const clientJs = result.files.find((f) => f.type === 'clientJs')
21
+ expect(clientJs).toBeDefined()
22
+ return { content: clientJs!.content, result }
23
+ }
24
+
25
+ describe('destructured props compile to live reads', () => {
26
+ test('BF043 no longer exists as an error code', () => {
27
+ // Checked by string value, not by a removed `ErrorCodes` key (that
28
+ // would be a compile error) — same convention as
29
+ // `invalid-signal-usage.audit.test.ts`'s BF012 deletion audit.
30
+ expect(Object.values(ErrorCodes)).not.toContain('BF043')
31
+ })
32
+
33
+ test('a destructured prop no longer gets a captured-once extraction line, and no BF043 diagnostic appears', () => {
34
+ const source = `
35
+ 'use client'
36
+ import { createSignal, createMemo, createEffect } from '@barefootjs/client'
37
+
38
+ function Child({ value, onClick, label = 'n', size = 'md', items = [] }: {
39
+ value: number
40
+ onClick: () => void
41
+ label?: string
42
+ size?: string
43
+ items?: string[]
44
+ }) {
45
+ const doubled = createMemo(() => value * 2)
46
+ const [local, setLocal] = createSignal(value)
47
+ createEffect(() => {
48
+ console.log('value is', value)
49
+ })
50
+ return (
51
+ <div className={size}>
52
+ <span data-label={label}>{value}</span>
53
+ <span>{doubled()}</span>
54
+ <span>{items.length}</span>
55
+ <button onClick={() => { setLocal(value); onClick() }}>click</button>
56
+ </div>
57
+ )
58
+ }
59
+ `
60
+ const { content, result } = compileClientJs(source, 'Child.tsx')
61
+
62
+ // No captured-once local for any destructured prop.
63
+ expect(content).not.toContain('const value = _p.value')
64
+ expect(content).not.toContain('const onClick = _p.onClick')
65
+ expect(content).not.toContain('const label = ')
66
+ expect(content).not.toContain('const size = ')
67
+ expect(content).not.toContain('const items = ')
68
+
69
+ // Memo computation reads the live prop directly.
70
+ expect(content).toMatch(/createMemo\(\(\) => _p\.value \* 2\)/)
71
+
72
+ // The user effect reads the live prop, not a captured local.
73
+ expect(content).toContain("console.log('value is', _p.value)")
74
+
75
+ // The handler reads the live prop for both the signal update and the
76
+ // callback-prop invocation.
77
+ expect(content).toContain('_p.onClick()')
78
+ expect(content).toContain('setLocal(_p.value)')
79
+
80
+ // `items`'s destructure default survives as a live fallback, not a
81
+ // one-time extraction.
82
+ expect(content).toContain('(_p.items ?? []).length')
83
+
84
+ // No BF043 diagnostic (retired) anywhere in errors/warnings.
85
+ expect(result.errors.some((e) => e.code === 'BF043')).toBe(false)
86
+ })
87
+
88
+ test('an aliased destructured prop (`{ n: count }`) reads the caller-facing key live everywhere', () => {
89
+ const source = `
90
+ 'use client'
91
+ import { createEffect } from '@barefootjs/client'
92
+ function Badge({ text, n: count }: { text: string; n: number }) {
93
+ createEffect(() => {
94
+ console.log(count)
95
+ })
96
+ return <span>{text}:{count}</span>
97
+ }
98
+ `
99
+ const { content } = compileClientJs(source, 'Badge.tsx')
100
+ expect(content).not.toContain('const count = ')
101
+ expect(content).not.toContain('_p.count')
102
+ expect(content).toContain('console.log(_p.n)')
103
+ })
104
+
105
+ test('an accessor-typed prop (`value: () => number`) still gets CALLED at the live read site', () => {
106
+ const source = `
107
+ 'use client'
108
+ import { createEffect } from '@barefootjs/client'
109
+ function Child({ value }: { value: () => number }) {
110
+ createEffect(() => {
111
+ console.log(value())
112
+ })
113
+ return <span>{value()}</span>
114
+ }
115
+ `
116
+ const { content } = compileClientJs(source, 'Child.tsx')
117
+ expect(content).not.toContain('const value = _p.value')
118
+ expect(content).toContain('_p.value()')
119
+ })
120
+
121
+ test('shadowing is preserved: a `.map()` callback param and a handler-local both keep their own binding', () => {
122
+ const source = `
123
+ 'use client'
124
+ import { createSignal } from '@barefootjs/client'
125
+ function List({ title, items }: { title: string; items: { a: string }[] }) {
126
+ const [count, setCount] = createSignal(0)
127
+ return (
128
+ <div>
129
+ <span>{title}</span>
130
+ <ul>
131
+ {items.map((title) => <li key={title.a}>{title.a}</li>)}
132
+ </ul>
133
+ <button onClick={() => {
134
+ const title = 'local'
135
+ console.log(title)
136
+ setCount(count() + 1)
137
+ }}>click</button>
138
+ </div>
139
+ )
140
+ }
141
+ `
142
+ const { content } = compileClientJs(source, 'List.tsx')
143
+ // The outer `title` prop is rewritten wherever it is a free reference.
144
+ expect(content).toContain('_p.title')
145
+ // The `.map()` callback's OWN `title` parameter must never be rewritten
146
+ // — `(_p.title) => _p.title.a` would be invalid JS.
147
+ expect(content).not.toMatch(/\(_p\.title\)\s*=>/)
148
+ expect(content).toMatch(/\(title\)\s*=>[\s\S]*?title\.a/)
149
+ // The handler-local `const title = 'local'` shadows the prop for the
150
+ // rest of that handler — its own reference must stay bare.
151
+ expect(content).toContain("const title = 'local'")
152
+ expect(content).toContain('console.log(title)')
153
+ })
154
+
155
+ test('`children` keeps its one-time captured-once extraction (not rewritten live)', () => {
156
+ const source = `
157
+ 'use client'
158
+ import { createSignal } from '@barefootjs/client'
159
+ function Wrapper({ children }: { children: unknown }) {
160
+ const [open, setOpen] = createSignal(true)
161
+ return <div onClick={() => setOpen(!open())}>{open() ? children : null}</div>
162
+ }
163
+ `
164
+ const { content } = compileClientJs(source, 'Wrapper.tsx')
165
+ expect(content).toContain('const children = _p.children')
166
+ })
167
+ })
@@ -433,9 +433,8 @@ for (const page of PAGES) {
433
433
  //
434
434
  // - "Implemented but doc snippet too minimal": the code IS emitted
435
435
  // by the compiler in real programs, but the literal snippet in
436
- // `error-codes.md` doesn't carry enough context (e.g. BF043 needs
437
- // a stateful component; BF044 needs a declared signal getter).
438
- // These are doc-edit follow-ups.
436
+ // `error-codes.md` doesn't carry enough context (e.g. BF044 needs
437
+ // a declared signal getter). These are doc-edit follow-ups.
439
438
  //
440
439
  // Previously-documented-but-unimplemented codes were removed from the
441
440
  // doc to keep it honest.
@@ -458,7 +457,6 @@ interface ErrorCodeContract {
458
457
  // surrounding context the snippet omits).
459
458
  const ERROR_CODES_DOC_TOO_MINIMAL: Record<string, string> = {
460
459
  BF021: 'BF021 has multiple ❌ snippets in placeholder form (`.map(...)`) — covered concretely by `jsx-compatibility.md` tests; the doc-form snippets here remain placeholder',
461
- BF043: 'BF043 fires only for STATEFUL components (signals/memos/effects). The doc snippet `function Child({ count }: Props)` has no reactivity, so the check is correctly silent — doc snippet needs enrichment to be testable as-is',
462
460
  BF044: 'BF044 fires only when a real signal getter is bound. The doc snippet `<Child count={count} />` references an undeclared `count`, so the check is silent — doc snippet needs enrichment',
463
461
  BF101: 'BF101 is raised by the non-JS template adapters\' own per-adapter checks (Go/Mojo/Xslate/… `renderLoop` / callback lowering), not by the shared `isSupported` gate every adapter shares — `TestAdapter` here is JS-runtime-style like Hono and executes both doc snippets verbatim, so the check is correctly silent. Covered concretely (compiled against the real 8 template adapters, with verbatim diagnostic text) by `jsx-compatibility.md`\'s doc-examples coverage and the `filter-nested-callback-predicate` / `filter-nested-find-predicate` / `static-array-from-props` adapter-conformance fixtures.',
464
462
  }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * BarefootJS Compiler — container's own handler vs. a `.map()` row's
3
+ * delegated handler for the same event (#2930).
4
+ *
5
+ * `.map()` rows compiled via delegation share their delegated listener's
6
+ * DOM node with the loop's static container. When the container ALSO
7
+ * carries its own directly-authored handler for the same event, both used
8
+ * to become separate `addEventListener` calls on the identical node, so a
9
+ * row's `stopPropagation()` could never stop the container's own handler
10
+ * (native DOM: `stopPropagation()` only blocks bubbling to *other nodes*,
11
+ * never other listeners already registered on the *same* node).
12
+ *
13
+ * The fix merges the two into ONE listener: the delegated dispatch runs
14
+ * first, and the container's own handler only fires when the event's
15
+ * `cancelBubble` flag is still false — i.e. no row handler called
16
+ * `stopPropagation()`/`stopImmediatePropagation()`.
17
+ */
18
+
19
+ import { describe, test, expect } from 'bun:test'
20
+ import { compileJSX } from '../compiler'
21
+ import { TestAdapter } from '../adapters/test-adapter'
22
+
23
+ const adapter = new TestAdapter()
24
+
25
+ function compileClientJs(source: string): string {
26
+ const result = compileJSX(source, 'Repro.tsx', { adapter })
27
+ expect(result.errors).toHaveLength(0)
28
+ const clientJs = result.files.find(f => f.type === 'clientJs')
29
+ expect(clientJs).toBeDefined()
30
+ return clientJs!.content
31
+ }
32
+
33
+ describe('event delegation vs. container own handler (#2930)', () => {
34
+ test('static array: container onContextMenu merges into the row delegation listener', () => {
35
+ const source = `
36
+ 'use client'
37
+ const items = ['a', 'b', 'c']
38
+
39
+ export function Repro() {
40
+ return (
41
+ <div
42
+ id="container"
43
+ onContextMenu={(e) => {
44
+ e.preventDefault()
45
+ console.log('container handler')
46
+ }}
47
+ >
48
+ {items.map(item => (
49
+ <div
50
+ key={item}
51
+ data-item={item}
52
+ onContextMenu={(e) => {
53
+ e.preventDefault()
54
+ e.stopPropagation()
55
+ console.log('row handler', item)
56
+ }}
57
+ >
58
+ row {item}
59
+ </div>
60
+ ))}
61
+ </div>
62
+ )
63
+ }
64
+ `
65
+ const content = compileClientJs(source)
66
+
67
+ // Exactly one addEventListener('contextmenu', ...) on the shared
68
+ // container — not two separate registrations.
69
+ const registrations = content.match(/\.addEventListener\('contextmenu'/g) ?? []
70
+ expect(registrations).toHaveLength(1)
71
+
72
+ // The merged listener fires the row handler, then gates the
73
+ // container's own handler on `cancelBubble`, and also fires it
74
+ // unconditionally when no row matched (click on the container's own
75
+ // background).
76
+ expect(content).toContain('row handler')
77
+ expect(content).toContain('container handler')
78
+ expect(content).toContain('!__bfEvt.cancelBubble')
79
+
80
+ // The row handler must be checked (and able to call stopPropagation)
81
+ // BEFORE the cancelBubble-gated container call.
82
+ const rowPos = content.indexOf("console.log('row handler'")
83
+ const gatePos = content.indexOf('!__bfEvt.cancelBubble')
84
+ expect(rowPos).toBeGreaterThan(-1)
85
+ expect(gatePos).toBeGreaterThan(-1)
86
+ expect(rowPos).toBeLessThan(gatePos)
87
+ })
88
+
89
+ test('dynamic loop: container onContextMenu merges into the row delegation listener', () => {
90
+ const source = `
91
+ 'use client'
92
+ import { createSignal } from '@barefootjs/client'
93
+
94
+ export function Repro() {
95
+ const [items, setItems] = createSignal(['a', 'b', 'c'])
96
+ return (
97
+ <div
98
+ onContextMenu={(e) => {
99
+ e.preventDefault()
100
+ console.log('container handler')
101
+ }}
102
+ >
103
+ {items().map(item => (
104
+ <div
105
+ key={item}
106
+ onContextMenu={(e) => {
107
+ e.preventDefault()
108
+ e.stopPropagation()
109
+ console.log('row handler', item)
110
+ }}
111
+ >
112
+ row {item}
113
+ </div>
114
+ ))}
115
+ </div>
116
+ )
117
+ }
118
+ `
119
+ const content = compileClientJs(source)
120
+
121
+ const registrations = content.match(/\.addEventListener\('contextmenu'/g) ?? []
122
+ expect(registrations).toHaveLength(1)
123
+ expect(content).toContain('!__bfEvt.cancelBubble')
124
+ })
125
+
126
+ test('container handler alone (no row collision) stays byte-unaffected', () => {
127
+ const source = `
128
+ 'use client'
129
+ const items = ['a', 'b', 'c']
130
+
131
+ export function Repro() {
132
+ return (
133
+ <div onContextMenu={(e) => console.log('container handler')}>
134
+ {items.map(item => <div key={item}>row {item}</div>)}
135
+ </div>
136
+ )
137
+ }
138
+ `
139
+ const content = compileClientJs(source)
140
+
141
+ // No loop event to delegate at all — the container's own listener is
142
+ // the ordinary direct-listener emission, unaffected by this change.
143
+ expect(content).not.toContain('cancelBubble')
144
+ const registrations = content.match(/\.addEventListener\('contextmenu'/g) ?? []
145
+ expect(registrations).toHaveLength(1)
146
+ })
147
+
148
+ test('row handler alone (no container collision) stays byte-unaffected', () => {
149
+ const source = `
150
+ 'use client'
151
+ const items = ['a', 'b', 'c']
152
+
153
+ export function Repro() {
154
+ return (
155
+ <div>
156
+ {items.map(item => (
157
+ <div key={item} onContextMenu={(e) => { e.stopPropagation(); console.log('row handler', item) }}>
158
+ row {item}
159
+ </div>
160
+ ))}
161
+ </div>
162
+ )
163
+ }
164
+ `
165
+ const content = compileClientJs(source)
166
+
167
+ // Delegation-only — no own handler to gate, so no cancelBubble check
168
+ // is introduced.
169
+ expect(content).not.toContain('cancelBubble')
170
+ const registrations = content.match(/\.addEventListener\('contextmenu'/g) ?? []
171
+ expect(registrations).toHaveLength(1)
172
+ })
173
+
174
+ test('two real nested elements (no .map()) keep two independent listeners', () => {
175
+ // The structurally simpler case from the issue report: no delegation
176
+ // involved at all, so native bubbling already does the right thing and
177
+ // this change must not touch it.
178
+ const source = `
179
+ 'use client'
180
+
181
+ export function Repro() {
182
+ return (
183
+ <div onContextMenu={(e) => console.log('outer')}>
184
+ <div onContextMenu={(e) => { e.stopPropagation(); console.log('inner') }}>
185
+ inner
186
+ </div>
187
+ </div>
188
+ )
189
+ }
190
+ `
191
+ const content = compileClientJs(source)
192
+
193
+ expect(content).not.toContain('cancelBubble')
194
+ const registrations = content.match(/\.addEventListener\('contextmenu'/g) ?? []
195
+ expect(registrations).toHaveLength(2)
196
+ })
197
+ })
@@ -28,8 +28,10 @@ describe('formatError — diagnostic rendering contract', () => {
28
28
  })
29
29
 
30
30
  test('warning severity also lowercases', () => {
31
+ // Any code works: `severity` is an explicit override on `createError`,
32
+ // independent of the code's own default.
31
33
  const err = createError(
32
- ErrorCodes.PROPS_DESTRUCTURING,
34
+ ErrorCodes.MISSING_KEY_IN_LIST,
33
35
  {
34
36
  file: 'components/Display.tsx',
35
37
  start: { line: 1, column: 17 },
@@ -39,7 +41,7 @@ describe('formatError — diagnostic rendering contract', () => {
39
41
  )
40
42
 
41
43
  const out = formatError(err)
42
- expect(out).toContain('warning[BF043]:')
44
+ expect(out).toContain('warning[BF023]:')
43
45
  })
44
46
 
45
47
  test('--> row carries the documented file:line:col location', () => {
@@ -90,7 +92,7 @@ describe('formatError — diagnostic rendering contract', () => {
90
92
 
91
93
  test('suggestion renders as a `= help:` row at the tail', () => {
92
94
  const err = createError(
93
- ErrorCodes.PROPS_DESTRUCTURING,
95
+ ErrorCodes.MISSING_KEY_IN_LIST,
94
96
  {
95
97
  file: 'Display.tsx',
96
98
  start: { line: 1, column: 17 },
@@ -0,0 +1,141 @@
1
+ /**
2
+ * #2960 — `addCondAttrToTemplate`'s `isSingleRootElement` heuristic
3
+ * mis-classified a multi-root ternary branch as a single element root
4
+ * whenever its LAST element happened to share its FIRST element's tag
5
+ * name (`<div>...</div><div>...</div>`): the check was "does the string
6
+ * end with a closing tag of the root's own tag name", which a second,
7
+ * unrelated sibling of the same tag name satisfies just as well as a
8
+ * genuine single root's own closing tag.
9
+ *
10
+ * Compiled wrong, this stamps `bf-c="<id>"` onto only the first element
11
+ * instead of comment-wrapping the whole branch — which routes the
12
+ * runtime's branch swap through `insert()`'s `updateElementConditional`
13
+ * (`fragment.firstChild`-only) instead of `updateFragmentConditional`
14
+ * (which moves every top-level node), silently dropping every sibling
15
+ * but the first on a live branch swap.
16
+ */
17
+ import { describe, test, expect } from 'bun:test'
18
+ import { compileJSX } from '../compiler'
19
+ import { TestAdapter } from '../adapters/test-adapter'
20
+ import { addCondAttrToTemplate } from '../ir-to-client-js/html-template'
21
+
22
+ const adapter = new TestAdapter()
23
+
24
+ describe('#2960: multi-root cond branch whose roots share a tag name', () => {
25
+ test('comment-wraps a same-tag-name multi-root branch instead of stamping bf-c on only the first element', () => {
26
+ const source = `
27
+ 'use client'
28
+ import { createSignal } from '@barefootjs/client'
29
+
30
+ export function Repro() {
31
+ const [open, setOpen] = createSignal(false)
32
+ return (
33
+ <div>
34
+ <button onClick={() => setOpen(true)}>open</button>
35
+ {open() === false ? (
36
+ <div id="welcome">Welcome</div>
37
+ ) : (
38
+ <>
39
+ <div id="before">before</div>
40
+ <div id="after">after</div>
41
+ </>
42
+ )}
43
+ </div>
44
+ )
45
+ }
46
+ `
47
+
48
+ const result = compileJSX(source, 'Repro.tsx', { adapter })
49
+ expect(result.errors).toHaveLength(0)
50
+
51
+ const clientJs = result.files.find(f => f.type === 'clientJs')
52
+ expect(clientJs).toBeDefined()
53
+
54
+ // The multi-root branch must be comment-wrapped ...
55
+ expect(clientJs!.content).toContain('bf-cond-start:')
56
+ expect(clientJs!.content).toContain('bf-cond-end:')
57
+ // ... and BOTH of its sibling elements must appear inside the
58
+ // template literal, not just the first one.
59
+ expect(clientJs!.content).toMatch(/id=\\?"before\\?"/)
60
+ expect(clientJs!.content).toMatch(/id=\\?"after\\?"/)
61
+ })
62
+
63
+ test('a genuine single-root branch (no same-tag sibling) still gets bf-c, not comment markers', () => {
64
+ const source = `
65
+ 'use client'
66
+ import { createSignal } from '@barefootjs/client'
67
+
68
+ export function Simple() {
69
+ const [on, setOn] = createSignal(false)
70
+ return <div>{on() ? <span id="a">A</span> : <span id="b">B</span>}</div>
71
+ }
72
+ `
73
+
74
+ const result = compileJSX(source, 'Simple.tsx', { adapter })
75
+ expect(result.errors).toHaveLength(0)
76
+
77
+ const clientJs = result.files.find(f => f.type === 'clientJs')
78
+ expect(clientJs).toBeDefined()
79
+ expect(clientJs!.content).toContain('bf-c=')
80
+ expect(clientJs!.content).not.toContain('bf-cond-start:')
81
+ })
82
+
83
+ // The depth-tracking fix above must not widen which shapes are treated
84
+ // as "single root" beyond what the sibling `bf-c` splice regex
85
+ // (`html.replace(/^(<\w+)(\s|>)/, ...)`) can actually stamp — a
86
+ // self-closing root's own `/` or a hyphenated custom-element tag name
87
+ // both fail that splice. Every one of these must still come back
88
+ // comment-wrapped (never bare, unmodified HTML with neither `bf-c` nor
89
+ // markers, which would make `insert()` unable to find the branch at all).
90
+ describe('does not widen single-root detection into shapes the bf-c splice cannot stamp', () => {
91
+ const unstampable = [
92
+ ['<input/>', 'self-closing void element root'],
93
+ ['<my-widget>a</my-widget>', 'hyphenated custom-element root'],
94
+ ['<my-widget>a</my-widget><my-widget>b</my-widget>', 'multi-root, same hyphenated tag'],
95
+ ] as const
96
+
97
+ for (const [html, label] of unstampable) {
98
+ test(label, () => {
99
+ const result = addCondAttrToTemplate(html, 'c1')
100
+ expect(result).toContain('bf-cond-start:c1')
101
+ expect(result).toContain('bf-cond-end:c1')
102
+ })
103
+ }
104
+ })
105
+
106
+ // The depth-tracking walk must not treat BarefootJS's own marker
107
+ // comments (`<!--bf:sN-->`, its `<!--/-->` pair) as if they were real
108
+ // tags — an earlier version of this fix's tag-matching regex matched
109
+ // any `<...>` run indiscriminately, so a perfectly ordinary single-root
110
+ // branch with an internal reactive text slot got miscounted into an
111
+ // unbalanced depth and wrongly comment-wrapped instead of getting
112
+ // `bf-c`. Caught by `doc-examples.test.ts`'s snapshot drifting on the
113
+ // `count() > 0 ? <p>...</p> : <p>No items</p>` example.
114
+ test('a single root containing internal bf: slot marker comments still gets bf-c, not comment-wrap', () => {
115
+ const html = '<p bf="s2"><!--bf:s1-->${__bfSlot(count(), __slots)}<!--/--> items</p>'
116
+ const result = addCondAttrToTemplate(html, 's0')
117
+ expect(result).toContain('bf-c="s0"')
118
+ expect(result).not.toContain('bf-cond-start:')
119
+ })
120
+
121
+ // A self-closing/void root followed by a real sibling element
122
+ // (`<input .../><label>...</label>`, todo-app's "mark all as complete"
123
+ // branch) is genuinely two roots. The whole-string self-closing check
124
+ // only catches a self-closing tag with NOTHING else in the string, so
125
+ // this shape still reaches the depth-tracking walk — an earlier version
126
+ // of that walk unconditionally `continue`d past every self-closing tag
127
+ // on the theory that one could never be the outermost token by the time
128
+ // the walk runs, which is wrong: the initial tag-name gate only checks
129
+ // the tag name and the character right after it, not whether the tag
130
+ // later turns out to self-close. That version silently merged the
131
+ // `<input/>` and `<label>` into a false single root, stamping `bf-c`
132
+ // onto only the `<input/>` and dropping `<label>` on a live swap.
133
+ // Caught by `generate-expected-html.ts` drifting the `todo-app` fixture.
134
+ test('a self-closing root followed by a sibling element is multi-root, not single', () => {
135
+ const html = '<input id="toggle-all" class="toggle-all" type="checkbox" bf="s2" /><label for="toggle-all">Mark all as complete</label>'
136
+ const result = addCondAttrToTemplate(html, 's1')
137
+ expect(result).toContain('bf-cond-start:s1')
138
+ expect(result).toContain('bf-cond-end:s1')
139
+ expect(result).not.toContain('bf-c=')
140
+ })
141
+ })