@barefootjs/jsx 0.41.2 → 0.41.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.
@@ -1,6 +1,6 @@
1
1
  import { describe, test, expect } from 'bun:test'
2
- import { parseExpression } from '../expression-parser'
3
- import { evaluateStaticLiteral, isFullyStaticLiteral, resolveStaticLoopSource } from '../static-literal'
2
+ import { parseExpression, stringifyParsedExpr } from '../expression-parser'
3
+ import { evaluateStaticLiteral, foldStaticBindings, isFullyStaticLiteral, resolveStaticLoopSource } from '../static-literal'
4
4
  import type { ConstantInfo } from '../types'
5
5
 
6
6
  // #2208: a local const whose initializer is fully known at compile time (no
@@ -159,3 +159,48 @@ describe('resolveStaticLoopSource (#2208)', () => {
159
159
  expect(resolveStaticLoopSource(parseExpression('obj'), locals)).toBeNull()
160
160
  })
161
161
  })
162
+
163
+ // #3798: the row of a compile-time-unrolled loop folds into an expression
164
+ // that otherwise reads the component's own scope.
165
+ describe('foldStaticBindings (#3798)', () => {
166
+ const fold = (src: string, bindings: Record<string, unknown>) =>
167
+ foldStaticBindings(parseExpression(src), new Map(Object.entries(bindings)))
168
+ const text = (e: ReturnType<typeof fold>) => (e === null ? null : stringifyParsedExpr(e))
169
+
170
+ test('a bound name becomes a literal and the rest of the tree is kept', () => {
171
+ expect(text(fold("q === 'x' ? props.label : '0'", { q: 'x' }))).toBe('"x" === "x" ? props.label : "0"')
172
+ })
173
+
174
+ test('a static member chain off an object row folds to its value', () => {
175
+ expect(text(fold('item.on ? props.a : item.id', { item: { on: false, id: 'b' } }))).toBe('false ? props.a : "b"')
176
+ })
177
+
178
+ test('a template literal keeps its shape and folds the parts inside it', () => {
179
+ expect(text(fold('`${q}-${props.a}`', { q: 'x' }))).toBe('`${"x"}-${props.a}`')
180
+ expect(fold('`${q}x`', { q: 'x' })?.kind).toBe('template-literal')
181
+ })
182
+
183
+ test('a number row keeps its value, including 0 and a fraction', () => {
184
+ expect(text(fold('n === 0 ? props.a : n', { n: 0 }))).toBe('0 === 0 ? props.a : 0')
185
+ expect(text(fold('n > 1 ? 1 : 2', { n: 1.5 }))).toBe('1.5 > 1 ? 1 : 2')
186
+ })
187
+
188
+ test('a string that spells the bound name is not a reference', () => {
189
+ expect(text(fold("q === 'q' ? 'q' : props.q", { q: 'q' }))).toBe('"q" === "q" ? "q" : props.q')
190
+ })
191
+
192
+ test('an arrow parameter named like a bound name shadows it', () => {
193
+ expect(text(fold('props.xs.some(q => q === 1) && q', { q: 'x' }))).toBe('props.xs.some(q => q === 1) && "x"')
194
+ expect(fold('props.xs.some(q => q === 1)', { q: 'x' })).not.toBeNull()
195
+ })
196
+
197
+ test('an object row read other than through a static member chain refuses', () => {
198
+ expect(fold('fn(item)', { item: { a: 1 } })).toBeNull()
199
+ expect(fold('item.missing.deeper', { item: { a: 1 } })).toBeNull()
200
+ })
201
+
202
+ test('no bindings returns the expression itself', () => {
203
+ const expr = parseExpression('props.a')
204
+ expect(foldStaticBindings(expr, new Map())).toBe(expr)
205
+ })
206
+ })
@@ -0,0 +1,436 @@
1
+ /**
2
+ * Whether an expression can reach a value the component's caller supplied
3
+ * that may be, or may build, a live element.
4
+ *
5
+ * A caller can hand a component an element factory: a callback prop
6
+ * (`renderNode={(n) => <Pill id={n.id} />}`), or an object holding one. The
7
+ * element such a callback returns owns its own state, so a branch that may
8
+ * hold one must not be evaluated again while it is mounted
9
+ * (`IRExpression.readsCallerValue`). The compiler cannot see what a caller
10
+ * passes, so the answer is built from the safe side: a name is safe only when
11
+ * the caller's props cannot reach it, and everything else is not.
12
+ *
13
+ * A name read inside the component is safe when it is
14
+ *
15
+ * - declared outside the component (a module const or function, an
16
+ * import, a global): it can see a prop only through an argument, and
17
+ * the arguments are read by the same walk;
18
+ * - a prop whose declared type holds data only (`isDataOnlyType`): a
19
+ * string, number, boolean, `null` or `undefined`, an array or object of
20
+ * those, or a function returning one;
21
+ * - a component `const` or `function` declaration whose initializer or
22
+ * body reads only safe names, through any number of hops.
23
+ *
24
+ * It is not safe when it is the props object used whole, a rest bag, a prop
25
+ * with any other or no declared type (`children` included), a `let`, a const
26
+ * the component mutates, a binding of a nested destructuring pattern, or a
27
+ * component declaration that reads any of these. How the value is then used
28
+ * does not matter: `props.render(row)`, `props['render'](row)`,
29
+ * `props.render.call(null, row)`, `apply(props.render, row)`, a wrapper
30
+ * `const draw = row => props.render(row)`, an object `{ draw: props.render }`
31
+ * and a memo or signal seeded from one all read an unsafe name.
32
+ *
33
+ * The declarations are read from the component function's own AST rather than
34
+ * from the analyzer's `localConstants` / `localFunctions` records: those hold
35
+ * free identifier NAMES, which cannot tell `props.count` from `props.render`,
36
+ * and they have no entry for an array pattern or a nested object pattern, so
37
+ * a name bound by one would read as a global.
38
+ */
39
+
40
+ import ts from 'typescript'
41
+ import type { AnalyzerContext } from './analyzer-context.ts'
42
+ import { unwrapJsxTransparent } from './analyzer.ts'
43
+ import type { ParamInfo, TypeInfo } from './types.ts'
44
+ import { isValueReferenceIdentifier } from './value-references.ts'
45
+
46
+ /**
47
+ * Whether the recorded property list of a type declaration is its whole
48
+ * member list. `PropertyInfo[]` keeps property signatures only: a method
49
+ * (`render(row): unknown`), an index signature (`[k: string]: Fn`) and a
50
+ * call signature are dropped, and an interface records its own members
51
+ * without those of an `extends` clause. A type with any of these, or with
52
+ * type parameters, cannot be proved data-only from the list, so it is not.
53
+ * `source` is the declaration text (`interface ...`, `type ... = {...}`),
54
+ * read with the TypeScript parser.
55
+ */
56
+ function hasCompleteMembers(source: string): boolean {
57
+ const file = ts.createSourceFile('__members__.ts', source, ts.ScriptTarget.Latest, false)
58
+ const declaration = file.statements[0]
59
+ if (!declaration || file.statements.length !== 1) return false
60
+ let members: ts.NodeArray<ts.TypeElement>
61
+ if (ts.isInterfaceDeclaration(declaration)) {
62
+ if (declaration.heritageClauses?.length || declaration.typeParameters?.length) return false
63
+ members = declaration.members
64
+ } else if (ts.isTypeAliasDeclaration(declaration) && ts.isTypeLiteralNode(declaration.type)) {
65
+ if (declaration.typeParameters?.length) return false
66
+ members = declaration.type.members
67
+ } else {
68
+ return false
69
+ }
70
+ return members.every(ts.isPropertySignature)
71
+ }
72
+
73
+ /**
74
+ * Whether a value of `type` is data all the way down: it is not an element
75
+ * and calling anything it holds cannot produce one. A named type resolves
76
+ * through the file's own type definitions; one declared elsewhere is unknown.
77
+ */
78
+ export function isDataOnlyType(
79
+ type: TypeInfo | undefined | null,
80
+ analyzer: Pick<AnalyzerContext, 'typeDefinitions'>,
81
+ seen: ReadonlySet<string> = new Set(),
82
+ ): boolean {
83
+ if (!type) return false
84
+ switch (type.kind) {
85
+ case 'primitive':
86
+ return true
87
+ case 'union':
88
+ return (type.unionTypes ?? []).length > 0 && (type.unionTypes ?? []).every(t => isDataOnlyType(t, analyzer, seen))
89
+ case 'array':
90
+ return isDataOnlyType(type.elementType, analyzer, seen)
91
+ case 'function':
92
+ return isDataOnlyType(type.returnType, analyzer, seen)
93
+ case 'object':
94
+ return type.properties !== undefined
95
+ && hasCompleteMembers(`type T = ${type.raw}`)
96
+ && type.properties.every(p => isDataOnlyType(p.type, analyzer, seen))
97
+ case 'interface': {
98
+ // A recursive type (`type Tree = { kids: Tree[] }`) is data when the
99
+ // rest of it is.
100
+ if (seen.has(type.raw)) return true
101
+ // Two declarations of one name merge (`interface X` twice); the
102
+ // recorded list is then partial.
103
+ const named = analyzer.typeDefinitions.filter(d => d.name === type.raw)
104
+ const definition = named.length === 1 ? named[0] : undefined
105
+ if (!definition?.properties || !hasCompleteMembers(definition.definition)) return false
106
+ const next = new Set(seen).add(type.raw)
107
+ return definition.properties.every(p => isDataOnlyType(p.type, analyzer, next))
108
+ }
109
+ case 'unknown':
110
+ return false
111
+ }
112
+ }
113
+
114
+ /** The component's names a caller's element can be reached through. */
115
+ interface CallerReach {
116
+ /** The props object and the consts that alias it (`const p = props`). */
117
+ readonly propsObjects: ReadonlySet<string>
118
+ /** Every other component-scope name that is not safe. */
119
+ readonly unsafe: ReadonlySet<string>
120
+ }
121
+
122
+ /** A component-scope declaration still to be judged by what it reads. */
123
+ interface PendingDeclaration {
124
+ readonly names: readonly string[]
125
+ /** The initializer, or the whole function declaration. */
126
+ readonly reads: ts.Node
127
+ }
128
+
129
+ const reachCache = new WeakMap<AnalyzerContext, CallerReach | null>()
130
+
131
+ function collectBindingNames(name: ts.BindingName, out: string[]): void {
132
+ if (ts.isIdentifier(name)) {
133
+ out.push(name.text)
134
+ return
135
+ }
136
+ for (const element of name.elements) {
137
+ if (!ts.isOmittedExpression(element)) collectBindingNames(element.name, out)
138
+ }
139
+ }
140
+
141
+ function isFunctionLike(node: ts.Node): node is ts.FunctionLikeDeclaration {
142
+ return ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node)
143
+ || ts.isMethodDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node)
144
+ || ts.isConstructorDeclaration(node)
145
+ }
146
+
147
+ /** The component function: the one whose body the analyzer recorded, or that returns the JSX. */
148
+ function componentFunction(analyzer: AnalyzerContext): ts.FunctionLikeDeclaration | null {
149
+ let node: ts.Node | undefined = analyzer.componentBodyBlock ?? analyzer.jsxReturn ?? undefined
150
+ while (node && !isFunctionLike(node)) node = node.parent
151
+ return node ?? null
152
+ }
153
+
154
+ /** The declared type of the prop `key` names: a destructured local name, or a member of the props object. */
155
+ function propTypeOf(key: string, byLocalName: boolean, analyzer: AnalyzerContext): TypeInfo | undefined {
156
+ const param: ParamInfo | undefined = byLocalName
157
+ ? analyzer.propsParams.find(p => p.name === key && !p.isRest)
158
+ : analyzer.propsParams.find(p => (p.sourceName ?? p.name) === key && !p.isRest)
159
+ return param?.declaredType ?? param?.type
160
+ }
161
+
162
+ /**
163
+ * The prop a use of the props object reads: `props.name`, `props['name']`,
164
+ * through parentheses, `!` and `as`. `null` for any other use, which hands
165
+ * the whole object on.
166
+ */
167
+ function readPropName(propsIdentifier: ts.Identifier): string | null {
168
+ let inner: ts.Node = propsIdentifier
169
+ let parent = inner.parent
170
+ while (
171
+ parent &&
172
+ (ts.isParenthesizedExpression(parent) || ts.isNonNullExpression(parent) || ts.isAsExpression(parent) || ts.isSatisfiesExpression(parent))
173
+ ) {
174
+ inner = parent
175
+ parent = parent.parent
176
+ }
177
+ if (!parent) return null
178
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === inner) return parent.name.text
179
+ if (ts.isElementAccessExpression(parent) && parent.expression === inner && ts.isStringLiteralLike(parent.argumentExpression)) {
180
+ return parent.argumentExpression.text
181
+ }
182
+ return null
183
+ }
184
+
185
+ /**
186
+ * Whether anything under `node` reads a name a caller's element can be
187
+ * reached through. `isSafeName` answers first for names the caller knows
188
+ * (a loop row's item); a name a nested function binds as a parameter is that
189
+ * function's own.
190
+ */
191
+ function readsUnsafeName(
192
+ node: ts.Node,
193
+ reach: { propsObjects: ReadonlySet<string>; unsafe: ReadonlySet<string> },
194
+ analyzer: AnalyzerContext,
195
+ resolveOuter: (name: string) => boolean | undefined,
196
+ ): boolean {
197
+ const visit = (n: ts.Node, bound: ReadonlySet<string>): boolean => {
198
+ if (ts.isTypeNode(n)) return false
199
+ if (ts.isIdentifier(n)) {
200
+ if (!isValueReferenceIdentifier(n) || bound.has(n.text)) return false
201
+ const outer = resolveOuter(n.text)
202
+ if (outer !== undefined) return outer
203
+ if (reach.propsObjects.has(n.text)) {
204
+ const prop = readPropName(n)
205
+ return prop === null || !isDataOnlyType(propTypeOf(prop, false, analyzer), analyzer)
206
+ }
207
+ return reach.unsafe.has(n.text)
208
+ }
209
+ let inner = bound
210
+ if (isFunctionLike(n) && n.parameters.length > 0) {
211
+ const params: string[] = []
212
+ for (const p of n.parameters) collectBindingNames(p.name, params)
213
+ inner = new Set([...bound, ...params])
214
+ }
215
+ return ts.forEachChild(n, child => visit(child, inner) || undefined) === true
216
+ }
217
+ return visit(node, new Set())
218
+ }
219
+
220
+ /** Collect the declarations of the statements a component body runs, without entering nested functions. */
221
+ function collectStatementDeclarations(
222
+ statement: ts.Node,
223
+ declarations: ts.VariableDeclaration[],
224
+ functions: ts.FunctionDeclaration[],
225
+ otherNames: string[],
226
+ ): void {
227
+ if (ts.isFunctionDeclaration(statement)) {
228
+ if (statement.name) functions.push(statement)
229
+ return
230
+ }
231
+ if (ts.isClassDeclaration(statement)) {
232
+ if (statement.name) otherNames.push(statement.name.text)
233
+ return
234
+ }
235
+ if (ts.isVariableDeclaration(statement)) {
236
+ declarations.push(statement)
237
+ return
238
+ }
239
+ if (ts.isExpression(statement) || isFunctionLike(statement)) return
240
+ ts.forEachChild(statement, child => collectStatementDeclarations(child, declarations, functions, otherNames))
241
+ }
242
+
243
+ /** Sort the props parameter's bindings into the props object and the unsafe names. */
244
+ function classifyParameters(
245
+ fn: ts.FunctionLikeDeclaration,
246
+ analyzer: AnalyzerContext,
247
+ propsObjects: Set<string>,
248
+ unsafe: Set<string>,
249
+ ): void {
250
+ fn.parameters.forEach((param, index) => {
251
+ if (index === 0 && ts.isIdentifier(param.name)) {
252
+ propsObjects.add(param.name.text)
253
+ return
254
+ }
255
+ if (index === 0 && ts.isObjectBindingPattern(param.name)) {
256
+ classifyPropsPattern(param.name, true, analyzer, unsafe, [])
257
+ return
258
+ }
259
+ const names: string[] = []
260
+ collectBindingNames(param.name, names)
261
+ for (const name of names) unsafe.add(name)
262
+ })
263
+ }
264
+
265
+ /**
266
+ * Judge each binding of an object pattern over the props object: a plain
267
+ * `name`, `key: name` or `name = default` binding of a data-only prop is
268
+ * safe (its default is judged later, with the other declarations); a rest
269
+ * element, a nested pattern or any other prop is not.
270
+ */
271
+ function classifyPropsPattern(
272
+ pattern: ts.ObjectBindingPattern,
273
+ isParameter: boolean,
274
+ analyzer: AnalyzerContext,
275
+ unsafe: Set<string>,
276
+ pending: PendingDeclaration[],
277
+ ): void {
278
+ for (const element of pattern.elements) {
279
+ const names: string[] = []
280
+ collectBindingNames(element.name, names)
281
+ const key = element.propertyName ?? element.name
282
+ const plain = !element.dotDotDotToken && ts.isIdentifier(element.name) && (ts.isIdentifier(key) || ts.isStringLiteralLike(key))
283
+ const type = plain
284
+ ? isParameter
285
+ ? propTypeOf((element.name as ts.Identifier).text, true, analyzer)
286
+ : propTypeOf((key as ts.Identifier | ts.StringLiteralLike).text, false, analyzer)
287
+ : undefined
288
+ if (!plain || !isDataOnlyType(type, analyzer)) {
289
+ for (const name of names) unsafe.add(name)
290
+ } else if (element.initializer) {
291
+ pending.push({ names, reads: element.initializer })
292
+ }
293
+ }
294
+ }
295
+
296
+ /** The names a variable declaration binds. */
297
+ function declaredNames(declaration: ts.VariableDeclaration): string[] {
298
+ const names: string[] = []
299
+ collectBindingNames(declaration.name, names)
300
+ return names
301
+ }
302
+
303
+ /**
304
+ * Split the component's variable declarations into the `const`s that can be
305
+ * judged by their initializer and the names that cannot: a `let` or `var`,
306
+ * a declaration with no initializer, and a const the component mutates.
307
+ */
308
+ function analysableConsts(
309
+ declarations: readonly ts.VariableDeclaration[],
310
+ analyzer: AnalyzerContext,
311
+ unsafe: Set<string>,
312
+ ): ts.VariableDeclaration[] {
313
+ const mutated = new Set(analyzer.localConstants.filter(c => c.mutatedAfterDeclaration).map(c => c.name))
314
+ const consts: ts.VariableDeclaration[] = []
315
+ for (const declaration of declarations) {
316
+ const names = declaredNames(declaration)
317
+ const isConst = ts.isVariableDeclarationList(declaration.parent) && (declaration.parent.flags & ts.NodeFlags.Const) !== 0
318
+ if (isConst && declaration.initializer && !names.some(n => mutated.has(n))) {
319
+ consts.push(declaration)
320
+ } else {
321
+ for (const name of names) unsafe.add(name)
322
+ }
323
+ }
324
+ return consts
325
+ }
326
+
327
+ /** Whether an initializer is the props object itself: `props`, or a name already known to alias it. */
328
+ function isPropsObjectValue(init: ts.Expression, propsObjects: ReadonlySet<string>): boolean {
329
+ const value = unwrapJsxTransparent(init)
330
+ return ts.isIdentifier(value) && propsObjects.has(value.text)
331
+ }
332
+
333
+ /**
334
+ * Move every `const p = props` alias, through any number of hops and in any
335
+ * declaration order, into `propsObjects`; return the other consts.
336
+ */
337
+ function takePropsAliases(consts: readonly ts.VariableDeclaration[], propsObjects: Set<string>): ts.VariableDeclaration[] {
338
+ let rest = [...consts]
339
+ for (let grew = true; grew; ) {
340
+ grew = false
341
+ const next: ts.VariableDeclaration[] = []
342
+ for (const declaration of rest) {
343
+ if (ts.isIdentifier(declaration.name) && isPropsObjectValue(declaration.initializer!, propsObjects)) {
344
+ propsObjects.add(declaration.name.text)
345
+ grew = true
346
+ } else {
347
+ next.push(declaration)
348
+ }
349
+ }
350
+ rest = next
351
+ }
352
+ return rest
353
+ }
354
+
355
+ /**
356
+ * Mark a declaration unsafe as soon as it reads an unsafe name, and repeat
357
+ * until none changes, so a chain of hops ends up unsafe in any order.
358
+ */
359
+ function settleDeclarations(
360
+ pending: readonly PendingDeclaration[],
361
+ reach: { propsObjects: ReadonlySet<string>; unsafe: Set<string> },
362
+ analyzer: AnalyzerContext,
363
+ ): void {
364
+ let open = [...pending]
365
+ for (let changed = true; changed; ) {
366
+ changed = false
367
+ const still: PendingDeclaration[] = []
368
+ for (const declaration of open) {
369
+ if (readsUnsafeName(declaration.reads, reach, analyzer, () => undefined)) {
370
+ for (const name of declaration.names) reach.unsafe.add(name)
371
+ changed = true
372
+ } else {
373
+ still.push(declaration)
374
+ }
375
+ }
376
+ open = still
377
+ }
378
+ }
379
+
380
+ function buildCallerReach(analyzer: AnalyzerContext): CallerReach | null {
381
+ const fn = componentFunction(analyzer)
382
+ if (!fn) return null
383
+ const propsObjects = new Set<string>()
384
+ const unsafe = new Set<string>()
385
+ const pending: PendingDeclaration[] = []
386
+ classifyParameters(fn, analyzer, propsObjects, unsafe)
387
+
388
+ const declarations: ts.VariableDeclaration[] = []
389
+ const functions: ts.FunctionDeclaration[] = []
390
+ const otherNames: string[] = []
391
+ if (fn.body && ts.isBlock(fn.body)) {
392
+ for (const statement of fn.body.statements) collectStatementDeclarations(statement, declarations, functions, otherNames)
393
+ }
394
+ for (const name of otherNames) unsafe.add(name)
395
+ for (const declaration of functions) pending.push({ names: [declaration.name!.text], reads: declaration })
396
+
397
+ const consts = takePropsAliases(analysableConsts(declarations, analyzer, unsafe), propsObjects)
398
+ for (const declaration of consts) {
399
+ const init = declaration.initializer!
400
+ if (ts.isObjectBindingPattern(declaration.name) && isPropsObjectValue(init, propsObjects)) {
401
+ classifyPropsPattern(declaration.name, false, analyzer, unsafe, pending)
402
+ } else {
403
+ pending.push({ names: declaredNames(declaration), reads: init })
404
+ }
405
+ }
406
+
407
+ const reach = { propsObjects, unsafe }
408
+ settleDeclarations(pending, reach, analyzer)
409
+ return reach
410
+ }
411
+
412
+ /**
413
+ * Whether `node`, an expression of the component's JSX, reads a value the
414
+ * caller supplied that may be or build a live element. `rowName` answers for
415
+ * the names the enclosing loop rows bind: `true` for a row's item, index or
416
+ * destructured name (the row's own data), `false` for any other name a row
417
+ * or callback binds (a `.map()` preamble local, whose initializer this walk
418
+ * does not see), `undefined` for a name they do not bind.
419
+ */
420
+ export function readsCallerValue(
421
+ node: ts.Node,
422
+ analyzer: AnalyzerContext,
423
+ rowName: (name: string) => boolean | undefined,
424
+ ): boolean {
425
+ let reach = reachCache.get(analyzer)
426
+ if (reach === undefined) {
427
+ reach = buildCallerReach(analyzer)
428
+ reachCache.set(analyzer, reach)
429
+ }
430
+ // No component function to read the declarations from: nothing is known safe.
431
+ if (reach === null) return true
432
+ return readsUnsafeName(node, reach, analyzer, name => {
433
+ const row = rowName(name)
434
+ return row === undefined ? undefined : !row
435
+ })
436
+ }
package/src/index.ts CHANGED
@@ -235,7 +235,7 @@ export type {
235
235
  LoopSortSpelling,
236
236
  SavedLoopBinding,
237
237
  } from './adapters/loop-plan.ts'
238
- export { evaluateStaticLiteral, isFullyStaticLiteral, resolveStaticLoopSource } from './static-literal.ts'
238
+ export { evaluateStaticLiteral, foldStaticBindings, isFullyStaticLiteral, resolveStaticLoopSource } from './static-literal.ts'
239
239
  export {
240
240
  arithmeticOperandIsNull,
241
241
  arithmeticOperandIsUndefined,
@@ -1832,54 +1832,33 @@ function summarizeLoopChildBranch(
1832
1832
  // on the branch root yields exactly this branch's direct bindings
1833
1833
  // without re-collecting what a nested arm already owns (#2347).
1834
1834
  reactiveAttrs: collectLoopChildReactiveAttrs(node, ctx, loopParam, loopParamBindings, true, preambleNames, loopIndex),
1835
- // Skip ONLY when the branch's entire content is a single bare
1836
- // `expression` (no wrapping element) that MAY yield a live DOM node —
1837
- // i.e. it contains a call anywhere (`node.hasFunctionCalls`, computed
1838
- // by the AST walk in `exprHasFunctionCalls`/jsx-to-ir.ts, recursively —
1839
- // catches a call nested in a template literal or a nested ternary, not
1840
- // just a top-level call). A call can return an Element (a hoisted
1841
- // `renderNode={(n) => <Pill/>}` callback lowered to a component call,
1842
- // #1211/#1213) and the compiler cannot tell from syntax whether it does
1843
- // — both `renderChild(...)` and `_p.renderCell(...)` are a
1844
- // `CallExpression` — so this stays conservative for ANY call, not just
1845
- // ones known to return JSX. Re-evaluating a non-idempotent call inside
1846
- // an *additional* nested createEffect (on top of the eval already done
1847
- // for the `__bfSlot`-wrapped splice whenever `insert()` (re-)mounts this
1848
- // branch) would call it again on every unrelated tick and discard the
1849
- // previous element's listeners/state.
1835
+ // The branch's own text slots, decided by the collector every other row
1836
+ // text goes through (`collectLoopChildReactiveTexts`): a slot whose
1837
+ // expression reads the row or a reactive source, or contains a call
1838
+ // (`decideWrapFromAstFlags`), gets an update effect inside this arm.
1839
+ // `insert()` (runtime/insert.ts) leaves a branch alone while its
1840
+ // condition is unchanged, so this effect is the only thing that
1841
+ // rewrites the branch when a keyed row is reused with a new item.
1850
1842
  //
1851
- // Everything else — a property access (`row.label`), an identifier, a
1852
- // literal, a template literal, string concatenation, or a nested
1853
- // ternary of those — cannot itself construct a DOM node (only a JSX
1854
- // literal or a call can, and a JSX literal branch is never `type:
1855
- // 'expression'` in the first place — see `transformJsxExpression`), so
1856
- // it is safe to collect. This is the fix for the loop-branch-stale-text
1857
- // defect: a keyed loop row whose branch is e.g. `row.done ? row.label :
1858
- // 'pending'` previously had NO update path at all when `row.label`
1859
- // changed without `row.done` flipping — `insert()` (runtime/insert.ts)
1860
- // correctly no-ops when its condition is unchanged (branch-internal
1861
- // updates are deliberately the effect system's job, not DOM
1862
- // replacement's), but with reactiveTexts always `[]` for this shape,
1863
- // no effect existed either, so the branch was frozen at its mount-time
1864
- // value. The stale rationale in a prior version of this comment blamed
1865
- // "the loop-child arm's `$t()`-based anchor lookup", but `$t()` no
1866
- // longer exists — it was one of four content mechanisms deleted by the
1867
- // slot-unification work. The current claim door
1868
- // (`stringifyLoopChildArm` → `lazySlots(..., kind: 'markup')` →
1869
- // `writeMarkup`, runtime/claim-slots.ts) clears the claimed range and
1870
- // splices the Node by identity, so "lands beside the first" cannot
1871
- // happen through it; only the call's non-idempotence still applies, and
1872
- // that alone is why the skip narrows rather than disappears.
1843
+ // That includes a branch that is one bare expression with a call in it
1844
+ // (`cond ? fmt(row.wait) : '0s'`, #3894). Such a branch used to get no
1845
+ // effect whatever it called, so the slot kept the value the row was
1846
+ // built with, while the same call directly in the row, or in a
1847
+ // conditional outside a loop, was re-evaluated.
1873
1848
  //
1874
- // Collecting here is necessary but not sufficient: `n.slotId` must also
1875
- // be set for `collectLoopChildReactiveTexts` (ir-to-client-js/
1876
- // reactivity.ts) to do anything — see `transformConditionalBranch`'s
1877
- // `refsLoopParam` check (jsx-to-ir.ts) for the matching half of this fix
1878
- // that gives a bare loop-item-reading branch a slotId at all, which also
1879
- // makes `irToHtmlTemplate` emit its `<!--bf:sN-->…<!--/-->` marker (the
1880
- // same call builds both the SSR and the CSR/hydration template, so the
1881
- // two can't disagree on shape).
1882
- reactiveTexts: node.type === 'expression' && node.hasFunctionCalls
1849
+ // The one branch left without an effect is the one Phase 1 marks
1850
+ // `readsCallerValue`: it has a call and reads something the caller
1851
+ // supplied that may be or build a live element, such as a callback prop
1852
+ // (`props.renderNode ? props.renderNode(n) : <span/>`, #1211/#1213).
1853
+ // That element owns its state, and evaluating the branch again on every
1854
+ // change of the row's item would replace it each time, so the row keeps
1855
+ // the element `insert()` mounted with the branch.
1856
+ //
1857
+ // `n.slotId` must be set for the collector to take a slot. See
1858
+ // `transformConditionalBranch`'s `refsLoopParam` check (jsx-to-ir.ts),
1859
+ // which gives a bare branch reading the loop item its slot and so the
1860
+ // `<!--bf:sN-->` marker in both the SSR and the client template.
1861
+ reactiveTexts: node.type === 'expression' && node.readsCallerValue
1883
1862
  ? []
1884
1863
  : collectLoopChildReactiveTexts(node, ctx, loopParam, loopParamBindings, true, preambleNames, loopIndex),
1885
1864
  }
package/src/jsx-to-ir.ts CHANGED
@@ -75,6 +75,7 @@ import { reconstructAsSegments, reconstructWithoutTypes } from './strip-types.ts
75
75
  import { templatePartsToJsExpr } from './template-parts.ts'
76
76
  import { toHTMLAttrName, decodeEntities, BF_KEY, keyAttrName } from '@barefootjs/shared'
77
77
  import { BindingScope } from './scope/binding-scope.ts'
78
+ import { readsCallerValue } from './caller-value-reach.ts'
78
79
  import { identifierPattern, identifierCallPattern } from './identifier-pattern.ts'
79
80
  import { isEventHandlerName } from './event-handler-name.ts'
80
81
  import { seedActionAccessorReads } from './action-accessor.ts'
@@ -1226,6 +1227,20 @@ function isLoopRowPropRead(parsed: ParsedExpr, analyzer: AnalyzerContext, scope:
1226
1227
  )
1227
1228
  }
1228
1229
 
1230
+ /**
1231
+ * Whether a conditional branch reads a value the caller supplied that may
1232
+ * be or build a live element (`IRExpression.readsCallerValue`). A loop row's
1233
+ * item, index and destructured names are the row's own data; any other name
1234
+ * a row or callback binds (a `.map()` preamble local) is not known safe.
1235
+ */
1236
+ function branchReadsCallerValue(node: ts.Expression, ctx: TransformContext): boolean {
1237
+ return readsCallerValue(node, ctx.analyzer, name => {
1238
+ const source = ctx.scope.lookup(name)?.binding.source
1239
+ if (source === undefined) return undefined
1240
+ return source === 'item' || source === 'index' || source === 'destructure'
1241
+ })
1242
+ }
1243
+
1229
1244
  /** Set `childrenRead` and `loopRowPropRead` on an expression child from its parse. */
1230
1245
  function attachPropReadFlags(node: IRExpression, parsed: ParsedExpr, analyzer: AnalyzerContext, scope: BindingScope): void {
1231
1246
  const childrenRead = childrenReadOf(parsed, analyzer, scope)
@@ -1250,6 +1265,7 @@ function attachParsedAttrValues(
1250
1265
  if (value.kind === 'template' || value.kind === 'expression') {
1251
1266
  for (const part of value.parts ?? []) {
1252
1267
  if (part.type === 'expression') part.parsed = resolve(part.parsed)
1268
+ else if (part.type === 'ternary' && part.condition.trim()) part.parsedCondition = parse(part.condition.trim())
1253
1269
  }
1254
1270
  }
1255
1271
  if (value.kind === 'expression' || (spreads && value.kind === 'spread')) {
@@ -3639,6 +3655,7 @@ function transformConditionalBranch(
3639
3655
  slotId,
3640
3656
  callsReactiveGetters: callsReactive || undefined,
3641
3657
  hasFunctionCalls: hasCalls || undefined,
3658
+ ...(hasCalls && branchReadsCallerValue(node, ctx) && { readsCallerValue: true as const }),
3642
3659
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
3643
3660
  origin: branchOrigin,
3644
3661
  }