@barefootjs/jsx 0.39.5 → 0.39.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.
- package/dist/adapters/array-method.d.ts +93 -0
- package/dist/adapters/array-method.d.ts.map +1 -0
- package/dist/adapters/attr-plan.d.ts +142 -0
- package/dist/adapters/attr-plan.d.ts.map +1 -0
- package/dist/adapters/boolean-result.d.ts +84 -9
- package/dist/adapters/boolean-result.d.ts.map +1 -1
- package/dist/adapters/callback-method.d.ts +153 -0
- package/dist/adapters/callback-method.d.ts.map +1 -0
- package/dist/adapters/component-props.d.ts +99 -0
- package/dist/adapters/component-props.d.ts.map +1 -0
- package/dist/adapters/component-tree.d.ts +25 -0
- package/dist/adapters/component-tree.d.ts.map +1 -0
- package/dist/adapters/computed-const.d.ts +52 -0
- package/dist/adapters/computed-const.d.ts.map +1 -0
- package/dist/adapters/dangerous-inner-html.d.ts +10 -0
- package/dist/adapters/dangerous-inner-html.d.ts.map +1 -1
- package/dist/adapters/element-shell.d.ts +44 -0
- package/dist/adapters/element-shell.d.ts.map +1 -0
- package/dist/adapters/interface.d.ts +2 -0
- package/dist/adapters/interface.d.ts.map +1 -1
- package/dist/adapters/literal-value.d.ts +22 -0
- package/dist/adapters/literal-value.d.ts.map +1 -0
- package/dist/adapters/loop-plan.d.ts +53 -0
- package/dist/adapters/loop-plan.d.ts.map +1 -0
- package/dist/adapters/prop-classes.d.ts +37 -0
- package/dist/adapters/prop-classes.d.ts.map +1 -0
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/augment-inherited-props.d.ts +7 -0
- package/dist/augment-inherited-props.d.ts.map +1 -1
- package/dist/expression-parser.d.ts +38 -0
- package/dist/expression-parser.d.ts.map +1 -1
- package/dist/fold-render-reassignments.d.ts +43 -0
- package/dist/fold-render-reassignments.d.ts.map +1 -0
- package/dist/free-refs.d.ts +9 -0
- package/dist/free-refs.d.ts.map +1 -1
- package/dist/index.d.ts +23 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3954 -2401
- package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
- package/dist/ir-to-client-js/csr-substitute.d.ts +0 -13
- package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
- package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
- package/dist/ir-to-client-js/html-template.d.ts +9 -10
- package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
- package/dist/ir-to-client-js/index.d.ts.map +1 -1
- package/dist/ir-to-client-js/plan/declaration-emit.d.ts +5 -0
- package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
- package/dist/ir-to-client-js/prop-handling.d.ts +11 -12
- package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
- package/dist/ir-to-client-js/utils.d.ts +13 -0
- package/dist/ir-to-client-js/utils.d.ts.map +1 -1
- package/dist/jsx-to-ir.d.ts +465 -1
- package/dist/jsx-to-ir.d.ts.map +1 -1
- package/dist/nullable-signal-attr.d.ts +22 -2
- package/dist/nullable-signal-attr.d.ts.map +1 -1
- package/dist/props-binding.d.ts +34 -5
- package/dist/props-binding.d.ts.map +1 -1
- package/dist/relocate.d.ts +16 -0
- package/dist/relocate.d.ts.map +1 -1
- package/dist/ssr-seed-plan.d.ts +0 -6
- package/dist/ssr-seed-plan.d.ts.map +1 -1
- package/dist/types.d.ts +54 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
- package/src/__tests__/action-accessor.test.ts +6 -24
- package/src/__tests__/array-method-catalogue.test.ts +99 -0
- package/src/__tests__/attr-plan.test.ts +121 -0
- package/src/__tests__/binding-scope-ratchet.test.ts +12 -12
- package/src/__tests__/block-memo-type.test.ts +51 -0
- package/src/__tests__/boolean-result-expr.test.ts +106 -0
- package/src/__tests__/boolean-result.test.ts +34 -1
- package/src/__tests__/callback-method.test.ts +264 -0
- package/src/__tests__/client-only-date-lowering.test.ts +2 -2
- package/src/__tests__/component-props.test.ts +148 -0
- package/src/__tests__/computed-const.test.ts +101 -0
- package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
- package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
- package/src/__tests__/element-shell.test.ts +78 -0
- package/src/__tests__/fold-render-reassignments.test.ts +96 -0
- package/src/__tests__/inlinable-local-method-call.test.ts +81 -0
- package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
- package/src/__tests__/loop-plan.test.ts +104 -0
- package/src/__tests__/map-call-decisions.test.ts +521 -0
- package/src/__tests__/memo-body-expr.test.ts +120 -0
- package/src/__tests__/nullable-signal-attr.test.ts +45 -0
- package/src/__tests__/prop-handling.test.ts +35 -16
- package/src/__tests__/props-alias-const.test.ts +65 -0
- package/src/__tests__/signal-prop-seed.test.ts +90 -0
- package/src/__tests__/ssr-seed-plan.test.ts +54 -1
- package/src/__tests__/static-template-reachability.test.ts +137 -0
- package/src/adapters/array-method.ts +193 -0
- package/src/adapters/attr-plan.ts +228 -0
- package/src/adapters/boolean-result.ts +208 -12
- package/src/adapters/callback-method.ts +363 -0
- package/src/adapters/component-props.ts +144 -0
- package/src/adapters/component-tree.ts +118 -0
- package/src/adapters/computed-const.ts +185 -0
- package/src/adapters/dangerous-inner-html.ts +33 -0
- package/src/adapters/element-shell.ts +160 -0
- package/src/adapters/interface.ts +8 -0
- package/src/adapters/literal-value.ts +36 -0
- package/src/adapters/loop-plan.ts +88 -0
- package/src/adapters/prop-classes.ts +73 -0
- package/src/analyzer.ts +271 -82
- package/src/augment-inherited-props.ts +12 -0
- package/src/expression-parser.ts +537 -374
- package/src/fold-render-reassignments.ts +314 -0
- package/src/free-refs.ts +49 -0
- package/src/index.ts +61 -3
- package/src/ir-to-client-js/compute-inlinability.ts +93 -17
- package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
- package/src/ir-to-client-js/csr-substitute.ts +13 -35
- package/src/ir-to-client-js/emit-registration.ts +3 -2
- package/src/ir-to-client-js/html-template.ts +26 -70
- package/src/ir-to-client-js/index.ts +3 -2
- package/src/ir-to-client-js/init-declarations.ts +1 -1
- package/src/ir-to-client-js/plan/build-declaration-emit.ts +25 -51
- package/src/ir-to-client-js/plan/declaration-emit.ts +5 -0
- package/src/ir-to-client-js/prop-handling.ts +13 -54
- package/src/ir-to-client-js/rewrite-destructured-props.ts +6 -5
- package/src/ir-to-client-js/stringify/declaration-emit.ts +1 -1
- package/src/ir-to-client-js/utils.ts +11 -0
- package/src/jsx-to-ir.ts +1346 -1022
- package/src/nullable-signal-attr.ts +85 -4
- package/src/props-binding.ts +100 -5
- package/src/relocate.ts +40 -8
- package/src/ssr-seed-plan.ts +18 -6
- package/src/types.ts +50 -2
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// A template reads a computed const as its initializer (#3494): the shared
|
|
2
|
+
// substitution every template adapter applies before lowering an
|
|
3
|
+
// expression, against metadata built by the real pipeline.
|
|
4
|
+
|
|
5
|
+
import { describe, test, expect } from 'bun:test'
|
|
6
|
+
import { analyzeComponent } from '../analyzer'
|
|
7
|
+
import { buildMetadata } from '../compiler'
|
|
8
|
+
import { parseExpression, stringifyParsedExpr } from '../expression-parser'
|
|
9
|
+
import { computedConstContext, inlineComputedConsts } from '../adapters/computed-const'
|
|
10
|
+
|
|
11
|
+
function inliner(source: string, shadowed: readonly string[] = [], adapterBound: readonly string[] = []) {
|
|
12
|
+
const metadata = buildMetadata(analyzeComponent(source, 'test.tsx'))
|
|
13
|
+
const ctx = computedConstContext(metadata, name => shadowed.includes(name), name => adapterBound.includes(name))
|
|
14
|
+
return (expr: string) => stringifyParsedExpr(inlineComputedConsts(parseExpression(expr), ctx))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('inlineComputedConsts (#3494)', () => {
|
|
18
|
+
const source = `
|
|
19
|
+
'use client'
|
|
20
|
+
import { createSignal, useContext, createContext } from '@barefootjs/client'
|
|
21
|
+
const Theme = createContext('light')
|
|
22
|
+
function makeLabel() { return 'x' }
|
|
23
|
+
export function C(props: { v: string; n: number; label?: string; labels: Record<string, string> }) {
|
|
24
|
+
const [count] = createSignal(1)
|
|
25
|
+
const cls = 'btn ' + props.v
|
|
26
|
+
const wide = cls + ' w-full'
|
|
27
|
+
const twice = props.n * 2
|
|
28
|
+
const doubled = count() * 2
|
|
29
|
+
const fallback = props.label ?? 'Default'
|
|
30
|
+
const keys = Object.keys(props.labels)
|
|
31
|
+
const total = 5
|
|
32
|
+
const opaque = makeLabel()
|
|
33
|
+
const theme = useContext(Theme)
|
|
34
|
+
const format = (s: string) => s.trim()
|
|
35
|
+
return <p class={wide}>{twice}{doubled}{fallback}{keys.length}{total}{opaque}{theme}{format('a')}</p>
|
|
36
|
+
}
|
|
37
|
+
`
|
|
38
|
+
|
|
39
|
+
test('a const computed from props reads as its initializer, through a const of a const', () => {
|
|
40
|
+
const inline = inliner(source)
|
|
41
|
+
expect(inline('twice')).toBe('props.n * 2')
|
|
42
|
+
expect(inline('wide')).toBe('"btn " + props.v + " w-full"')
|
|
43
|
+
expect(inline('fallback')).toBe('props.label ?? "Default"')
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
test('a signal read stays a getter call inside the initializer', () => {
|
|
47
|
+
expect(inliner(source)('doubled')).toBe('count() * 2')
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
test('an initializer no template lowers is still substituted, for the adapter to refuse', () => {
|
|
51
|
+
expect(inliner(source)('keys.length')).toBe('Object.keys(props.labels).length')
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
test('a literal const, an opaque accessor, a context consumer and a function stay as read', () => {
|
|
55
|
+
const inline = inliner(source)
|
|
56
|
+
for (const name of ['total', 'opaque', 'theme']) expect(inline(name)).toBe(name)
|
|
57
|
+
expect(inline("format('a')")).toBe('format("a")')
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
test('a name a loop row binds at the read site is the row, not the const', () => {
|
|
61
|
+
expect(inliner(source, ['twice'])('twice')).toBe('twice')
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
test('an initializer whose free name the read site rebinds is left alone', () => {
|
|
65
|
+
expect(inliner(source, ['props'])('twice')).toBe('twice')
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
test('a const the adapter binds itself stays as read, also inside another initializer', () => {
|
|
69
|
+
const inline = inliner(source, [], ['cls'])
|
|
70
|
+
expect(inline('cls')).toBe('cls')
|
|
71
|
+
expect(inline('wide')).toBe('cls + " w-full"')
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
test('a callback param shadowing the name keeps the param', () => {
|
|
75
|
+
expect(inliner(source)('rows.map(twice => twice + 1)')).toBe('rows.map(twice => twice + 1)')
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
test('a props destructure binding stays as read: the adapter binds it as a props param', () => {
|
|
79
|
+
const inline = inliner(`
|
|
80
|
+
function A(props: { value: number; label?: string }) {
|
|
81
|
+
const { value, label: text = 'none' } = props
|
|
82
|
+
const shown = text + '!'
|
|
83
|
+
return <div>{value}{text}{shown}</div>
|
|
84
|
+
}
|
|
85
|
+
export { A }
|
|
86
|
+
`)
|
|
87
|
+
expect(inline('text')).toBe('text')
|
|
88
|
+
expect(inline('value')).toBe('value')
|
|
89
|
+
expect(inline('shown')).toBe('text + "!"')
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
test('a const named like a prop with no default of its own still reads as its initializer', () => {
|
|
93
|
+
const inline = inliner(`
|
|
94
|
+
export function B(props: { label?: string }) {
|
|
95
|
+
const label = props.label ?? 'Default'
|
|
96
|
+
return <p>{label}</p>
|
|
97
|
+
}
|
|
98
|
+
`)
|
|
99
|
+
expect(inline('label')).toBe('props.label ?? "Default"')
|
|
100
|
+
})
|
|
101
|
+
})
|
|
@@ -83,7 +83,7 @@ describe('delegated-handler preamble splicing (BUG-3 / BUG-4)', () => {
|
|
|
83
83
|
expect(js.split('cells.push')).toHaveLength(4) // three occurrences total
|
|
84
84
|
|
|
85
85
|
// The item guard still gates the handler call.
|
|
86
|
-
expect(handler).toContain('if (t) {')
|
|
86
|
+
expect(handler).toContain('if (t !== undefined) {')
|
|
87
87
|
expect(handler).toContain('(() => del(t.id))(__bfEvt)')
|
|
88
88
|
})
|
|
89
89
|
|
|
@@ -107,8 +107,8 @@ describe('delegated-handler preamble splicing (BUG-3 / BUG-4)', () => {
|
|
|
107
107
|
expect(handler).not.toContain('t().')
|
|
108
108
|
|
|
109
109
|
// Guard-order (part 3): the preamble line and the handler call both
|
|
110
|
-
// land AFTER `if (t) {`, i.e. inside the item-null guard.
|
|
111
|
-
const guardIdx = handler.indexOf('if (t) {')
|
|
110
|
+
// land AFTER `if (t !== undefined) {`, i.e. inside the item-null guard.
|
|
111
|
+
const guardIdx = handler.indexOf('if (t !== undefined) {')
|
|
112
112
|
const preambleIdx = handler.indexOf('const label = t.name')
|
|
113
113
|
const callIdx = handler.indexOf('(() => del(label))(__bfEvt)')
|
|
114
114
|
expect(guardIdx).toBeGreaterThanOrEqual(0)
|
|
@@ -143,7 +143,7 @@ describe('delegated-handler preamble splicing (BUG-3 / BUG-4)', () => {
|
|
|
143
143
|
expect(handler).toContain('(() => del(label))(__bfEvt)')
|
|
144
144
|
|
|
145
145
|
// Guard-order holds for the bindings-branch shape too.
|
|
146
|
-
const guardIdx = handler.indexOf('if (__bfLoopItem) {')
|
|
146
|
+
const guardIdx = handler.indexOf('if (__bfLoopItem !== undefined) {')
|
|
147
147
|
const preambleIdx = handler.indexOf('const label = name')
|
|
148
148
|
const callIdx = handler.indexOf('(() => del(label))(__bfEvt)')
|
|
149
149
|
expect(guardIdx).toBeGreaterThanOrEqual(0)
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The helpers the eight DSL template adapters (Blade, ERB, Jinja,
|
|
3
|
+
* MiniJinja, Mojolicious, Pebble, Twig, Xslate) used to carry one copy each
|
|
4
|
+
* of, now shared from `src/adapters/` (#3475). The adapters' own suites
|
|
5
|
+
* cover the lowering they drive; these pin each helper on its own.
|
|
6
|
+
*/
|
|
7
|
+
import { describe, test, expect } from 'bun:test'
|
|
8
|
+
import { compileJSX } from '../compiler'
|
|
9
|
+
import { TestAdapter } from '../adapters/test-adapter'
|
|
10
|
+
import { isExplicitStringCall } from '../adapters/boolean-result'
|
|
11
|
+
import { collectImportedLoopChildComponentErrors, hasClientInteractivity } from '../adapters/component-tree'
|
|
12
|
+
import { isBareStringLiteral, isLiteralIndex, isStringTypeInfo } from '../adapters/literal-value'
|
|
13
|
+
import { collectBooleanTypedProps, collectNullableOptionalProps, isBooleanTypedPropRef } from '../adapters/prop-classes'
|
|
14
|
+
import { childTemplateName } from '../adapters/component-props'
|
|
15
|
+
import { parseExpression } from '../expression-parser'
|
|
16
|
+
import type { ComponentIR } from '../types'
|
|
17
|
+
|
|
18
|
+
function compileToIR(source: string, file = 'demo.tsx'): ComponentIR {
|
|
19
|
+
const result = compileJSX(source, file, { adapter: new TestAdapter(), outputIR: true })
|
|
20
|
+
const ir = result.files.find(f => f.type === 'ir')
|
|
21
|
+
if (!ir) throw new Error('No IR output')
|
|
22
|
+
return JSON.parse(ir.content) as ComponentIR
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('isExplicitStringCall', () => {
|
|
26
|
+
test('a one-argument String(x) call is explicit', () => {
|
|
27
|
+
expect(isExplicitStringCall('String(props.checked ?? false)')).toBe(true)
|
|
28
|
+
expect(isExplicitStringCall(' String(on()) ')).toBe(true)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
test('other arities, other callees and non-calls are not', () => {
|
|
32
|
+
expect(isExplicitStringCall('String()')).toBe(false)
|
|
33
|
+
expect(isExplicitStringCall('String(a, b)')).toBe(false)
|
|
34
|
+
expect(isExplicitStringCall('Number(x)')).toBe(false)
|
|
35
|
+
expect(isExplicitStringCall('obj.String(x)')).toBe(false)
|
|
36
|
+
expect(isExplicitStringCall('checked()')).toBe(false)
|
|
37
|
+
})
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
describe('literal-value', () => {
|
|
41
|
+
test('isStringTypeInfo holds only for the string primitive', () => {
|
|
42
|
+
expect(isStringTypeInfo({ kind: 'primitive', raw: 'string', primitive: 'string' })).toBe(true)
|
|
43
|
+
expect(isStringTypeInfo({ kind: 'primitive', raw: 'number', primitive: 'number' })).toBe(false)
|
|
44
|
+
expect(isStringTypeInfo(undefined)).toBe(false)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
test('isBareStringLiteral accepts a single- or double-quoted literal only', () => {
|
|
48
|
+
expect(isBareStringLiteral("'a'")).toBe(true)
|
|
49
|
+
expect(isBareStringLiteral(' "b" ')).toBe(true)
|
|
50
|
+
expect(isBareStringLiteral('`c`')).toBe(false)
|
|
51
|
+
expect(isBareStringLiteral('0')).toBe(false)
|
|
52
|
+
expect(isBareStringLiteral(undefined)).toBe(false)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test('isLiteralIndex holds for a number or string literal index, not a variable or other literal', () => {
|
|
56
|
+
expect(isLiteralIndex(parseExpression('0'))).toBe(true)
|
|
57
|
+
expect(isLiteralIndex(parseExpression("'k'"))).toBe(true)
|
|
58
|
+
expect(isLiteralIndex(parseExpression('size'))).toBe(false)
|
|
59
|
+
expect(isLiteralIndex(parseExpression('true'))).toBe(false)
|
|
60
|
+
})
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
describe('prop-classes', () => {
|
|
64
|
+
const ir = compileToIR(`
|
|
65
|
+
type Props = { active: boolean; label?: string; rows?: number; tone: string; count?: number; items: string[]; flag?: boolean }
|
|
66
|
+
export function Demo({ active, label, rows, tone, count = 0, items, flag }: Props) {
|
|
67
|
+
return <div data-active={active} data-flag={flag}>{label}{rows}{tone}{count}{items.length}</div>
|
|
68
|
+
}
|
|
69
|
+
`)
|
|
70
|
+
|
|
71
|
+
test('collectBooleanTypedProps collects the boolean-typed props', () => {
|
|
72
|
+
expect([...collectBooleanTypedProps(ir)].sort()).toEqual(['active', 'flag'])
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
test('collectNullableOptionalProps collects no-default props that are optional or non-primitive', () => {
|
|
76
|
+
// `count` has a default; `active` / `tone` are required primitives.
|
|
77
|
+
expect([...collectNullableOptionalProps(ir)].sort()).toEqual(['flag', 'items', 'label', 'rows'])
|
|
78
|
+
})
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
describe('component-tree', () => {
|
|
82
|
+
test('hasClientInteractivity: a signal makes the component interactive, propless static markup does not', () => {
|
|
83
|
+
const reactive = compileToIR(`
|
|
84
|
+
'use client'
|
|
85
|
+
import { createSignal } from '@barefootjs/client'
|
|
86
|
+
export function Counter() {
|
|
87
|
+
const [n, setN] = createSignal(0)
|
|
88
|
+
return <button onClick={() => setN(n() + 1)}>{n()}</button>
|
|
89
|
+
}
|
|
90
|
+
`)
|
|
91
|
+
// A component that reads props still needs init (the analyzer's
|
|
92
|
+
// `needsInit`), so the inert case takes none.
|
|
93
|
+
const inert = compileToIR(`
|
|
94
|
+
export function Label() {
|
|
95
|
+
return <span>static</span>
|
|
96
|
+
}
|
|
97
|
+
`)
|
|
98
|
+
expect(hasClientInteractivity(reactive)).toBe(true)
|
|
99
|
+
expect(hasClientInteractivity(inert)).toBe(false)
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
test('collectImportedLoopChildComponentErrors names the adapter and fires only inside a loop', () => {
|
|
103
|
+
const ir = compileToIR(`
|
|
104
|
+
import { Row } from './row'
|
|
105
|
+
export function List({ items }: { items: string[] }) {
|
|
106
|
+
return <ul>{items.map(item => <Row key={item} label={item} />)}<Row label="last" /></ul>
|
|
107
|
+
}
|
|
108
|
+
`, 'list.tsx')
|
|
109
|
+
const errors = collectImportedLoopChildComponentErrors(ir, 'List', 'Twig')
|
|
110
|
+
expect(errors).toHaveLength(1)
|
|
111
|
+
expect(errors[0]!.code).toBe('BF103')
|
|
112
|
+
expect(errors[0]!.message).toContain('The Twig adapter emits a cross-template call')
|
|
113
|
+
expect(errors[0]!.suggestion?.message).toContain('register the resulting Twig template alongside the parent')
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
test('collectImportedLoopChildComponentErrors walks conditionals and component children, in render order', () => {
|
|
117
|
+
const ir = compileToIR(`
|
|
118
|
+
import { Row } from './row'
|
|
119
|
+
import { Card } from './card'
|
|
120
|
+
export function List({ items, open }: { items: string[]; open: boolean }) {
|
|
121
|
+
return (
|
|
122
|
+
<div>
|
|
123
|
+
{open ? <ul>{items.map(item => <Card key={item}>{item ? <Row label={item} /> : null}</Card>)}</ul> : null}
|
|
124
|
+
<Card><Row label="outside" /></Card>
|
|
125
|
+
</div>
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
`, 'list.tsx')
|
|
129
|
+
const errors = collectImportedLoopChildComponentErrors(ir, 'List', 'Jinja')
|
|
130
|
+
expect(errors.map(e => e.message.match(/<(\w+)>/)?.[1])).toEqual(['Card', 'Row'])
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
test('collectImportedLoopChildComponentErrors ignores a non-relative import', () => {
|
|
134
|
+
const ir = compileToIR(`
|
|
135
|
+
import { Row } from '@acme/ui'
|
|
136
|
+
export function List({ items }: { items: string[] }) {
|
|
137
|
+
return <ul>{items.map(item => <Row key={item} label={item} />)}</ul>
|
|
138
|
+
}
|
|
139
|
+
`, 'list.tsx')
|
|
140
|
+
expect(collectImportedLoopChildComponentErrors(ir, 'List', 'Twig')).toEqual([])
|
|
141
|
+
})
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
describe('isBooleanTypedPropRef', () => {
|
|
145
|
+
const ctx = { propsObjectName: 'props', booleanTypedProps: new Set(['open']), isBound: (n: string) => n === 'row' }
|
|
146
|
+
|
|
147
|
+
test('a bare or props-object read of a boolean prop', () => {
|
|
148
|
+
expect(isBooleanTypedPropRef('open', ctx)).toBe(true)
|
|
149
|
+
expect(isBooleanTypedPropRef(' props.open ', ctx)).toBe(true)
|
|
150
|
+
expect(isBooleanTypedPropRef('label', ctx)).toBe(false)
|
|
151
|
+
expect(isBooleanTypedPropRef('open()', ctx)).toBe(false)
|
|
152
|
+
expect(isBooleanTypedPropRef('open.value', ctx)).toBe(false)
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
test('a loop binding that shares the name is the row, not the prop (#2488)', () => {
|
|
156
|
+
expect(isBooleanTypedPropRef('open', { ...ctx, isBound: (n) => n === 'open' })).toBe(false)
|
|
157
|
+
})
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
describe('childTemplateName', () => {
|
|
161
|
+
test('snake_cases the declared name, through an import alias (#2822)', () => {
|
|
162
|
+
expect(childTemplateName('TodoItem', new Map())).toBe('todo_item')
|
|
163
|
+
expect(childTemplateName('Item', new Map([['Item', 'TodoItem']]))).toBe('todo_item')
|
|
164
|
+
expect(childTemplateName('Button', new Map())).toBe('button')
|
|
165
|
+
})
|
|
166
|
+
})
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { describe, test, expect } from 'bun:test'
|
|
2
|
+
import { analyzeComponent } from '../analyzer'
|
|
3
|
+
import { jsxToIR } from '../jsx-to-ir'
|
|
4
|
+
import type { CompilerError, IRElement, IRNode } from '../types'
|
|
5
|
+
import type { AttrValueEmitter } from '../adapters/attr-value-emitter'
|
|
6
|
+
import { renderElementShell, renderFragmentScope, type ElementShellSpelling } from '../adapters/element-shell'
|
|
7
|
+
import { renderDangerousInnerHtml } from '../adapters/dangerous-inner-html'
|
|
8
|
+
|
|
9
|
+
// #3475: the element every template adapter writes the same way, with the
|
|
10
|
+
// adapter's spelling supplied as data.
|
|
11
|
+
function root(source: string): IRNode {
|
|
12
|
+
const ir = jsxToIR(analyzeComponent(source, 'Test.tsx'))
|
|
13
|
+
if (!ir) throw new Error('expected IR')
|
|
14
|
+
return ir
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const attrEmitter: AttrValueEmitter = {
|
|
18
|
+
emitLiteral: (value, name) => `${name}="${value.value}"`,
|
|
19
|
+
emitExpression: (value, name) => `${name}="<${value.expr}>"`,
|
|
20
|
+
emitBooleanAttr: (_value, name) => name,
|
|
21
|
+
emitBooleanShorthand: (_value, name) => name,
|
|
22
|
+
emitTemplate: (_value, name) => `${name}="<tpl>"`,
|
|
23
|
+
emitSpread: () => '',
|
|
24
|
+
emitJsxChildren: () => '',
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function spelling(errors: CompilerError[] = []): ElementShellSpelling {
|
|
28
|
+
return {
|
|
29
|
+
attrEmitter,
|
|
30
|
+
renderDangerousInnerHtml: element =>
|
|
31
|
+
renderDangerousInnerHtml(element, errors, 'jinja', expr => `[raw ${expr}]`),
|
|
32
|
+
renderChildren: (children) => children.map(c => (c.type === 'text' ? c.value : `{${c.type}}`)).join(''),
|
|
33
|
+
renderScopeMarker: () => 'bf-s="SCOPE"',
|
|
34
|
+
renderSlotMarker: slotId => `bf="${slotId}"`,
|
|
35
|
+
dataKeyRelay: 'RELAY',
|
|
36
|
+
scopeIdValue: 'SCOPE_ID',
|
|
37
|
+
wrapSsrPortalElement: rendered => `[portal ${rendered}]`,
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
describe('renderElementShell (#3475)', () => {
|
|
42
|
+
test('renders attributes, the root markers, children, and the close tag', () => {
|
|
43
|
+
// A render root relays its caller's row key, in the adapter's spelling.
|
|
44
|
+
const el = root(`function Test() { return <p className="a" id="x">hi</p> }\nexport { Test }`) as IRElement
|
|
45
|
+
expect(renderElementShell(el, spelling())).toBe('<p class="a" id="x" bf-s="SCOPE" RELAY>hi</p>')
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
test('a void element has no children or close tag', () => {
|
|
49
|
+
const el = root(`function Test() { return <input type="text" /> }\nexport { Test }`) as IRElement
|
|
50
|
+
expect(renderElementShell(el, spelling())).toBe('<input type="text" bf-s="SCOPE" RELAY>')
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
test('a dynamic dangerouslySetInnerHTML replaces the children through the raw sink', () => {
|
|
54
|
+
const el = root(
|
|
55
|
+
`function Test({ html }: { html: string }) { return <div dangerouslySetInnerHTML={{ __html: html }}>x</div> }\nexport { Test }`,
|
|
56
|
+
) as IRElement
|
|
57
|
+
expect(renderElementShell(el, spelling())).toContain('>[raw html]</div>')
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
test('an unlowerable dangerouslySetInnerHTML records BF101 and renders empty', () => {
|
|
61
|
+
const el = root(
|
|
62
|
+
`function Test({ v }: { v: { __html: string } }) { return <div dangerouslySetInnerHTML={v} /> }\nexport { Test }`,
|
|
63
|
+
) as IRElement
|
|
64
|
+
const errors: CompilerError[] = []
|
|
65
|
+
expect(renderElementShell(el, spelling(errors))).toMatch(/><\/div>$/)
|
|
66
|
+
expect(errors.map(e => e.code)).toEqual(['BF101'])
|
|
67
|
+
})
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
describe('renderFragmentScope (#3475)', () => {
|
|
71
|
+
test('wraps a component-root fragment in its scope comment, else returns the children', () => {
|
|
72
|
+
const fragment = { type: 'fragment', children: [], needsScopeComment: true } as never
|
|
73
|
+
const render = () => 'kids'
|
|
74
|
+
expect(renderFragmentScope(fragment, render, r => `<!--s-->${r}<!--/s-->`)).toBe('<!--s-->kids<!--/s-->')
|
|
75
|
+
const plain = { type: 'fragment', children: [], needsScopeComment: false } as never
|
|
76
|
+
expect(renderFragmentScope(plain, render, r => `<!--s-->${r}<!--/s-->`)).toBe('kids')
|
|
77
|
+
})
|
|
78
|
+
})
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { foldRenderReassignmentsInSource } from '../fold-render-reassignments.ts'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A `let`'s render-time reassignments fold into its initializer (#3501), so
|
|
6
|
+
* every stage reads the one value the binding holds when the component
|
|
7
|
+
* returns. Only side-effect-free reassignments that directly follow the
|
|
8
|
+
* declaration fold; anything else is left as written.
|
|
9
|
+
*/
|
|
10
|
+
function fold(body: string): string | null {
|
|
11
|
+
const out = foldRenderReassignmentsInSource(`export function S(props: { label?: string }) {\n${body}\n return <p>{label}</p>\n}\n`, 'S.tsx')
|
|
12
|
+
return out === null ? null : out.split('\n').slice(1, -3).join('\n')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
describe('foldRenderReassignmentsInSource', () => {
|
|
16
|
+
test('an `if` reassignment becomes a conditional over the value so far', () => {
|
|
17
|
+
const [decl, removed] = fold(" let label = props.label ?? 'Default'\n if (!label) label = 'Fallback'")!.split('\n')
|
|
18
|
+
expect(decl).toBe(" const label_1 = props.label ?? 'Default'; let label = ((!(label_1)) ? ('Fallback') : (label_1))")
|
|
19
|
+
expect(removed!.trim()).toBe('')
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
test('`if`/`else`, blocks and compound assignments fold in order', () => {
|
|
23
|
+
const out = fold(" let label = 'a'\n if (props.label) { label = props.label } else { label += '!' }\n label ??= 'z'")
|
|
24
|
+
expect(out?.split('\n')[0]).toBe(
|
|
25
|
+
" const label_1 = ((props.label) ? (props.label) : ((('a') + ('!')))); let label = ((label_1) ?? ('z'))",
|
|
26
|
+
)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
test('removed statements keep their lines, so later locations stay valid', () => {
|
|
30
|
+
const body = " let label = 'a'\n if (props.label) {\n label = 'b'\n }"
|
|
31
|
+
expect(fold(body)?.split('\n').length).toBe(body.split('\n').length)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
test('a computed value inside a statement that would be repeated, reordered or dropped is not folded', () => {
|
|
35
|
+
expect(fold(" let label = 'a'\n if (props.label) { label = props.label; label = label + label }")).toBeNull()
|
|
36
|
+
expect(fold(" let label = 'a'\n if (props.label) { label = props.label; label = props.b + label }")).toBeNull()
|
|
37
|
+
expect(fold(' let label = 0\n { label = props.label; label = 7 }')).toBeNull()
|
|
38
|
+
expect(fold(" let label = 'a'\n { label = props.label; if (props.b) label = 1 }")).toBeNull()
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
test('a reassignment with a side effect is not folded', () => {
|
|
42
|
+
expect(fold(" let label = 'a'\n if (check()) label = 'b'")).toBeNull()
|
|
43
|
+
expect(fold(" let label = 'a'\n label = make()")).toBeNull()
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
test('a reassignment after an unrelated statement is not folded', () => {
|
|
47
|
+
expect(fold(" let label = 'a'\n console.log(label)\n label = 'b'")).toBeNull()
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
test('a reassignment in a loop is not folded', () => {
|
|
51
|
+
expect(fold(" let label = 'a'\n for (const t of [1]) label = 'b'")).toBeNull()
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
test('a `const` and a `let` with no reassignment are left as written', () => {
|
|
55
|
+
expect(fold(" const label = 'a'")).toBeNull()
|
|
56
|
+
expect(fold(" let label = 'a'")).toBeNull()
|
|
57
|
+
})
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The folded source evaluates every expression as often, and in the same
|
|
62
|
+
* order, as the original: a getter on the props object observes the same
|
|
63
|
+
* reads and the binding ends with the same value.
|
|
64
|
+
*/
|
|
65
|
+
describe('folding preserves evaluation', () => {
|
|
66
|
+
const bodies = [
|
|
67
|
+
"let label = props.label ?? 'Default'\n if (!label) label = 'Fallback'",
|
|
68
|
+
'let label = props.label\n if (label) label = 0',
|
|
69
|
+
"let label = props.label\n if (props.label) { label = props.label } else { label += '!' }\n label ??= 'z'",
|
|
70
|
+
"let label = 'a'\n if (props.label) { label = props.label; label += '!' }",
|
|
71
|
+
"let label = 0\n label = props.label\n label = 7",
|
|
72
|
+
]
|
|
73
|
+
const run = (source: string, values: unknown[]) => {
|
|
74
|
+
const log: unknown[] = []
|
|
75
|
+
let k = 0
|
|
76
|
+
const props = {
|
|
77
|
+
get label() {
|
|
78
|
+
const v = values[k++ % values.length]
|
|
79
|
+
log.push(v)
|
|
80
|
+
return v
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
const fn = new Function('props', source.slice(source.indexOf('{') + 1, source.lastIndexOf('}')))
|
|
84
|
+
return { value: fn(props), log }
|
|
85
|
+
}
|
|
86
|
+
for (const body of bodies) {
|
|
87
|
+
for (const values of [[undefined], [''], ['x'], [0, 1, 2]]) {
|
|
88
|
+
test(`${JSON.stringify(body)} with label reads ${JSON.stringify(values)}`, () => {
|
|
89
|
+
const original = `function S(props) {\n ${body}\n return label\n}\n`
|
|
90
|
+
const folded = foldRenderReassignmentsInSource(original, 'S.js')
|
|
91
|
+
expect(folded).not.toBeNull()
|
|
92
|
+
expect(run(folded!, values)).toEqual(run(original, values))
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
})
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #3513: a const read through a method call on another const that is itself
|
|
3
|
+
* inlinable into the CSR template (`const text = props.label ?? 'd'; const
|
|
4
|
+
* upper = text.toUpperCase()`) inlines as the call on that value, as the
|
|
5
|
+
* same chain without a call (`label + '!'`) already did. Before, the
|
|
6
|
+
* init-local receiver failed the adapter's call acceptance, `upper` reported
|
|
7
|
+
* BF061 and the template slot fell back to `undefined`.
|
|
8
|
+
*
|
|
9
|
+
* Both template paths are covered: the static template (no signal) and the
|
|
10
|
+
* CSR template a component with a signal registers, which reads
|
|
11
|
+
* `ctx.csrInlinable`. A receiver that is classified inlinable but gets no
|
|
12
|
+
* CSR form (`(choices).includes(name)`) withdraws the acceptance, so the call
|
|
13
|
+
* reports BF061 again instead of rendering `undefined.toUpperCase()`.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { describe, test, expect } from 'bun:test'
|
|
17
|
+
import { compileJSX } from '../compiler'
|
|
18
|
+
import { HonoAdapter } from '../../../adapter-hono/src/adapter/hono-adapter'
|
|
19
|
+
|
|
20
|
+
const SIGNAL_PRELUDE = "'use client'\nimport { createSignal } from '@barefootjs/client'\n"
|
|
21
|
+
|
|
22
|
+
function compile(body: string, { prelude = '', signal = false } = {}) {
|
|
23
|
+
const head = signal ? `${SIGNAL_PRELUDE}${prelude}` : prelude
|
|
24
|
+
const signalDecl = signal ? 'const [count] = createSignal(0)\n' : ''
|
|
25
|
+
const source = `${head}export function S(props: { label?: string }) {\n${signalDecl}${body}\n}`
|
|
26
|
+
const result = compileJSX(source, 'S.tsx', { adapter: new HonoAdapter() })
|
|
27
|
+
const clientJs = result.files.find((f) => f.path.endsWith('.client.js'))?.content ?? ''
|
|
28
|
+
const line = clientJs.split('\n').find((l) => l.includes('hydrate(')) ?? ''
|
|
29
|
+
return { errors: result.errors.map((e) => e.code), template: line }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Evaluate the registered `template:` lambda against `props`. */
|
|
33
|
+
function render(template: string, props: Record<string, unknown>): string {
|
|
34
|
+
const lambda = template.match(/template: (\(_p\) => `.*`) \}\)/)?.[1]
|
|
35
|
+
expect(lambda).toBeDefined()
|
|
36
|
+
return new Function('escapeAttr', 'escapeTextOrMarkup', `return ${lambda}`)(String, String)(props)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const CHAINS: [string, string, string][] = [
|
|
40
|
+
["const text = props.label ?? 'd'\nconst upper = text.toUpperCase()", 'upper', 'ABC'],
|
|
41
|
+
["const label = props.label ?? 'd'\nconst upper = label.toUpperCase()", 'upper', 'ABC'],
|
|
42
|
+
["const text = props.label ?? 'd'\nconst upper = text.toUpperCase()\nconst lower = upper.toLowerCase()", 'lower', 'abc'],
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
describe('a method call on an inlinable local inlines (#3513)', () => {
|
|
46
|
+
test.each(CHAINS)('static template: %s', (decls, read, rendered) => {
|
|
47
|
+
const { errors, template } = compile(`${decls}\nreturn <p title={${read}}>{${read}}</p>`)
|
|
48
|
+
expect(errors).not.toContain('BF061')
|
|
49
|
+
expect(template).toContain("(_p.label ?? 'd').toUpperCase()")
|
|
50
|
+
expect(template).not.toContain('escapeAttr(undefined)')
|
|
51
|
+
expect(render(template, { label: 'aBc' })).toContain(`title="${rendered}"`)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
test.each(CHAINS)('CSR template: %s', (decls, read, rendered) => {
|
|
55
|
+
const { errors, template } = compile(`${decls}\nreturn <p title={${read}}>{count()}</p>`, { signal: true })
|
|
56
|
+
expect(errors).not.toContain('BF061')
|
|
57
|
+
expect(template).toContain("(_p.label ?? 'd').toUpperCase()")
|
|
58
|
+
expect(render(template, { label: 'aBc' })).toContain(`title="${rendered}"`)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
test('a method call on a local that does not inline still reports BF061', () => {
|
|
62
|
+
const { errors, template } = compile(
|
|
63
|
+
'function readItems() { return [props.label] }\nconst items = readItems()\nconst first = items.join()\nreturn <p title={first}>{first}</p>',
|
|
64
|
+
)
|
|
65
|
+
expect(errors).toContain('BF061')
|
|
66
|
+
expect(template).not.toContain('items.join()')
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
test.each([
|
|
70
|
+
['const upper = text.toUpperCase()', 'upper'],
|
|
71
|
+
['const upper = text.toUpperCase()\nconst lower = upper.toLowerCase()', 'lower'],
|
|
72
|
+
])('a receiver refused after classification withdraws the call: %s', (decls, read) => {
|
|
73
|
+
const { errors, template } = compile(
|
|
74
|
+
`const text = (choices).includes(props.label) ? 'yes' : 'no'\n${decls}\nreturn <p title={${read}}>{count()}</p>`,
|
|
75
|
+
{ prelude: "const choices = ['a']\n", signal: true },
|
|
76
|
+
)
|
|
77
|
+
expect(errors).toContain('BF061')
|
|
78
|
+
expect(template).not.toContain('undefined.')
|
|
79
|
+
expect(() => render(template, { label: 'a' })).not.toThrow()
|
|
80
|
+
})
|
|
81
|
+
})
|
|
@@ -103,7 +103,7 @@ describe('static-index event delegation resolves nested .map() params (#3240)',
|
|
|
103
103
|
// static-index event — same shape as before #3240.
|
|
104
104
|
expect(content).not.toContain('__ic1')
|
|
105
105
|
expect(content).not.toContain('__iidx1')
|
|
106
|
-
expect(content).toMatch(/const item = ITEMS\[__idx\]\n\s*if \(item\) \{\n\s*;\(\(\) => setPicked\(item\)\)\(__bfEvt\)\n\s*\}/)
|
|
106
|
+
expect(content).toMatch(/const item = ITEMS\[__idx\]\n\s*if \(item !== undefined\) \{\n\s*;\(\(\) => setPicked\(item\)\)\(__bfEvt\)\n\s*\}/)
|
|
107
107
|
})
|
|
108
108
|
|
|
109
109
|
test('a nested array expression referencing the outer param resolves inside the outer guard', () => {
|