@barefootjs/jsx 0.39.5 → 0.39.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/adapters/array-method.d.ts +93 -0
  2. package/dist/adapters/array-method.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts +135 -0
  4. package/dist/adapters/attr-plan.d.ts.map +1 -0
  5. package/dist/adapters/boolean-result.d.ts +84 -9
  6. package/dist/adapters/boolean-result.d.ts.map +1 -1
  7. package/dist/adapters/callback-method.d.ts +126 -0
  8. package/dist/adapters/callback-method.d.ts.map +1 -0
  9. package/dist/adapters/component-props.d.ts +99 -0
  10. package/dist/adapters/component-props.d.ts.map +1 -0
  11. package/dist/adapters/component-tree.d.ts +25 -0
  12. package/dist/adapters/component-tree.d.ts.map +1 -0
  13. package/dist/adapters/literal-value.d.ts +22 -0
  14. package/dist/adapters/literal-value.d.ts.map +1 -0
  15. package/dist/adapters/loop-plan.d.ts +53 -0
  16. package/dist/adapters/loop-plan.d.ts.map +1 -0
  17. package/dist/adapters/prop-classes.d.ts +37 -0
  18. package/dist/adapters/prop-classes.d.ts.map +1 -0
  19. package/dist/expression-parser.d.ts +38 -0
  20. package/dist/expression-parser.d.ts.map +1 -1
  21. package/dist/index.d.ts +17 -3
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1765 -914
  24. package/dist/jsx-to-ir.d.ts +465 -1
  25. package/dist/jsx-to-ir.d.ts.map +1 -1
  26. package/dist/nullable-signal-attr.d.ts +19 -0
  27. package/dist/nullable-signal-attr.d.ts.map +1 -1
  28. package/package.json +2 -2
  29. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
  30. package/src/__tests__/action-accessor.test.ts +6 -24
  31. package/src/__tests__/array-method-catalogue.test.ts +99 -0
  32. package/src/__tests__/attr-plan.test.ts +121 -0
  33. package/src/__tests__/binding-scope-ratchet.test.ts +12 -12
  34. package/src/__tests__/boolean-result-expr.test.ts +106 -0
  35. package/src/__tests__/boolean-result.test.ts +34 -1
  36. package/src/__tests__/callback-method.test.ts +189 -0
  37. package/src/__tests__/component-props.test.ts +148 -0
  38. package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
  39. package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
  40. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
  41. package/src/__tests__/loop-plan.test.ts +104 -0
  42. package/src/__tests__/map-call-decisions.test.ts +521 -0
  43. package/src/__tests__/nullable-signal-attr.test.ts +45 -0
  44. package/src/adapters/array-method.ts +193 -0
  45. package/src/adapters/attr-plan.ts +200 -0
  46. package/src/adapters/boolean-result.ts +208 -12
  47. package/src/adapters/callback-method.ts +301 -0
  48. package/src/adapters/component-props.ts +144 -0
  49. package/src/adapters/component-tree.ts +118 -0
  50. package/src/adapters/literal-value.ts +36 -0
  51. package/src/adapters/loop-plan.ts +88 -0
  52. package/src/adapters/prop-classes.ts +73 -0
  53. package/src/expression-parser.ts +537 -374
  54. package/src/index.ts +53 -2
  55. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
  56. package/src/jsx-to-ir.ts +1328 -991
  57. package/src/nullable-signal-attr.ts +78 -0
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The props a DSL adapter passes to a child component (#3479): which entries,
3
+ * spreads and captures `planComponentProps` makes of a component call, and
4
+ * the order `spellComponentProps` spells them in.
5
+ */
6
+
7
+ import { describe, test, expect } from 'bun:test'
8
+ import {
9
+ isEmptyComponentProps,
10
+ planComponentProps,
11
+ spellComponentProps,
12
+ type ComponentPropEntry,
13
+ type ComponentPropsOptions,
14
+ } from '../adapters/component-props'
15
+ import type { AttrValue, IRComponent, IRNode, IRProp } from '../types'
16
+
17
+ const loc = { file: 'x.tsx', start: { line: 1, column: 0 }, end: { line: 1, column: 0 } }
18
+ const text = (value: string): IRNode => ({ type: 'text', value, loc }) as IRNode
19
+
20
+ function prop(name: string, value: AttrValue): IRProp {
21
+ return { name, value, loc } as IRProp
22
+ }
23
+ const literal = (value: string): AttrValue => ({ kind: 'literal', value })
24
+ const expression = (expr: string): AttrValue => ({ kind: 'expression', expr }) as AttrValue
25
+ const spread = (expr: string): AttrValue => ({ kind: 'spread', expr }) as AttrValue
26
+ const jsx = (...children: IRNode[]): AttrValue => ({ kind: 'jsx-children', children }) as AttrValue
27
+
28
+ function component(props: IRProp[], extra: Partial<IRComponent> = {}): IRComponent {
29
+ return {
30
+ type: 'component',
31
+ name: 'Tag',
32
+ props,
33
+ propsType: null,
34
+ children: [],
35
+ template: 'tag',
36
+ slotId: 's0',
37
+ loc,
38
+ ...extra,
39
+ } as IRComponent
40
+ }
41
+
42
+ const noProps: ComponentPropsOptions = { propsObjectName: null, propsParams: [] }
43
+ const withProps: ComponentPropsOptions = {
44
+ propsObjectName: 'props',
45
+ propsParams: [{ name: 'tone' }, { name: 'size' }],
46
+ }
47
+
48
+ /** The plan, spelled as `key=value` parts and `...spread`. */
49
+ function spell(comp: IRComponent, options = noProps): string[] {
50
+ const describe = (entry: ComponentPropEntry): string => {
51
+ switch (entry.kind) {
52
+ case 'value':
53
+ return `${entry.name}=${entry.value.kind === 'literal' ? `'${entry.value.value}'` : (entry.value as { expr: string }).expr}`
54
+ case 'named-slot':
55
+ return `${entry.name}=<slot>`
56
+ case 'props-param':
57
+ return `${entry.name}=$${entry.name}`
58
+ case 'slot-id':
59
+ return `_bf_slot='${entry.slotId}'`
60
+ case 'children':
61
+ return 'children=<children>'
62
+ }
63
+ }
64
+ return spellComponentProps(planComponentProps(comp, options), {
65
+ entry: describe,
66
+ spread: (value) => value.expr,
67
+ }).map((segment) => (segment.kind === 'spread' ? `...${segment.expr}` : `{${segment.parts.join(', ')}}`))
68
+ }
69
+
70
+ describe('planComponentProps', () => {
71
+ test('ordinary props, then the slot id', () => {
72
+ expect(spell(component([prop('tone', literal('warm')), prop('size', expression('size()'))]))).toEqual([
73
+ `{tone='warm', size=size(), _bf_slot='s0'}`,
74
+ ])
75
+ })
76
+
77
+ test('callback props and ref are client-only; a callback-named literal is kept', () => {
78
+ const comp = component([
79
+ prop('onClick', expression('handle')),
80
+ prop('ref', expression('el')),
81
+ prop('onLabel', literal('on')),
82
+ ])
83
+ expect(spell(comp)).toEqual([`{onLabel='on', _bf_slot='s0'}`])
84
+ })
85
+
86
+ test('a loop row root passes no slot id', () => {
87
+ expect(spell(component([prop('tone', literal('warm'))], { loopItemRoot: true }))).toEqual([`{tone='warm'}`])
88
+ expect(spell(component([], { slotId: null }))).toEqual(['{}'])
89
+ })
90
+
91
+ test('a spread folds in at its source position', () => {
92
+ const comp = component([prop('tone', literal('a')), prop('', spread('rest')), prop('size', literal('b'))])
93
+ expect(spell(comp)).toEqual([`{tone='a'}`, '...rest', `{size='b', _bf_slot='s0'}`])
94
+ })
95
+
96
+ test('{...props} enumerates the props params', () => {
97
+ const comp = component([prop('', spread(' props ')), prop('label', literal('x'))])
98
+ expect(spell(comp, withProps)).toEqual([`{tone=$tone, size=$size, label='x', _bf_slot='s0'}`])
99
+ })
100
+
101
+ test('a repeated key keeps its first position and takes the later value', () => {
102
+ const later = component([prop('', spread('props')), prop('tone', literal('explicit'))])
103
+ expect(spell(later, withProps)).toEqual([`{tone='explicit', size=$size, _bf_slot='s0'}`])
104
+ const earlier = component([prop('tone', literal('first')), prop('', spread('props'))])
105
+ expect(spell(earlier, withProps)).toEqual([`{tone=$tone, size=$size, _bf_slot='s0'}`])
106
+ })
107
+
108
+ test('a key repeated across a spread stays twice: the spread may set it in between', () => {
109
+ const comp = component([prop('tone', literal('a')), prop('', spread('rest')), prop('tone', literal('b'))])
110
+ expect(spell(comp)).toEqual([`{tone='a'}`, '...rest', `{tone='b', _bf_slot='s0'}`])
111
+ })
112
+
113
+ test('named slots in place, the children last', () => {
114
+ const nested = component([prop('header', jsx(text('H'))), prop('tone', literal('x'))], { children: [text('C')] })
115
+ expect(spell(nested)).toEqual([`{header=<slot>, tone='x', _bf_slot='s0', children=<children>}`])
116
+ // `children={<jsx/>}` is the children entry, not an ordinary prop.
117
+ const attribute = component([prop('children', jsx(text('C'))), prop('tone', literal('x'))])
118
+ expect(spell(attribute)).toEqual([`{tone='x', _bf_slot='s0', children=<children>}`])
119
+ })
120
+
121
+ test('the children follow a trailing spread, so the spread cannot override them', () => {
122
+ const comp = component([prop('', spread('rest'))], { children: [text('C')], slotId: null })
123
+ expect(spell(comp)).toEqual(['{}', '...rest', '{children=<children>}'])
124
+ })
125
+ })
126
+
127
+ describe('spellComponentProps', () => {
128
+ test('spells entries in source order and drops an empty part', () => {
129
+ const order: string[] = []
130
+ const comp = component([prop('a', jsx(text('A'))), prop('b', literal('x')), prop('c', jsx(text('C')))], {
131
+ children: [text('D')],
132
+ })
133
+ const segments = spellComponentProps(planComponentProps(comp, noProps), {
134
+ entry: (entry) => {
135
+ order.push(entry.kind === 'slot-id' || entry.kind === 'children' ? entry.kind : entry.name)
136
+ return entry.kind === 'value' ? '' : 'part'
137
+ },
138
+ spread: () => '',
139
+ })
140
+ expect(order).toEqual(['a', 'b', 'c', 'slot-id', 'children'])
141
+ expect(segments).toEqual([{ kind: 'entries', parts: ['part', 'part', 'part', 'part'] }])
142
+ })
143
+
144
+ test('isEmptyComponentProps: no part in any segment', () => {
145
+ expect(isEmptyComponentProps([{ kind: 'entries', parts: [] }])).toBe(true)
146
+ expect(isEmptyComponentProps([{ kind: 'entries', parts: [] }, { kind: 'spread', expr: 'x' }])).toBe(false)
147
+ })
148
+ })
@@ -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
+ })
@@ -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', () => {
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The loop decisions shared by the DSL adapters (#3473): what `planLoop`
3
+ * decides about a `.map()` loop against the scope outside it.
4
+ */
5
+
6
+ import { describe, test, expect } from 'bun:test'
7
+ import { analyzeComponent } from '../analyzer'
8
+ import { jsxToIR } from '../jsx-to-ir'
9
+ import { planLoop, type LoopPlanContext } from '../adapters/loop-plan'
10
+ import { BindingScope } from '../scope/binding-scope'
11
+ import type { IRLoop, IRNode } from '../types'
12
+
13
+ function firstLoop(node: IRNode | null): IRLoop {
14
+ const visit = (n: IRNode): IRLoop | null => {
15
+ if (n.type === 'loop') return n
16
+ for (const child of ('children' in n ? (n.children as IRNode[]) : []) ?? []) {
17
+ const found = visit(child)
18
+ if (found) return found
19
+ }
20
+ return null
21
+ }
22
+ const loop = node ? visit(node) : null
23
+ if (!loop) throw new Error('no loop in the component')
24
+ return loop
25
+ }
26
+
27
+ function plan(source: string, overrides: Partial<LoopPlanContext<unknown[]>> = {}) {
28
+ const ctx = analyzeComponent(source, 'Test.tsx')
29
+ const loop = firstLoop(jsxToIR(ctx))
30
+ const literals = new Set(['LIMITS'])
31
+ return planLoop(loop, {
32
+ scope: BindingScope.EMPTY,
33
+ localConstants: ctx.localConstants,
34
+ resolveLiteralConst: (name) => (literals.has(name) ? name : null),
35
+ callbackLowering: { adapterName: 'Test' },
36
+ spellStatic: (items) => items,
37
+ ...overrides,
38
+ })
39
+ }
40
+
41
+ describe('planLoop', () => {
42
+ test('a plain loop: no destructure, no static source, no sort, no captures', () => {
43
+ expect(plan(`export function Test(props: { items: string[] }) { return <ul>{props.items.map(x => <li key={x}>{x}</li>)}</ul> }`)).toEqual({
44
+ destructure: 'none',
45
+ staticSource: null,
46
+ unresolvableConst: null,
47
+ sort: null,
48
+ captureAliases: [],
49
+ })
50
+ })
51
+
52
+ test('an inline literal source is spelled statically', () => {
53
+ expect(plan(`export function Test() { return <ul>{['a', 'b'].map(x => <li key={x}>{x}</li>)}</ul> }`).staticSource).toEqual(['a', 'b'])
54
+ })
55
+
56
+ test('a static const source the backend cannot spell is BF101 instead', () => {
57
+ const source = `export function Test() {
58
+ const items = [{ id: 1, on: true }]
59
+ return <ul>{items.map(x => <li key={x.id}>{String(x.on)}</li>)}</ul>
60
+ }`
61
+ expect(plan(source)).toMatchObject({ staticSource: [{ id: 1, on: true }], unresolvableConst: null })
62
+ const perl = plan(source, { spellStatic: (items) => (JSON.stringify(items).includes('true') ? null : items) })
63
+ expect(perl.staticSource).toBeNull()
64
+ expect(perl.unresolvableConst?.name).toBe('items')
65
+ })
66
+
67
+ test('a computed const source no template binds is BF101, unless a loop binding shadows it', () => {
68
+ const source = `export function Test(props: { labels: Record<string, string> }) {
69
+ const entries = Object.keys(props.labels)
70
+ return <ul>{entries.map(x => <li key={x}>{x}</li>)}</ul>
71
+ }`
72
+ expect(plan(source).unresolvableConst?.name).toBe('entries')
73
+ const shadowed = BindingScope.EMPTY.enterLoopRow({ param: 'entries' } as IRLoop)
74
+ expect(plan(source, { scope: shadowed }).unresolvableConst).toBeNull()
75
+ })
76
+
77
+ test('a parenthesized computed const source is the same const (#3473)', () => {
78
+ const source = `export function Test(props: { labels: Record<string, string> }) {
79
+ const entries = Object.keys(props.labels)
80
+ return <ul>{(entries).map(x => <li key={x}>{x}</li>)}</ul>
81
+ }`
82
+ expect(plan(source).unresolvableConst?.name).toBe('entries')
83
+ })
84
+
85
+ test('a lowerable destructure, and one no template binds', () => {
86
+ expect(plan(`export function Test(props: { rows: { a: string }[] }) { return <ul>{props.rows.map(({ a }) => <li key={a}>{a}</li>)}</ul> }`).destructure).toBe('lowerable')
87
+ expect(
88
+ plan(`export function Test(props: { rows: { a: string; b: string }[] }) { return <ul>{props.rows.map(({ a, ...rest }) => <li key={a}>{String(rest)}</li>)}</ul> }`).destructure,
89
+ ).toBe('unlowerable')
90
+ })
91
+
92
+ test('a sort comparator takes the shared callback lowering', () => {
93
+ const sorted = plan(`export function Test(props: { items: { n: number }[] }) { return <ul>{props.items.toSorted((a, b) => a.n - b.n).map(x => <li key={x.n}>{x.n}</li>)}</ul> }`)
94
+ expect(sorted.sort).toMatchObject({ kind: 'eval', helper: 'sort_eval' })
95
+ })
96
+
97
+ test('a filter capture a row binding would shadow gets a per-loop alias', () => {
98
+ const captured = plan(`export function Test(props: { items: { id: string }[]; id: string }) {
99
+ const id = props.id
100
+ return <ul>{props.items.filter(x => x.id !== id).map(id => <li key={id.id}>{id.id}</li>)}</ul>
101
+ }`)
102
+ expect(captured.captureAliases).toEqual([{ name: 'id', alias: expect.stringMatching(/^__bf_cap_\w+_id$/) }])
103
+ })
104
+ })