@barefootjs/jsx 0.39.2 → 0.39.3
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.
- package/dist/adapters/line-statement-text.d.ts +17 -0
- package/dist/adapters/line-statement-text.d.ts.map +1 -0
- package/dist/analyzer.d.ts +1 -0
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/augment-inherited-props.d.ts +20 -0
- package/dist/augment-inherited-props.d.ts.map +1 -1
- package/dist/html-types.d.ts +15 -0
- package/dist/html-types.d.ts.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +260 -91
- package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
- package/dist/ir-to-client-js/utils.d.ts.map +1 -1
- package/dist/nullable-signal-attr.d.ts +73 -0
- package/dist/nullable-signal-attr.d.ts.map +1 -0
- package/dist/scope/root-prop-alias.d.ts +43 -0
- package/dist/scope/root-prop-alias.d.ts.map +1 -0
- package/package.json +2 -2
- package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +3 -3
- package/src/__tests__/attribute-fallback-wrap.test.ts +24 -0
- package/src/__tests__/compiler-stress-1244.test.ts +10 -13
- package/src/__tests__/conditional-fallback-wrap.test.ts +20 -0
- package/src/__tests__/html-event-handler-names.test.ts +107 -0
- package/src/__tests__/line-statement-text.test.ts +25 -0
- package/src/__tests__/lookup-literal-const.test.ts +46 -0
- package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +66 -19
- package/src/__tests__/nullable-signal-attr.test.ts +124 -0
- package/src/__tests__/profile-binding-ids.test.ts +102 -0
- package/src/__tests__/root-prop-alias.test.ts +62 -0
- package/src/adapters/line-statement-text.ts +24 -0
- package/src/analyzer.ts +50 -26
- package/src/augment-inherited-props.ts +49 -0
- package/src/html-types.ts +15 -0
- package/src/index.ts +13 -2
- package/src/ir-to-client-js/collect-elements.ts +7 -1
- package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +2 -2
- package/src/ir-to-client-js/stringify/declaration-emit.ts +5 -5
- package/src/ir-to-client-js/utils.ts +88 -117
- package/src/jsx-to-ir.ts +7 -0
- package/src/nullable-signal-attr.ts +156 -0
- package/src/scope/root-prop-alias.ts +81 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { ComponentIR } from '../types.ts';
|
|
2
|
+
import type { BindingScope } from './binding-scope.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Root-prop aliases for template engines that flatten `props.X` to the bare
|
|
5
|
+
* template variable `X` (#3314). A loop that binds the same name (`.map(value
|
|
6
|
+
* => …)`) shadows that variable for its whole body, so an explicit
|
|
7
|
+
* `props.value` inside the row read the ROW's `value` instead of the prop.
|
|
8
|
+
*
|
|
9
|
+
* The adapter assigns each shadowed prop to an alias just before the loop
|
|
10
|
+
* header — where the bare name still means the prop — and an explicit
|
|
11
|
+
* `props.X` read inside the row uses the alias. Only the template syntax
|
|
12
|
+
* of the assignment is per-adapter; which names need one, and their alias
|
|
13
|
+
* name, are decided here once.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* The template variable each prop in `propNames` is aliased to: `__bf_root_<name>`,
|
|
17
|
+
* extended with `_` until it names nothing else the component turns into a
|
|
18
|
+
* template variable — a prop, a local const or function, a signal or memo,
|
|
19
|
+
* any loop binding, or another prop's alias. The `__bf_` namespace is
|
|
20
|
+
* reserved only by convention, so an alias must not overwrite a user prop
|
|
21
|
+
* spelled `__bf_root_value` nor be shadowed by a binding of that name.
|
|
22
|
+
* Computed once per component so the assignment before a loop and every
|
|
23
|
+
* `props.X` read inside it agree on the name.
|
|
24
|
+
*/
|
|
25
|
+
export declare function rootPropAliasNames(ir: ComponentIR, propNames: Iterable<string>): ReadonlyMap<string, string>;
|
|
26
|
+
/**
|
|
27
|
+
* Props the loop row newly shadows, with their aliases: names `row` binds
|
|
28
|
+
* that `outer` did not (an enclosing loop that already bound a name already
|
|
29
|
+
* aliased it, and a re-assignment here would capture that loop's row value)
|
|
30
|
+
* and that are component props (keys of `aliases`). In source order of
|
|
31
|
+
* `row`'s bindings.
|
|
32
|
+
*/
|
|
33
|
+
export declare function rootPropAliasesForLoop(outer: BindingScope, row: BindingScope, aliases: ReadonlyMap<string, string>): {
|
|
34
|
+
name: string;
|
|
35
|
+
alias: string;
|
|
36
|
+
}[];
|
|
37
|
+
/**
|
|
38
|
+
* The template variable an explicit `props.<name>` read resolves to at a
|
|
39
|
+
* position with `scope`: the alias (from `rootPropAliasNames`) while a loop
|
|
40
|
+
* binding shadows `name`, else `name` itself.
|
|
41
|
+
*/
|
|
42
|
+
export declare function rootPropReadName(name: string, scope: BindingScope, aliases: ReadonlyMap<string, string>): string;
|
|
43
|
+
//# sourceMappingURL=root-prop-alias.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"root-prop-alias.d.ts","sourceRoot":"","sources":["../../src/scope/root-prop-alias.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAEtD;;;;;;;;;;;GAWG;AAEH;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAmB5G;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,YAAY,EACnB,GAAG,EAAE,YAAY,EACjB,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GACnC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,EAAE,CAOnC;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GACnC,MAAM,CAGR"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@barefootjs/jsx",
|
|
3
|
-
"version": "0.39.
|
|
3
|
+
"version": "0.39.3",
|
|
4
4
|
"description": "JSX compiler for BarefootJS - transforms JSX to server HTML + client JS",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"directory": "packages/jsx"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@barefootjs/shared": "0.39.
|
|
52
|
+
"@barefootjs/shared": "0.39.3"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"@barefootjs/client": ">=0.2.0",
|
|
@@ -859,7 +859,7 @@ hydrate('StatementExample', { init: initStatementExample, template: (_p) => \`<d
|
|
|
859
859
|
export function StatementExample(_p, __bfKey) { return createComponent('StatementExample', _p, __bfKey) }"
|
|
860
860
|
`;
|
|
861
861
|
|
|
862
|
-
exports[`docs/core/reactivity/create-signal.md doc-examples
|
|
862
|
+
exports[`docs/core/reactivity/create-signal.md doc-examples L33 — (no label) 1`] = `
|
|
863
863
|
"import { createComponent, createEffect, createMemo, createSignal, hydrate, onCleanup, onMount, untrack } from '@barefootjs/client/runtime'
|
|
864
864
|
|
|
865
865
|
|
|
@@ -875,7 +875,7 @@ hydrate('StatementExample', { init: initStatementExample, template: (_p) => \`<d
|
|
|
875
875
|
export function StatementExample(_p, __bfKey) { return createComponent('StatementExample', _p, __bfKey) }"
|
|
876
876
|
`;
|
|
877
877
|
|
|
878
|
-
exports[`docs/core/reactivity/create-signal.md doc-examples
|
|
878
|
+
exports[`docs/core/reactivity/create-signal.md doc-examples L36 — ❌ Mutating the same array — no update 1`] = `
|
|
879
879
|
"import { createComponent, createEffect, createMemo, createSignal, hydrate, onCleanup, onMount, untrack } from '@barefootjs/client/runtime'
|
|
880
880
|
|
|
881
881
|
|
|
@@ -894,7 +894,7 @@ hydrate('StatementExample', { init: initStatementExample, template: (_p) => \`<d
|
|
|
894
894
|
export function StatementExample(_p, __bfKey) { return createComponent('StatementExample', _p, __bfKey) }"
|
|
895
895
|
`;
|
|
896
896
|
|
|
897
|
-
exports[`docs/core/reactivity/create-signal.md doc-examples
|
|
897
|
+
exports[`docs/core/reactivity/create-signal.md doc-examples L41 — ✅ New array — triggers update 1`] = `
|
|
898
898
|
"import { createComponent, createEffect, createMemo, createSignal, hydrate, onCleanup, onMount, untrack } from '@barefootjs/client/runtime'
|
|
899
899
|
|
|
900
900
|
|
|
@@ -216,4 +216,28 @@ describe('Solid-style wrap-by-default fallback for attributes (#940)', () => {
|
|
|
216
216
|
expect(clientJs).not.toContain('Reactive attributes')
|
|
217
217
|
expect(clientJs).not.toMatch(/setAttribute\(\s*['"]style['"]/)
|
|
218
218
|
})
|
|
219
|
+
|
|
220
|
+
test('a wrapped attribute on an element with no other dynamic content gets a slot (#3266)', () => {
|
|
221
|
+
// `v()` reads a store the analyzer can't see into (an untyped prop
|
|
222
|
+
// holding a class instance), so only the call shape marks
|
|
223
|
+
// `hidden={v().hide}` for wrapping. The <p> has no event, ref or
|
|
224
|
+
// dynamic child, so before #3266 it got no slot id: the wrapped effect
|
|
225
|
+
// had no element to address and `hidden` was never applied on the
|
|
226
|
+
// client, not even initially.
|
|
227
|
+
const source = `
|
|
228
|
+
'use client'
|
|
229
|
+
|
|
230
|
+
export function Card(props: any) {
|
|
231
|
+
const s = props.data.s
|
|
232
|
+
const v = () => s.get()
|
|
233
|
+
return <div><p className="h" hidden={v().hide}>x</p></div>
|
|
234
|
+
}
|
|
235
|
+
`
|
|
236
|
+
|
|
237
|
+
const clientJs = getClientJs(source, 'Card.tsx')
|
|
238
|
+
const slot = clientJs.match(/<p class="h" [^>]*bf="(s\d+)"/)?.[1]
|
|
239
|
+
expect(slot).toBeDefined()
|
|
240
|
+
expect(clientJs).toContain(`_${slot}.hidden = !!(__x)`)
|
|
241
|
+
expect(clientJs).toContain('const __x = v().hide')
|
|
242
|
+
})
|
|
219
243
|
})
|
|
@@ -617,18 +617,15 @@ describe('nested destructuring in loop param', () => {
|
|
|
617
617
|
// SyntaxError that takes down the whole compiled module at parse
|
|
618
618
|
// time, before any runtime code runs.
|
|
619
619
|
//
|
|
620
|
-
// The
|
|
621
|
-
// expression's TS AST,
|
|
622
|
-
// name matches a binding, and
|
|
623
|
-
//
|
|
624
|
-
// identifier-replacement regex skips string-literal contents, so the
|
|
625
|
-
// key stays as the literal `"color"` while the value-position
|
|
626
|
-
// `color` lowers to `__bfItem().color`.
|
|
620
|
+
// The binding rewrite (`rewriteIdentifierReferences`) walks the
|
|
621
|
+
// expression's TS AST and, for a `ShorthandPropertyAssignment` whose
|
|
622
|
+
// name matches a binding, emits the key and the rewritten value in
|
|
623
|
+
// one edit (`{ color: __bfItem().color }`, #3260).
|
|
627
624
|
//
|
|
628
625
|
// `style={{ color }}` is the most common surface (Tailwind-style
|
|
629
626
|
// dynamic colour bindings on per-item tables / lists) and is the
|
|
630
627
|
// shape this test pins.
|
|
631
|
-
test('shorthand property in object literal lowers via
|
|
628
|
+
test('shorthand property in object literal lowers via key expansion (CSR runtime path)', () => {
|
|
632
629
|
const src = `
|
|
633
630
|
'use client'
|
|
634
631
|
import { createSignal } from '@barefootjs/client'
|
|
@@ -650,14 +647,14 @@ describe('nested destructuring in loop param', () => {
|
|
|
650
647
|
// The invalid shorthand form `{ __bfItem().color }` is a SyntaxError;
|
|
651
648
|
// its presence in the emit means the module won't load at all.
|
|
652
649
|
expect(c.clientJs).not.toMatch(/\{\s*__bfItem\(\)\.color\s*\}/)
|
|
653
|
-
// The
|
|
654
|
-
//
|
|
655
|
-
expect(c.clientJs).toMatch(/\{\s*
|
|
650
|
+
// The shorthand expands to `key: value` in one edit; the AST rewrite
|
|
651
|
+
// leaves the key alone and rewrites only the value position (#3260).
|
|
652
|
+
expect(c.clientJs).toMatch(/\{\s*color:\s*__bfItem\(\)\.color\s*\}/)
|
|
656
653
|
})
|
|
657
654
|
|
|
658
655
|
test('shorthand property survives nested destructure (object-in-array)', () => {
|
|
659
656
|
// Nested: tuple element destructured as object. Same shorthand
|
|
660
|
-
// pitfall as the flat case above — the AST
|
|
657
|
+
// pitfall as the flat case above — the AST rewrite finds the
|
|
661
658
|
// shorthand even though the binding path is deeper
|
|
662
659
|
// (`__bfItem()[1].color`).
|
|
663
660
|
const src = `
|
|
@@ -679,7 +676,7 @@ describe('nested destructuring in loop param', () => {
|
|
|
679
676
|
expectNoFatalErrors(c)
|
|
680
677
|
|
|
681
678
|
expect(c.clientJs).not.toMatch(/\{\s*__bfItem\(\)\[1\]\.color\s*\}/)
|
|
682
|
-
expect(c.clientJs).toMatch(/\{\s*
|
|
679
|
+
expect(c.clientJs).toMatch(/\{\s*color:\s*__bfItem\(\)\[1\]\.color\s*\}/)
|
|
683
680
|
})
|
|
684
681
|
})
|
|
685
682
|
|
|
@@ -182,4 +182,24 @@ describe('Solid-style wrap-by-default fallback for conditionals (#941)', () => {
|
|
|
182
182
|
const insertCount = (clientJs.match(/\binsert\s*\(/g) ?? []).length
|
|
183
183
|
expect(insertCount).toBe(2)
|
|
184
184
|
})
|
|
185
|
+
|
|
186
|
+
test('unrecognised call in a branch\'s text wraps in the branch bindEvents (#3266)', () => {
|
|
187
|
+
// The same `{v().text}` gets a createEffect outside the conditional
|
|
188
|
+
// (#939's fallback for top-level text). Inside a branch, the text
|
|
189
|
+
// effects were gated on `reactive` alone, so the branch kept its
|
|
190
|
+
// mount-time text until the condition flipped (#3266).
|
|
191
|
+
const source = `
|
|
192
|
+
'use client'
|
|
193
|
+
|
|
194
|
+
export function Card(props: any) {
|
|
195
|
+
const s = props.data.s
|
|
196
|
+
const v = () => s.get()
|
|
197
|
+
return <div>{v().kind === 'a' ? <p className="a">{v().text}</p> : <p className="b">{v().text}</p>}</div>
|
|
198
|
+
}
|
|
199
|
+
`
|
|
200
|
+
|
|
201
|
+
const clientJs = getClientJs(source, 'Card.tsx')
|
|
202
|
+
const branchTextEffects = clientJs.match(/__disposers\.push\(createDisposableEffect\(\(\) => \{ __bfw_s\d+\('s\d+', escapeTextOrNode\(v\(\)\.text\)\) \}\)\)/g) ?? []
|
|
203
|
+
expect(branchTextEffects).toHaveLength(2)
|
|
204
|
+
})
|
|
185
205
|
})
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every event handler typed on `HTMLBaseAttributes` (and the
|
|
3
|
+
* `BaseEventAttributes` it extends) must compile to a real DOM event name
|
|
4
|
+
* (#3273).
|
|
5
|
+
*
|
|
6
|
+
* The types (`html-types.ts`) and the compiler's JSX → DOM event-name
|
|
7
|
+
* conversion (`toDomEventName`) are two independent answers to "which events
|
|
8
|
+
* can a JSX element listen to". A typed prop whose lowered name is not a DOM
|
|
9
|
+
* event type-checks and compiles, but the listener never fires. This test
|
|
10
|
+
* joins the two: it reads the handler props from `html-types.ts` with a TS
|
|
11
|
+
* AST walk, compiles each one through `compileJSX`, and checks the emitted
|
|
12
|
+
* `addEventListener` name against the DOM lib's `HTMLElementEventMap`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { describe, test, expect } from 'bun:test'
|
|
16
|
+
import ts from 'typescript'
|
|
17
|
+
import { readFileSync } from 'node:fs'
|
|
18
|
+
import { resolve } from 'node:path'
|
|
19
|
+
import { compileJSX } from '..'
|
|
20
|
+
import { HonoAdapter } from '../../../adapter-hono/src/adapter/hono-adapter'
|
|
21
|
+
|
|
22
|
+
const HTML_TYPES_PATH = resolve(import.meta.dir, '../html-types.ts')
|
|
23
|
+
|
|
24
|
+
// Typed before this test existed, and not a DOM event: `dragexit` was
|
|
25
|
+
// dropped from the HTML spec and no browser fires it. Kept typed so existing
|
|
26
|
+
// code keeps compiling; this set may only shrink.
|
|
27
|
+
const NOT_A_DOM_EVENT = new Set(['onDragExit'])
|
|
28
|
+
|
|
29
|
+
function collectHandlerProps(): string[] {
|
|
30
|
+
const source = ts.createSourceFile(
|
|
31
|
+
HTML_TYPES_PATH,
|
|
32
|
+
readFileSync(HTML_TYPES_PATH, 'utf8'),
|
|
33
|
+
ts.ScriptTarget.Latest,
|
|
34
|
+
true,
|
|
35
|
+
)
|
|
36
|
+
const names: string[] = []
|
|
37
|
+
for (const stmt of source.statements) {
|
|
38
|
+
if (!ts.isInterfaceDeclaration(stmt)) continue
|
|
39
|
+
if (stmt.name.text !== 'BaseEventAttributes' && stmt.name.text !== 'HTMLBaseAttributes') continue
|
|
40
|
+
for (const member of stmt.members) {
|
|
41
|
+
if (!ts.isPropertySignature(member) || !ts.isIdentifier(member.name)) continue
|
|
42
|
+
if (/^on[A-Z]/.test(member.name.text)) names.push(member.name.text)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return names
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function collectDomEventNames(): Set<string> {
|
|
49
|
+
const libDir = resolve(require.resolve('typescript'), '..')
|
|
50
|
+
const program = ts.createProgram({
|
|
51
|
+
rootNames: [resolve(libDir, 'lib.dom.d.ts')],
|
|
52
|
+
options: { noLib: true },
|
|
53
|
+
})
|
|
54
|
+
const checker = program.getTypeChecker()
|
|
55
|
+
const dom = program.getSourceFile(resolve(libDir, 'lib.dom.d.ts'))!
|
|
56
|
+
const decl = dom.statements.find(
|
|
57
|
+
(s): s is ts.InterfaceDeclaration =>
|
|
58
|
+
ts.isInterfaceDeclaration(s) && s.name.text === 'HTMLElementEventMap',
|
|
59
|
+
)!
|
|
60
|
+
const type = checker.getTypeAtLocation(decl.name)
|
|
61
|
+
return new Set(checker.getPropertiesOfType(type).map(p => p.name))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function compiledEventName(prop: string): string | undefined {
|
|
65
|
+
const source = `
|
|
66
|
+
"use client"
|
|
67
|
+
export function Test() {
|
|
68
|
+
return <div ${prop}={() => {}}>x</div>
|
|
69
|
+
}
|
|
70
|
+
`
|
|
71
|
+
const result = compileJSX(source, 'Test.tsx', { adapter: new HonoAdapter() })
|
|
72
|
+
const js = result.files.find(f => f.type === 'clientJs')?.content ?? ''
|
|
73
|
+
return js.match(/addEventListener\('([^']+)'/)?.[1]
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
describe('typed JSX event handlers compile to DOM events (#3273)', () => {
|
|
77
|
+
const props = collectHandlerProps()
|
|
78
|
+
const domEvents = collectDomEventNames()
|
|
79
|
+
|
|
80
|
+
test('the handler set includes the pointer events from #3273', () => {
|
|
81
|
+
for (const name of [
|
|
82
|
+
'onPointerCancel',
|
|
83
|
+
'onPointerOver',
|
|
84
|
+
'onPointerOut',
|
|
85
|
+
'onGotPointerCapture',
|
|
86
|
+
'onLostPointerCapture',
|
|
87
|
+
]) {
|
|
88
|
+
expect(props).toContain(name)
|
|
89
|
+
}
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
for (const prop of props) {
|
|
93
|
+
if (NOT_A_DOM_EVENT.has(prop)) continue
|
|
94
|
+
test(`${prop} → a DOM event`, () => {
|
|
95
|
+
const eventName = compiledEventName(prop)
|
|
96
|
+
expect(eventName).toBeDefined()
|
|
97
|
+
expect(domEvents.has(eventName!)).toBe(true)
|
|
98
|
+
})
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
test('NOT_A_DOM_EVENT only lists typed props that really are not DOM events', () => {
|
|
102
|
+
for (const prop of NOT_A_DOM_EVENT) {
|
|
103
|
+
expect(props).toContain(prop)
|
|
104
|
+
expect(domEvents.has(compiledEventName(prop)!)).toBe(false)
|
|
105
|
+
}
|
|
106
|
+
})
|
|
107
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, test, expect } from 'bun:test'
|
|
2
|
+
import { escapeLineStatementSigil } from '../adapters/line-statement-text'
|
|
3
|
+
|
|
4
|
+
describe('escapeLineStatementSigil (#3311)', () => {
|
|
5
|
+
const esc = (t: string) => escapeLineStatementSigil(t, '%', "<%= '%' %>")
|
|
6
|
+
|
|
7
|
+
test('rewrites a sigil that leads the text, keeping its indentation', () => {
|
|
8
|
+
expect(esc('%y')).toBe("<%= '%' %>y")
|
|
9
|
+
expect(esc(' %y')).toBe(" <%= '%' %>y")
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
test('rewrites a sigil that leads any later line', () => {
|
|
13
|
+
expect(esc('a\n %b\nc')).toBe("a\n <%= '%' %>b\nc")
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
test('leaves a sigil that does not lead its line', () => {
|
|
17
|
+
expect(esc('50%')).toBe('50%')
|
|
18
|
+
expect(esc('a % b')).toBe('a % b')
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
test('rewrites only the leading sigil, once', () => {
|
|
22
|
+
expect(esc('%%')).toBe("<%= '%' %>%")
|
|
23
|
+
expect(escapeLineStatementSigil(': :x', ':', "<: ':' :>")).toBe("<: ':' :> :x")
|
|
24
|
+
})
|
|
25
|
+
})
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { describe, test, expect } from 'bun:test'
|
|
2
|
+
import { compileJSX, lookupLiteralConst, type ComponentIR } from '../index'
|
|
3
|
+
import { TestAdapter } from '../adapters/test-adapter'
|
|
4
|
+
|
|
5
|
+
function constantsOf(src: string): ComponentIR['metadata']['localConstants'] {
|
|
6
|
+
const result = compileJSX(src.trimStart(), 'T.tsx', { adapter: new TestAdapter(), outputIR: true })
|
|
7
|
+
const irFile = result.files.find(f => f.type === 'ir')
|
|
8
|
+
if (!irFile) throw new Error('no IR')
|
|
9
|
+
return (JSON.parse(irFile.content) as ComponentIR).metadata.localConstants
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
describe('lookupLiteralConst (#3312)', () => {
|
|
13
|
+
const consts = constantsOf(`
|
|
14
|
+
const enabled = false
|
|
15
|
+
const limit = -2
|
|
16
|
+
const missing = null
|
|
17
|
+
export function C() {
|
|
18
|
+
const on = true
|
|
19
|
+
const mode = 'on'
|
|
20
|
+
const ratio = 1.5
|
|
21
|
+
const multiline = 'a\\nb'
|
|
22
|
+
const derived = mode + '!'
|
|
23
|
+
return <div data-x={on && enabled ? mode : String(limit + ratio) + derived + multiline} data-m={missing ?? 'm'}>x</div>
|
|
24
|
+
}
|
|
25
|
+
`)
|
|
26
|
+
const never = () => false
|
|
27
|
+
|
|
28
|
+
test('resolves boolean, number, string and null literals at module and function scope', () => {
|
|
29
|
+
expect(lookupLiteralConst('on', consts, never)).toEqual({ kind: 'boolean', text: 'true' })
|
|
30
|
+
expect(lookupLiteralConst('enabled', consts, never)).toEqual({ kind: 'boolean', text: 'false' })
|
|
31
|
+
expect(lookupLiteralConst('limit', consts, never)).toEqual({ kind: 'number', text: '-2' })
|
|
32
|
+
expect(lookupLiteralConst('ratio', consts, never)).toEqual({ kind: 'number', text: '1.5' })
|
|
33
|
+
expect(lookupLiteralConst('mode', consts, never)).toEqual({ kind: 'string', text: 'on' })
|
|
34
|
+
expect(lookupLiteralConst('multiline', consts, never)).toEqual({ kind: 'string', text: 'a\nb' })
|
|
35
|
+
expect(lookupLiteralConst('missing', consts, never)).toEqual({ kind: 'null', text: 'null' })
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
test('declines a non-literal initializer and an unknown name', () => {
|
|
39
|
+
expect(lookupLiteralConst('derived', consts, never)).toBeNull()
|
|
40
|
+
expect(lookupLiteralConst('unknown', consts, never)).toBeNull()
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
test('declines a name the caller reports as shadowed', () => {
|
|
44
|
+
expect(lookupLiteralConst('on', consts, n => n === 'on')).toBeNull()
|
|
45
|
+
})
|
|
46
|
+
})
|
|
@@ -411,35 +411,82 @@ describe('.map() row: a nested scope that shadows the loop param fails loudly in
|
|
|
411
411
|
})
|
|
412
412
|
})
|
|
413
413
|
|
|
414
|
-
describe('destructured loop-param path (rewriteLoopBindingRefs)
|
|
415
|
-
// `rewriteLoopBindingRefs`
|
|
416
|
-
//
|
|
417
|
-
//
|
|
418
|
-
//
|
|
419
|
-
// the
|
|
420
|
-
//
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
// destructured-binding machinery, which is a larger, separate change.
|
|
424
|
-
// Drop `.todo` once `rewriteLoopBindingRefs` gets the same AST-aware
|
|
425
|
-
// treatment `rewriteIdentifierAsAccessor` got here.
|
|
426
|
-
test.todo('an object-literal key matching a destructured binding name is left alone', () => {
|
|
427
|
-
const source = `
|
|
414
|
+
describe('destructured loop-param path (rewriteLoopBindingRefs) shares the plain-param AST rewrite (#3260)', () => {
|
|
415
|
+
// `rewriteLoopBindingRefs` rewrites a DESTRUCTURED loop param's bindings
|
|
416
|
+
// (`({ color, label }) => ...`) to `__bfItem().color` etc. It used a
|
|
417
|
+
// \bname\b-style regex plus a shorthand-only AST pre-pass (#1244), so an
|
|
418
|
+
// explicit object-literal key or a member name spelling a binding name was
|
|
419
|
+
// corrupted the same way #3239 described for the plain param. It now runs
|
|
420
|
+
// the same AST walk as `rewriteIdentifierAsAccessor`.
|
|
421
|
+
function compileRow(row: string, item = "{ color: 'red', label: 'a', onPick: () => 1, extra: 1 }", pattern = '{ color, label }'): string {
|
|
422
|
+
return getClientJs(`
|
|
428
423
|
'use client'
|
|
429
424
|
import { createSignal } from '@barefootjs/client'
|
|
425
|
+
const THEME = { color: 'blue' }
|
|
430
426
|
export function App() {
|
|
431
|
-
const [items] = createSignal([{
|
|
427
|
+
const [items] = createSignal([${item}])
|
|
432
428
|
return (
|
|
433
429
|
<div>
|
|
434
|
-
{items().map(({
|
|
435
|
-
|
|
430
|
+
{items().map((${pattern}) => (
|
|
431
|
+
${row}
|
|
436
432
|
))}
|
|
437
433
|
</div>
|
|
438
434
|
)
|
|
439
435
|
}
|
|
440
|
-
`
|
|
441
|
-
|
|
436
|
+
`)
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
test('an object-literal key matching a destructured binding name is left alone', () => {
|
|
440
|
+
const js = compileRow('<b key={label}>{JSON.stringify({ color: 1 })}</b>')
|
|
442
441
|
assertParses(js)
|
|
443
442
|
expect(js).toContain('JSON.stringify({ color: 1 })')
|
|
444
443
|
})
|
|
444
|
+
|
|
445
|
+
test('a member name matching a destructured binding name is left alone', () => {
|
|
446
|
+
const js = compileRow('<b key={label}>{THEME.color}</b>')
|
|
447
|
+
assertParses(js)
|
|
448
|
+
expect(js).toContain('THEME.color')
|
|
449
|
+
expect(js).not.toContain('THEME.__bfItem()')
|
|
450
|
+
})
|
|
451
|
+
|
|
452
|
+
test('explicit key with a matching value `{ color: color }` rewrites only the value', () => {
|
|
453
|
+
const js = compileRow('<b key={label}>{JSON.stringify({ color: color })}</b>')
|
|
454
|
+
assertParses(js)
|
|
455
|
+
expect(js).toContain('JSON.stringify({ color: __bfItem().color })')
|
|
456
|
+
})
|
|
457
|
+
|
|
458
|
+
test('shorthand `{ color }` still expands to `{ color: __bfItem().color }` (#1244)', () => {
|
|
459
|
+
const js = compileRow('<b key={label}>{JSON.stringify({ color })}</b>')
|
|
460
|
+
assertParses(js)
|
|
461
|
+
expect(js).toContain('JSON.stringify({ color: __bfItem().color })')
|
|
462
|
+
})
|
|
463
|
+
|
|
464
|
+
test('a destructured binding called as a function becomes a call on the item field', () => {
|
|
465
|
+
// Unlike the plain param, `onPick()` is not an accessor call already —
|
|
466
|
+
// it calls the item's `onPick` field — so the callee is rewritten.
|
|
467
|
+
const js = compileRow('<b key={label}>{String(onPick())}</b>', undefined, '{ label, onPick }')
|
|
468
|
+
assertParses(js)
|
|
469
|
+
expect(js).toContain('String(__bfItem().onPick())')
|
|
470
|
+
})
|
|
471
|
+
|
|
472
|
+
test('a rest binding still renders through its residual form', () => {
|
|
473
|
+
const js = compileRow('<b key={label}>{JSON.stringify(rest)}</b>', undefined, '{ label, ...rest }')
|
|
474
|
+
assertParses(js)
|
|
475
|
+
expect(js).toContain('JSON.stringify((({ label: __bfR0, ...__bfRest }) => __bfRest)(__bfItem()))')
|
|
476
|
+
})
|
|
477
|
+
|
|
478
|
+
test('a named function expression shadows only its own name; other bindings inside are still rewritten', () => {
|
|
479
|
+
const js = compileRow('<b key={label}>{String((function color() { return label })())}</b>')
|
|
480
|
+
assertParses(js)
|
|
481
|
+
expect(js).toContain('(function color() { return __bfItem().label })()')
|
|
482
|
+
})
|
|
483
|
+
|
|
484
|
+
test('a nested function declaration shadowing a binding fails to parse instead of calling the item field', () => {
|
|
485
|
+
// Keeping `function color() {}` while rewriting its call to
|
|
486
|
+
// `__bfItem().color()` would compile and then call the wrong value at
|
|
487
|
+
// hydration. Rewriting the declaration name too breaks it loudly, as the
|
|
488
|
+
// old destructured regex did (#3260 review).
|
|
489
|
+
const js = compileRow("<b key={label}>{(() => { function color() { return 'blue' } return color() })()}</b>")
|
|
490
|
+
assertDoesNotParse(js)
|
|
491
|
+
})
|
|
445
492
|
})
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { describe, test, expect } from 'bun:test'
|
|
2
|
+
import { analyzeComponent } from '../analyzer'
|
|
3
|
+
import { parseExpression } from '../expression-parser'
|
|
4
|
+
import {
|
|
5
|
+
attrValueMayBeNullish,
|
|
6
|
+
collectNullableSignalGetters,
|
|
7
|
+
collectNullishAttrContext,
|
|
8
|
+
nullableSignalAttrGetter,
|
|
9
|
+
} from '../nullable-signal-attr'
|
|
10
|
+
import type { ComponentIR } from '../types'
|
|
11
|
+
|
|
12
|
+
function nullableGetters(decls: string): Set<string> {
|
|
13
|
+
const source = `
|
|
14
|
+
'use client'
|
|
15
|
+
import { createSignal } from '@barefootjs/client'
|
|
16
|
+
export function C() {
|
|
17
|
+
${decls}
|
|
18
|
+
return <p>x</p>
|
|
19
|
+
}
|
|
20
|
+
`
|
|
21
|
+
const metadata = analyzeComponent(source, 'C.tsx')
|
|
22
|
+
return collectNullableSignalGetters({ metadata } as unknown as ComponentIR)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('collectNullableSignalGetters (#3304)', () => {
|
|
26
|
+
test('a zero-arg typed signal is nullable', () => {
|
|
27
|
+
expect([...nullableGetters('const [a] = createSignal<number>()')]).toEqual(['a'])
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
test('a type admitting undefined or null is nullable, whatever the initial value', () => {
|
|
31
|
+
expect([...nullableGetters(`
|
|
32
|
+
const [a] = createSignal<string | undefined>(undefined)
|
|
33
|
+
const [b] = createSignal<string | null>('x')
|
|
34
|
+
`)].sort()).toEqual(['a', 'b'])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
test('an untyped literal undefined or null initial value is nullable', () => {
|
|
38
|
+
expect([...nullableGetters(`
|
|
39
|
+
const [a] = createSignal(undefined)
|
|
40
|
+
const [b] = createSignal(null)
|
|
41
|
+
`)].sort()).toEqual(['a', 'b'])
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
test('a non-nullable typed or inferred signal is not', () => {
|
|
45
|
+
expect([...nullableGetters(`
|
|
46
|
+
const [a] = createSignal('x')
|
|
47
|
+
const [b] = createSignal<number>(0)
|
|
48
|
+
`)]).toEqual([])
|
|
49
|
+
})
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
describe('nullableSignalAttrGetter (#3304)', () => {
|
|
53
|
+
const nullable = new Set(['s'])
|
|
54
|
+
|
|
55
|
+
test('matches a bare zero-arg read of a nullable signal', () => {
|
|
56
|
+
expect(nullableSignalAttrGetter(parseExpression('s()'), nullable)).toBe('s')
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
test('does not match any other shape', () => {
|
|
60
|
+
for (const expr of ['t()', 's', 's(1)', 's()?.x', "s() ?? 'a'", 'a ? s() : b']) {
|
|
61
|
+
expect(nullableSignalAttrGetter(parseExpression(expr), nullable)).toBeNull()
|
|
62
|
+
}
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
describe('attrValueMayBeNullish (#3322)', () => {
|
|
67
|
+
const source = `
|
|
68
|
+
'use client'
|
|
69
|
+
import { createMemo, createSignal } from '@barefootjs/client'
|
|
70
|
+
export function C() {
|
|
71
|
+
const [s] = createSignal<string | undefined>(undefined)
|
|
72
|
+
const [t] = createSignal('x')
|
|
73
|
+
const [user] = createSignal<{ name?: string }>({})
|
|
74
|
+
const label = createMemo(() => s())
|
|
75
|
+
const nested = createMemo(() => label())
|
|
76
|
+
const plain = createMemo(() => t())
|
|
77
|
+
const typed = createMemo<string | undefined>(() => t())
|
|
78
|
+
const loop = createMemo(() => loop())
|
|
79
|
+
return <p>x</p>
|
|
80
|
+
}
|
|
81
|
+
`
|
|
82
|
+
const ctx = collectNullishAttrContext({ metadata: analyzeComponent(source, 'C.tsx') } as unknown as ComponentIR)
|
|
83
|
+
const mayBe = (expr: string, shadowed: string[] = []) =>
|
|
84
|
+
attrValueMayBeNullish(parseExpression(expr), ctx, name => shadowed.includes(name))
|
|
85
|
+
|
|
86
|
+
test('a nullable signal or a memo over one, however deep', () => {
|
|
87
|
+
for (const expr of ['s()', 'label()', 'nested()', 'typed()']) expect(mayBe(expr)).toBe(true)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
test('a memo over a present value, or a self-referencing memo, is not', () => {
|
|
91
|
+
for (const expr of ['t()', 'plain()', 'loop()']) expect(mayBe(expr)).toBe(false)
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
test('an optional member read, or a member of a nullable value', () => {
|
|
95
|
+
expect(mayBe('user()?.name')).toBe(true)
|
|
96
|
+
expect(mayBe('label().length')).toBe(true)
|
|
97
|
+
expect(mayBe('user().name')).toBe(false)
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
test('a ternary or logical operand the result can be', () => {
|
|
101
|
+
expect(mayBe("t() ? s() : 'a'")).toBe(true)
|
|
102
|
+
expect(mayBe("t() ? 'a' : label()")).toBe(true)
|
|
103
|
+
expect(mayBe("s() ? 'a' : 'b'")).toBe(false)
|
|
104
|
+
expect(mayBe("s() ?? 'a'")).toBe(false)
|
|
105
|
+
expect(mayBe("t() || s()")).toBe(true)
|
|
106
|
+
expect(mayBe("s() && 'a'")).toBe(true)
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
test('literal undefined / null, and nothing else', () => {
|
|
110
|
+
expect(mayBe('undefined')).toBe(true)
|
|
111
|
+
expect(mayBe('null')).toBe(true)
|
|
112
|
+
expect(mayBe("''")).toBe(false)
|
|
113
|
+
expect(mayBe('0')).toBe(false)
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
test('a getter a loop binding shadows is not the signal or memo', () => {
|
|
117
|
+
expect(mayBe('label()', ['label'])).toBe(false)
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
test("a memo's body reads its getters where the memo is declared, not where it is read", () => {
|
|
121
|
+
expect(mayBe('label()', ['s'])).toBe(true)
|
|
122
|
+
expect(mayBe('nested()', ['s', 'label'])).toBe(true)
|
|
123
|
+
})
|
|
124
|
+
})
|