@barefootjs/jsx 0.39.0 → 0.39.2
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/interface.d.ts +19 -0
- package/dist/adapters/interface.d.ts.map +1 -1
- package/dist/adapters/jsx-adapter.d.ts.map +1 -1
- package/dist/adapters/parsed-expr-emitter.d.ts +2 -2
- package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
- package/dist/analyzer.d.ts +19 -0
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/compiler.d.ts.map +1 -1
- package/dist/debug.d.ts.map +1 -1
- package/dist/html-types.d.ts +5 -0
- package/dist/html-types.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1455 -1139
- package/dist/ir-to-client-js/collect-elements.d.ts +17 -1
- package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
- package/dist/ir-to-client-js/reactivity.d.ts +10 -2
- package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
- package/dist/ir-to-client-js/safe-html.d.ts +1 -1
- package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
- package/dist/ir-to-client-js/utils.d.ts +11 -7
- package/dist/ir-to-client-js/utils.d.ts.map +1 -1
- package/dist/jsx-to-ir.d.ts.map +1 -1
- package/dist/literal-member-index.d.ts +6 -0
- package/dist/literal-member-index.d.ts.map +1 -0
- package/dist/scope/binding-scope.d.ts +11 -0
- package/dist/scope/binding-scope.d.ts.map +1 -1
- package/dist/signal-prop-name-collision.d.ts +20 -0
- package/dist/signal-prop-name-collision.d.ts.map +1 -0
- package/dist/ssr-defaults.d.ts.map +1 -1
- package/dist/ssr-seed-plan.d.ts +3 -2
- package/dist/ssr-seed-plan.d.ts.map +1 -1
- package/dist/types.d.ts +44 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +4 -4
- package/src/__tests__/adapter-output.test.ts +142 -0
- package/src/__tests__/binding-scope.test.ts +27 -0
- package/src/__tests__/client-template-escape-soundness.test.ts +17 -0
- package/src/__tests__/conditional-nested-loop-bindings.test.ts +41 -0
- package/src/__tests__/create-mutation.test.ts +30 -0
- package/src/__tests__/create-query.test.ts +52 -0
- package/src/__tests__/debug.test.ts +83 -0
- package/src/__tests__/destructured-from-props-localconst-value.test.ts +3 -2
- package/src/__tests__/ir-fragment-transparency.test.ts +23 -0
- package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +245 -0
- package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +80 -0
- package/src/__tests__/literal-member-index.test.ts +14 -0
- package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +445 -0
- package/src/__tests__/signal-prop-name-collision.test.ts +171 -0
- package/src/__tests__/ssr-defaults.test.ts +6 -7
- package/src/__tests__/ssr-seed-plan.test.ts +23 -0
- package/src/__tests__/staged-ir/02-shadow-guards.test.ts +1 -1
- package/src/__tests__/staged-ir/08-relocate-unit.test.ts +6 -3
- package/src/adapters/interface.ts +19 -0
- package/src/adapters/jsx-adapter.ts +30 -20
- package/src/adapters/parsed-expr-emitter.ts +3 -3
- package/src/analyzer.ts +45 -11
- package/src/compiler.ts +78 -46
- package/src/debug.ts +34 -2
- package/src/html-types.ts +14 -0
- package/src/index.ts +2 -0
- package/src/ir-to-client-js/collect-elements.ts +72 -13
- package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +112 -3
- package/src/ir-to-client-js/reactivity.ts +31 -1
- package/src/ir-to-client-js/safe-html.ts +19 -6
- package/src/ir-to-client-js/utils.ts +130 -15
- package/src/jsx-to-ir.ts +89 -14
- package/src/literal-member-index.ts +12 -0
- package/src/scope/binding-scope.ts +31 -1
- package/src/signal-prop-name-collision.ts +164 -0
- package/src/ssr-defaults.ts +13 -5
- package/src/ssr-seed-plan.ts +26 -3
- package/src/types.ts +47 -0
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { type IRNode, type IRElement, type IRComponent, type IRConditional, type IRLoop, type IRProp, pickAttrMetaFromIR } from '../types.ts'
|
|
6
6
|
import type { ClientJsContext, ConditionalBranchChildComponent, ConditionalBranchReactiveAttr, BranchLoop, ConditionalBranchTextEffect, ConditionalElement, LoopChildBindings, LoopChildBranchSummary, LoopChildConditional, LoopOffset, NestedLoop } from './types.ts'
|
|
7
|
-
import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, type LoopParamSpec } from './utils.ts'
|
|
7
|
+
import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, toHtmlAttrName, type LoopParamSpec } from './utils.ts'
|
|
8
8
|
import { classifyReactivity, needsEffectWrapper, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectConditionalBranchComponentNodes, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings, buildLoopRowScope, anyNameIn } from './reactivity.ts'
|
|
9
9
|
import { irToHtmlTemplate, irToPlaceholderTemplate, irChildrenToJsExpr, jsxChildrenPropGetterExpr, buildLoopSkeletonTemplate, computeSkeletonSlotPaths, renderFlatMapClientBody, renderFlatMapProjectionClientBody, flatMapCallbackHasKeyedLeaf, type SkeletonSlotPaths } from './html-template.ts'
|
|
10
10
|
import { detectRootNamespaceWrapTag } from './control-flow/stringify/template-parse.ts'
|
|
@@ -196,8 +196,14 @@ export function computeLoopSiblingOffsets(root: IRNode): Map<IRLoop, IRNode[]> {
|
|
|
196
196
|
* undecidable fall back to `legacyElementCount` (the pre-#1693 behaviour).
|
|
197
197
|
* Returns `undefined` when nothing precedes the loop (or only non-element
|
|
198
198
|
* nodes do), so the loop keeps bare `children[idx]`.
|
|
199
|
+
*
|
|
200
|
+
* Exported for `collectLoopChildEventsWithNesting` (`reactivity.ts`), which
|
|
201
|
+
* builds its own `NestedLoop` chain for delegated-event metadata and needs
|
|
202
|
+
* the same static-sibling-count resolution the hydration side
|
|
203
|
+
* (`collectInnerLoops`, below) already applies — see that call site's
|
|
204
|
+
* comment (#3240 follow-up).
|
|
199
205
|
*/
|
|
200
|
-
function resolveLoopOffset(preceding: IRNode[] | undefined): LoopOffset | undefined {
|
|
206
|
+
export function resolveLoopOffset(preceding: IRNode[] | undefined): LoopOffset | undefined {
|
|
201
207
|
if (!preceding || preceding.length === 0) return undefined
|
|
202
208
|
let staticCount = 0
|
|
203
209
|
const dynamicTerms: string[] = []
|
|
@@ -411,7 +417,7 @@ export function collectInnerLoops(
|
|
|
411
417
|
}
|
|
412
418
|
|
|
413
419
|
for (const child of n.children) {
|
|
414
|
-
bindings.events.push(...collectLoopChildEventsWithNesting(child))
|
|
420
|
+
bindings.events.push(...collectLoopChildEventsWithNesting(child, [], siblingOffsets))
|
|
415
421
|
}
|
|
416
422
|
}
|
|
417
423
|
|
|
@@ -463,14 +469,15 @@ export function collectInnerLoops(
|
|
|
463
469
|
*
|
|
464
470
|
* Used by both the top-level `case 'loop'` in `collectElements` and the
|
|
465
471
|
* branch-loop collector in `collectBranchLoops`. Each call site applies
|
|
466
|
-
* its own final-emission rule over `innerLoops
|
|
467
|
-
*
|
|
468
|
-
*
|
|
472
|
+
* its own final-emission rule over `innerLoops`. Static top-level loops
|
|
473
|
+
* hydrate existing rows; branch-scoped loops materialize rows via mapArray
|
|
474
|
+
* and therefore use composite rendering for static nested loops too.
|
|
469
475
|
*/
|
|
470
476
|
function decideLoopRendering(
|
|
471
477
|
loop: IRLoop,
|
|
472
478
|
siblingOffsets: Map<IRLoop, IRNode[]>,
|
|
473
479
|
ctx: ClientJsContext | undefined,
|
|
480
|
+
branchScope = false,
|
|
474
481
|
): { useElementReconciliation: boolean; innerLoops: NestedLoop[] | undefined } {
|
|
475
482
|
const hasNestedComps = (loop.nestedComponents?.length ?? 0) > 0
|
|
476
483
|
// Collect inner loops even when the outer item is a child component
|
|
@@ -489,7 +496,7 @@ function decideLoopRendering(
|
|
|
489
496
|
)
|
|
490
497
|
const hasInnerLoops = (innerLoops?.length ?? 0) > 0
|
|
491
498
|
const useElementReconciliation =
|
|
492
|
-
!loop.childComponent && !loop.isStaticArray && (hasNestedComps || hasInnerLoops)
|
|
499
|
+
!loop.childComponent && (!loop.isStaticArray || (branchScope && hasInnerLoops)) && (hasNestedComps || hasInnerLoops)
|
|
493
500
|
return { useElementReconciliation, innerLoops }
|
|
494
501
|
}
|
|
495
502
|
|
|
@@ -1132,6 +1139,60 @@ function collectFromElement(element: IRElement, ctx: ClientJsContext, insideCond
|
|
|
1132
1139
|
const valueStr = attrValueToString(attr.value)
|
|
1133
1140
|
if (!valueStr) continue
|
|
1134
1141
|
|
|
1142
|
+
// #3057: a statically expanded rest-key attribute (`{...rest}` onto
|
|
1143
|
+
// this element, unrolled per-key by `expandSpreadAttribute` because
|
|
1144
|
+
// the rest type is closed) reads the destructured rest OBJECT
|
|
1145
|
+
// (`rest.tag`) — a snapshot taken once when the component
|
|
1146
|
+
// initializes, never a live prop read. The string-level heuristics
|
|
1147
|
+
// below (`needsEffectWrapper`/`decideWrapForAttr`) don't recognize
|
|
1148
|
+
// `rest`/the expanded key as a tracked prop name, so this would
|
|
1149
|
+
// otherwise be classified static and never get a `createEffect` —
|
|
1150
|
+
// exactly the bug this issue reports. Bind it straight to a live
|
|
1151
|
+
// `_p.<key>` read instead, unconditionally: forwarding a prop via
|
|
1152
|
+
// `{...rest}` means it tracks the caller's current value by
|
|
1153
|
+
// definition, so it can never be "static" the way an ordinary
|
|
1154
|
+
// attribute expression can. `insideConditional` below just skips
|
|
1155
|
+
// this element the same way the generic path does (#1071) — unlike
|
|
1156
|
+
// the generic path, `collectBranchReactiveAttrs` does not read
|
|
1157
|
+
// `restExpandedKey`, so a rest key inside a conditional branch gets
|
|
1158
|
+
// no binding at all; that gap is intentionally out of scope for
|
|
1159
|
+
// #3057 (see the PR description). Two cases
|
|
1160
|
+
// fall back to the pre-#3057 classification below instead of this
|
|
1161
|
+
// fast path (both found by review on #3252):
|
|
1162
|
+
// - `attr.name` is an explicit JSX attribute's HTML name too
|
|
1163
|
+
// (e.g. a closed `id` rest key alongside a literal `id="fixed"`
|
|
1164
|
+
// on the same element). An unconditional `_p.id` write would
|
|
1165
|
+
// `removeAttribute` the SSR value whenever the caller doesn't
|
|
1166
|
+
// pass `id`, clobbering the explicit attribute.
|
|
1167
|
+
// - `classifyDOMProp` says this key doesn't reach the DOM as a
|
|
1168
|
+
// plain attribute at all (`ref` / `event` / `skip`, e.g.
|
|
1169
|
+
// `onPing` or `children`). `applyRestAttrs` already excludes
|
|
1170
|
+
// these from its own attribute set for the same reason; an
|
|
1171
|
+
// unconditional `setAttribute` here would stringify a function
|
|
1172
|
+
// or children value onto the element, which the pre-#3057
|
|
1173
|
+
// path never did.
|
|
1174
|
+
const restKeyHtmlName = toHtmlAttrName(attr.name)
|
|
1175
|
+
const collidesWithExplicitAttr = element.attrs.some(
|
|
1176
|
+
other => other !== attr && other.name !== '...' && toHtmlAttrName(other.name) === restKeyHtmlName,
|
|
1177
|
+
)
|
|
1178
|
+
const restKeyDomKind = classifyDOMProp(attr.name).kind
|
|
1179
|
+
if (
|
|
1180
|
+
attr.restExpandedKey &&
|
|
1181
|
+
!collidesWithExplicitAttr &&
|
|
1182
|
+
restKeyDomKind !== 'ref' &&
|
|
1183
|
+
restKeyDomKind !== 'event' &&
|
|
1184
|
+
restKeyDomKind !== 'skip'
|
|
1185
|
+
) {
|
|
1186
|
+
if (insideConditional) continue
|
|
1187
|
+
ctx.reactiveAttrs.push({
|
|
1188
|
+
slotId: element.slotId,
|
|
1189
|
+
attrName: attr.name,
|
|
1190
|
+
expression: `${PROPS_PARAM}.${attr.name}`,
|
|
1191
|
+
...pickAttrMetaFromIR(attr),
|
|
1192
|
+
})
|
|
1193
|
+
continue
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1135
1196
|
// Expand local constant references to detect transitive prop dependencies.
|
|
1136
1197
|
// e.g., `classes` → `` `${baseClasses} ${variantClasses[variant]} ${className}` ``
|
|
1137
1198
|
const expandedResult = expandConstantForReactivity(valueStr, ctx, attr.freeIdentifiers)
|
|
@@ -1282,10 +1343,8 @@ function collectBranchLoops(
|
|
|
1282
1343
|
// the top-level `useElementReconciliation` rule so a `.map()` directly
|
|
1283
1344
|
// inside an outer `.map()` gets its own reactive mapArray even when
|
|
1284
1345
|
// the outer loop lives inside a conditional branch.
|
|
1285
|
-
//
|
|
1286
|
-
//
|
|
1287
|
-
// is handled at the enclosing branch-loop level below (`if (ctx)` block
|
|
1288
|
-
// around `collectLoopChildReactiveTexts`), not per inner loop.
|
|
1346
|
+
// Branch rows are materialized by mapArray even for static arrays.
|
|
1347
|
+
// Collect each inner row's bindings and reconcile nested rows there too.
|
|
1289
1348
|
// flatMap PROJECTION loop — see the top-level handler's note: children
|
|
1290
1349
|
// are SSR-only; the client rides the descriptor mapArray path.
|
|
1291
1350
|
const projectionInner =
|
|
@@ -1295,7 +1354,7 @@ function collectBranchLoops(
|
|
|
1295
1354
|
|
|
1296
1355
|
const { useElementReconciliation, innerLoops: innerLoopsCollected } = projectionInner
|
|
1297
1356
|
? { useElementReconciliation: false, innerLoops: undefined }
|
|
1298
|
-
: decideLoopRendering(n, siblingOffsets,
|
|
1357
|
+
: decideLoopRendering(n, siblingOffsets, ctx, true)
|
|
1299
1358
|
|
|
1300
1359
|
// Build the item template from loop children.
|
|
1301
1360
|
// Use loopDepth=0: this loop gets its own mapArray/mapArrayAnchored call (independent
|
|
@@ -1544,7 +1603,7 @@ export function collectLoopChildBindings(
|
|
|
1544
1603
|
): LoopChildBindings {
|
|
1545
1604
|
const bindings = emptyLoopChildBindings()
|
|
1546
1605
|
for (const child of children) {
|
|
1547
|
-
bindings.events.push(...collectLoopChildEventsWithNesting(child))
|
|
1606
|
+
bindings.events.push(...collectLoopChildEventsWithNesting(child, [], siblingOffsets))
|
|
1548
1607
|
// stopAtReactiveConditionals=true (#2347): this function always also
|
|
1549
1608
|
// collects nested reactive conditionals below via
|
|
1550
1609
|
// `collectLoopChildConditionals`, which gives each its own insert() +
|
|
@@ -324,9 +324,118 @@ function emitStaticIndexLookup(
|
|
|
324
324
|
// Preamble and idx binding run INSIDE the item null guard (BUG-4) — an
|
|
325
325
|
// out-of-range index (stale-DOM race) must short-circuit first.
|
|
326
326
|
ls.push(` if (${param}) {`)
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
327
|
+
// Nested static `.map()` params (#3240): static arrays carry no
|
|
328
|
+
// data-key markers, so — unlike `emitKeyedLookup`'s nested branch, which
|
|
329
|
+
// resolves each level via `closest('[data-key-N]')` — each nested level's
|
|
330
|
+
// item is recovered positionally, the same way hydration wires up a
|
|
331
|
+
// nested static loop's own bindings (`stringify/static-array-child-init.ts`'s
|
|
332
|
+
// `__ic`/`indexOf` shape, #2798): scope a `containerSlotId` lookup inside
|
|
333
|
+
// the previously-resolved row, walk the ORIGINAL event target up to that
|
|
334
|
+
// container's direct child, and read its position. The positional lookups
|
|
335
|
+
// run inside this guard (not above) because a nested `array` expression
|
|
336
|
+
// may read the outer `param` (e.g. `CHOICES[group]`), which must exist
|
|
337
|
+
// first; the params themselves are declared just below, once every
|
|
338
|
+
// level's index has resolved (see `emitNestedIndexParams`'s docstring on
|
|
339
|
+
// why the guard is on the indices, not the params).
|
|
340
|
+
const { guardNames: nestedGuardNames, paramLines: nestedParamLines } = emitNestedIndexParams(ls, ev, '__el', ' ')
|
|
341
|
+
const guarded = nestedGuardNames.length > 0
|
|
342
|
+
if (guarded) ls.push(` if (${nestedGuardNames.join(' && ')}) {`)
|
|
343
|
+
const bodyIndent = guarded ? ' ' : ' '
|
|
344
|
+
for (const line of nestedParamLines) ls.push(`${bodyIndent}${line}`)
|
|
345
|
+
if (preambleLine) ls.push(`${bodyIndent}${preambleLine}`)
|
|
346
|
+
if (idxLine) ls.push(`${bodyIndent}${idxLine}`)
|
|
347
|
+
ls.push(`${bodyIndent};${handlerCall}`)
|
|
348
|
+
if (guarded) ls.push(` }`)
|
|
330
349
|
ls.push(` }`)
|
|
331
350
|
ls.push(` }`)
|
|
332
351
|
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Resolve each nested (inner) `.map()`'s item for an index-based item lookup
|
|
355
|
+
* (#3240). `ev.nestedLoops` is ordered outermost-first (depth 1, 2, …); each
|
|
356
|
+
* entry's `containerSlotId` (the slot id of the element enclosing that
|
|
357
|
+
* level's loop, or `null` when the loop's items are direct children of the
|
|
358
|
+
* previous level's row) is looked up scoped to the previously-resolved row
|
|
359
|
+
* element — never document-wide — so a same-id container in a sibling row
|
|
360
|
+
* never collides. `baseScopeVar` is the already-resolved OUTERMOST row
|
|
361
|
+
* element (`__el`, `static-index`'s own resolved row); the walk-up at every
|
|
362
|
+
* level still starts from the actual event-target slot element
|
|
363
|
+
* (`<childSlotId>El`), since that is the only DOM reference this dispatcher
|
|
364
|
+
* holds — walking it up to become a direct child of each level's container
|
|
365
|
+
* recovers that level's row regardless of how many levels are nested
|
|
366
|
+
* beneath it.
|
|
367
|
+
*
|
|
368
|
+
* Emits the positional index resolution (`__icN`/`__irN`/`__iidxN`) for
|
|
369
|
+
* every level up front, and returns it split into two pieces the caller
|
|
370
|
+
* assembles around the rest of the handler body:
|
|
371
|
+
*
|
|
372
|
+
* - `guardNames`: one `<idxVar> >= 0` condition per level, meant to be
|
|
373
|
+
* `&&`-joined into the guard that wraps the param declarations and the
|
|
374
|
+
* handler call.
|
|
375
|
+
* - `paramLines`: one `const <nested.param> = <array>[<idxVar>]` per
|
|
376
|
+
* level, in depth order, meant to be pushed INSIDE that guard.
|
|
377
|
+
*
|
|
378
|
+
* The guard checks the resolved INDEX, not the item's truthiness — unlike
|
|
379
|
+
* an earlier version of this function, which declared `const <param> =
|
|
380
|
+
* <idx> >= 0 ? <array>[<idx>] : undefined` and left the caller to guard on
|
|
381
|
+
* `<param>` directly. That silently dropped a click on a falsy item
|
|
382
|
+
* (`NUMS = [0, 1, 2]`, clicking `0`) since `if (0)` is false, and threw a
|
|
383
|
+
* `TypeError` for a destructured `nested.param` (`({ id, label }) => ...`
|
|
384
|
+
* destructuring `undefined` on a miss) since `if ({ id, label })` is always
|
|
385
|
+
* true regardless of whether the lookup actually resolved. Guarding on the
|
|
386
|
+
* index and declaring the (possibly-destructured) param only once every
|
|
387
|
+
* level's index is known to be `>= 0` fixes both: a `0` item still passes
|
|
388
|
+
* `__iidxN >= 0`, and a destructured param is never handed `undefined`.
|
|
389
|
+
*
|
|
390
|
+
* Declaring the params in depth order (rather than each next to its own
|
|
391
|
+
* index computation) still lets a nested `array` expression read an outer
|
|
392
|
+
* level's param (e.g. `CHOICES[group]`) — the container/row/index
|
|
393
|
+
* computations for every level never depend on any level's param, only on
|
|
394
|
+
* DOM structure, so they can all run first regardless of param order; only
|
|
395
|
+
* the actual item lookups (`paramLines`) need the depth ordering, and the
|
|
396
|
+
* caller pushes them in the order this function returns them.
|
|
397
|
+
*
|
|
398
|
+
* Returns `{ guardNames: [], paramLines: [] }` (emitting nothing) when
|
|
399
|
+
* `ev.nestedLoops` is empty, so a non-nested event's emitted lines are
|
|
400
|
+
* unchanged.
|
|
401
|
+
*
|
|
402
|
+
* Only `emitStaticIndexLookup` calls this today. `emitDynamicIndexLookup`
|
|
403
|
+
* (the other unkeyed item-lookup shape) never sees a non-empty
|
|
404
|
+
* `ev.nestedLoops`: a dynamic (non-static-array) loop with a nested `.map()`
|
|
405
|
+
* always sets `useElementReconciliation`
|
|
406
|
+
* (`collect-elements.ts`'s `decideLoopRendering`), which routes it to the
|
|
407
|
+
* composite/element-reconciliation emission path — a direct
|
|
408
|
+
* `addEventListener` on each row at creation, not this delegated dispatcher
|
|
409
|
+
* — regardless of whether the outer loop has a key (verified by compiling
|
|
410
|
+
* both a keyed and an unkeyed reactive outer array with a nested static
|
|
411
|
+
* `.map()`: both emit `mapArray` + a direct per-row listener, never
|
|
412
|
+
* `static-index`/`dynamic-index`/`keyed` delegation for the inner event).
|
|
413
|
+
*/
|
|
414
|
+
function emitNestedIndexParams(
|
|
415
|
+
ls: string[],
|
|
416
|
+
ev: LoopChildEvent,
|
|
417
|
+
baseScopeVar: string,
|
|
418
|
+
indent: string,
|
|
419
|
+
): { guardNames: string[]; paramLines: string[] } {
|
|
420
|
+
const evVar = varSlotId(ev.childSlotId)
|
|
421
|
+
const guardNames: string[] = []
|
|
422
|
+
const paramLines: string[] = []
|
|
423
|
+
let scopeVar = baseScopeVar
|
|
424
|
+
for (const nested of ev.nestedLoops) {
|
|
425
|
+
const containerVarName = `__ic${nested.depth}`
|
|
426
|
+
const rowVarName = `__ir${nested.depth}`
|
|
427
|
+
const idxVarName = `__iidx${nested.depth}`
|
|
428
|
+
const containerExpr = nested.containerSlotId
|
|
429
|
+
? `${scopeVar}.querySelector('[bf="${nested.containerSlotId}"]') || ${scopeVar}`
|
|
430
|
+
: scopeVar
|
|
431
|
+
ls.push(`${indent}const ${containerVarName} = ${containerExpr}`)
|
|
432
|
+
ls.push(`${indent}let ${rowVarName} = ${evVar}El`)
|
|
433
|
+
ls.push(`${indent}while (${rowVarName}.parentElement && ${rowVarName}.parentElement !== ${containerVarName}) ${rowVarName} = ${rowVarName}.parentElement`)
|
|
434
|
+
const offsetSuffix = buildLoopChildIndexSubtraction(nested.offset)
|
|
435
|
+
ls.push(`${indent}const ${idxVarName} = ${rowVarName}.parentElement === ${containerVarName} ? Array.from(${containerVarName}.children).indexOf(${rowVarName})${offsetSuffix} : -1`)
|
|
436
|
+
guardNames.push(`${idxVarName} >= 0`)
|
|
437
|
+
paramLines.push(`const ${nested.param} = ${nested.array}[${idxVarName}]`)
|
|
438
|
+
scopeVar = rowVarName
|
|
439
|
+
}
|
|
440
|
+
return { guardNames, paramLines }
|
|
441
|
+
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Reactivity detection: reactive expression checking, event/ref collection.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import { type IRNode, type IRElement, type IRComponent, type IRProp, type LoopParamBinding, type OriginInfo, pickAttrMetaFromIR, isReactiveOrigin } from '../types.ts'
|
|
5
|
+
import { type IRNode, type IRElement, type IRComponent, type IRLoop, type IRProp, type LoopParamBinding, type OriginInfo, pickAttrMetaFromIR, isReactiveOrigin } from '../types.ts'
|
|
6
6
|
import type {
|
|
7
7
|
ClientJsContext,
|
|
8
8
|
ConditionalBranchEvent,
|
|
@@ -15,6 +15,16 @@ import type {
|
|
|
15
15
|
NestedLoop,
|
|
16
16
|
} from './types.ts'
|
|
17
17
|
import { attrValueToString, freeIdsFromRefs, tokenContainsIdent } from './utils.ts'
|
|
18
|
+
// `resolveLoopOffset` lives in `collect-elements.ts` (the sibling-offset
|
|
19
|
+
// pre-pass, #1693) — imported here (not duplicated) so the delegated-event
|
|
20
|
+
// `NestedLoop` chain built below resolves the SAME static-sibling-count
|
|
21
|
+
// offset the hydration-side `NestedLoop` (`collectInnerLoops`) already
|
|
22
|
+
// applies, rather than growing a second copy of that resolution (#3240
|
|
23
|
+
// follow-up). `collect-elements.ts` imports several collectors back from
|
|
24
|
+
// this module, so this is a deliberate circular import; both sides only use
|
|
25
|
+
// the other's export inside function bodies invoked well after module init,
|
|
26
|
+
// never at top-level, so the cycle resolves safely.
|
|
27
|
+
import { resolveLoopOffset } from './collect-elements.ts'
|
|
18
28
|
import { expandConstantForReactivity } from './prop-handling.ts'
|
|
19
29
|
import { extractFreeIdentifiersFromText } from './csr-substitute.ts'
|
|
20
30
|
import { walkIR, stopAt } from './walker.ts'
|
|
@@ -570,6 +580,14 @@ export function collectLoopChildEvents(node: IRNode): LoopChildEvent[] {
|
|
|
570
580
|
export function collectLoopChildEventsWithNesting(
|
|
571
581
|
node: IRNode,
|
|
572
582
|
initialNestingStack: NestedLoop[] = [],
|
|
583
|
+
/**
|
|
584
|
+
* The whole-component sibling-offset pre-pass (`computeLoopSiblingOffsets`,
|
|
585
|
+
* `collect-elements.ts`), keyed by IR loop-node identity. Optional — a
|
|
586
|
+
* caller with no sibling-offset data (none exist today) gets `nested.offset`
|
|
587
|
+
* left `undefined`, same as before #3240's follow-up fix, rather than a
|
|
588
|
+
* required param forcing every call site to thread an empty Map.
|
|
589
|
+
*/
|
|
590
|
+
siblingOffsets?: Map<IRLoop, IRNode[]>,
|
|
573
591
|
): LoopChildEvent[] {
|
|
574
592
|
type Scope = {
|
|
575
593
|
nestingStack: NestedLoop[]
|
|
@@ -625,6 +643,18 @@ export function collectLoopChildEventsWithNesting(
|
|
|
625
643
|
markerId: l.markerId,
|
|
626
644
|
containerSlotId: scope.lastElementSlotId,
|
|
627
645
|
bindings: emptyLoopChildBindings(),
|
|
646
|
+
// #3240 follow-up: a static-index delegated event resolves each
|
|
647
|
+
// nested level's item POSITIONALLY (`emitStaticIndexLookup` /
|
|
648
|
+
// `emitNestedIndexParams` in `stringify/event-delegation.ts`),
|
|
649
|
+
// so this level's item is wrong whenever anything precedes its
|
|
650
|
+
// `.map()` within its container (a static sibling, or another
|
|
651
|
+
// loop sharing the same parent) and this offset is left unset —
|
|
652
|
+
// the keyed path's nested resolution (`data-key-N` + `find()`)
|
|
653
|
+
// never needed it, which is why this field went unset from
|
|
654
|
+
// #2189 through the original #3240 fix. Resolved the same way
|
|
655
|
+
// the hydration-side `NestedLoop` does (`collectInnerLoops`
|
|
656
|
+
// above, `offset: resolveLoopOffset(siblingOffsets.get(n))`).
|
|
657
|
+
offset: siblingOffsets ? resolveLoopOffset(siblingOffsets.get(l)) : undefined,
|
|
628
658
|
},
|
|
629
659
|
],
|
|
630
660
|
})
|
|
@@ -37,6 +37,7 @@
|
|
|
37
37
|
*/
|
|
38
38
|
|
|
39
39
|
import type { IRExpression } from '../types.ts'
|
|
40
|
+
import { parseExpression, type ParsedExpr } from '../expression-parser.ts'
|
|
40
41
|
|
|
41
42
|
/**
|
|
42
43
|
* A JS expression string that evaluates, in the client template, to HTML
|
|
@@ -170,20 +171,33 @@ export const EMPTY_MARKUP: SafeHtml = safeHtml("''")
|
|
|
170
171
|
|
|
171
172
|
/**
|
|
172
173
|
* Recognizes a JSX child-position expression that is exactly a reference to
|
|
173
|
-
* the reserved `children` prop
|
|
174
|
+
* the reserved `children` prop, optionally with `?? ''`: bare `children` (destructured) or
|
|
174
175
|
* `<receiver>.children` for any single-identifier receiver (`props.children`,
|
|
175
176
|
* a custom props-param name, a loop-scoped alias closing over props, ...).
|
|
176
177
|
*
|
|
177
178
|
* Deliberately LOOSER than `isTransparentFragment` (`jsx-to-ir.ts`), which
|
|
178
179
|
* runs on the TS AST with the analyzer-resolved props name in hand. This
|
|
179
|
-
* layer
|
|
180
|
+
* layer parses IR expressions without analyzer context, so any single-identifier receiver
|
|
180
181
|
* is the available approximation. The looseness costs nothing measurable: an
|
|
181
182
|
* unrelated `.children` member (a tree node's own `children` array, say) is a
|
|
182
183
|
* reactive member expression that gets a `slotId` and takes the slotted arm
|
|
183
184
|
* of `spliceChildValue` before this predicate is consulted.
|
|
184
185
|
*/
|
|
185
186
|
function isChildrenPassthroughExpr(expr: string): boolean {
|
|
186
|
-
return
|
|
187
|
+
return isChildrenPassthrough(parseExpression(expr))
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function isChildrenPassthrough(expr: ParsedExpr): boolean {
|
|
191
|
+
if (expr.kind === 'identifier') return expr.name === 'children'
|
|
192
|
+
if (expr.kind === 'member') {
|
|
193
|
+
return expr.object.kind === 'identifier' && expr.property === 'children'
|
|
194
|
+
&& !expr.computed && !expr.optional
|
|
195
|
+
}
|
|
196
|
+
// An empty fallback adds no untrusted text to the compiler-built markup.
|
|
197
|
+
// Other fallbacks still take the escape-by-default path.
|
|
198
|
+
return expr.kind === 'logical' && expr.op === '??'
|
|
199
|
+
&& expr.right.kind === 'literal' && expr.right.value === ''
|
|
200
|
+
&& isChildrenPassthrough(expr.left)
|
|
187
201
|
}
|
|
188
202
|
|
|
189
203
|
export interface ChildSpliceContext {
|
|
@@ -220,7 +234,7 @@ export interface ChildSpliceContext {
|
|
|
220
234
|
* 6. otherwise → `escapedText`
|
|
221
235
|
*
|
|
222
236
|
* Arm 5 tests BOTH `node.expr` (the original source text, stable across
|
|
223
|
-
* builders) and the caller's resolved form (
|
|
237
|
+
* builders) and the caller's resolved form (with parentheses handled structurally): a
|
|
224
238
|
* destructured-and-renamed children (`const { children: kids } = props`)
|
|
225
239
|
* reads `kids` in the source and `(_p.children)` after substitution, and
|
|
226
240
|
* either alone misses one of the two shapes (#2786).
|
|
@@ -235,8 +249,7 @@ export function spliceChildValue(
|
|
|
235
249
|
if (node.slotId) {
|
|
236
250
|
return cx.markupSlotIds?.has(node.slotId) ? escapedTextOrMarkup(valueExpr) : escapedText(valueExpr)
|
|
237
251
|
}
|
|
238
|
-
|
|
239
|
-
if (isChildrenPassthroughExpr(node.expr) || isChildrenPassthroughExpr(resolved)) {
|
|
252
|
+
if (isChildrenPassthroughExpr(node.expr) || isChildrenPassthroughExpr(valueExpr)) {
|
|
240
253
|
return childrenMarkup(valueExpr)
|
|
241
254
|
}
|
|
242
255
|
return escapedText(valueExpr)
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import ts from 'typescript'
|
|
7
7
|
import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode, IRFragment, ComponentIR } from '../types.ts'
|
|
8
8
|
import type { TopLevelLoop, BranchLoop, LoopOffset } from './types.ts'
|
|
9
|
+
import { isNonReferenceIdentifierPosition } from '../analyzer.ts'
|
|
9
10
|
import { buildLoopChainExpr } from '../loop-chain.ts'
|
|
10
11
|
import { templatePartsToJsExpr } from '../template-parts.ts'
|
|
11
12
|
import { escapeIdentifierForRegex, ID_BOUNDARY_BEFORE, ID_BOUNDARY_AFTER } from '../identifier-pattern.ts'
|
|
@@ -683,9 +684,12 @@ function renderLoopBindingAccess(b: LoopParamBinding, base: string): string {
|
|
|
683
684
|
* e.g., "item.text" → "item().text", "item" → "item()"
|
|
684
685
|
* Does not double-wrap: "item().text" stays "item().text"
|
|
685
686
|
*
|
|
686
|
-
*
|
|
687
|
-
*
|
|
688
|
-
*
|
|
687
|
+
* The plain-param branch (`rewriteIdentifierAsAccessor`) walks the real AST,
|
|
688
|
+
* so it is inherently string/template-literal-context aware (a CSS class
|
|
689
|
+
* name like "preview-field" never surfaces as an `Identifier` node when
|
|
690
|
+
* `paramName` is "field") AND skips object-literal keys, shorthand
|
|
691
|
+
* properties, and member/property names — tokens that spell `paramName`
|
|
692
|
+
* without referencing it (#3239).
|
|
689
693
|
*
|
|
690
694
|
* When `bindings` is supplied (destructured `.map()` callback, #951), each
|
|
691
695
|
* binding name is rewritten to `__bfItem()${path}` instead of wrapping the
|
|
@@ -717,12 +721,7 @@ export function wrapLoopParamAsAccessor(
|
|
|
717
721
|
if (bindings && bindings.length > 0) {
|
|
718
722
|
result = rewriteLoopBindingRefs(expr, bindings, '__bfItem()')
|
|
719
723
|
} else {
|
|
720
|
-
|
|
721
|
-
// (`$1`, `$&`, …) — a plain string replacement would risk `String.replace`
|
|
722
|
-
// reading those as backreference/whole-match sequences, so use a replacer
|
|
723
|
-
// function to insert the accessor text literally (#2592).
|
|
724
|
-
const re = new RegExp(`${ID_BOUNDARY_BEFORE}${escapeIdentifierForRegex(paramName)}(?!\\s*\\()(?!-)${ID_BOUNDARY_AFTER}`, 'gu')
|
|
725
|
-
result = replaceInExprContexts(expr, re, () => `${paramName}()`)
|
|
724
|
+
result = rewriteIdentifierAsAccessor(expr, paramName)
|
|
726
725
|
}
|
|
727
726
|
if (indexParam && indexParam !== paramName) {
|
|
728
727
|
result = wrapIndexParamAsAccessor(result, indexParam)
|
|
@@ -731,10 +730,11 @@ export function wrapLoopParamAsAccessor(
|
|
|
731
730
|
}
|
|
732
731
|
|
|
733
732
|
/**
|
|
734
|
-
* The index-only half of `wrapLoopParamAsAccessor` — same
|
|
735
|
-
* identifier
|
|
736
|
-
*
|
|
737
|
-
*
|
|
733
|
+
* The index-only half of `wrapLoopParamAsAccessor` — same AST-aware
|
|
734
|
+
* identifier rewrite (`rewriteIdentifierAsAccessor`), own identifier.
|
|
735
|
+
* Factored out so `wrapLoopParamAsAccessor` can run it as a second pass
|
|
736
|
+
* regardless of which item-rewrite branch (bindings vs. plain param) ran
|
|
737
|
+
* first (#2859).
|
|
738
738
|
*
|
|
739
739
|
* Also exported standalone for `build-loop.ts`/`build-branch-loop.ts`: a
|
|
740
740
|
* plain loop's `template`/`mapPreambleWrapped` are built ONCE, before lazy
|
|
@@ -746,8 +746,123 @@ export function wrapLoopParamAsAccessor(
|
|
|
746
746
|
* is NOT going lazy.
|
|
747
747
|
*/
|
|
748
748
|
export function wrapIndexParamAsAccessor(expr: string, indexParam: string): string {
|
|
749
|
-
|
|
750
|
-
|
|
749
|
+
return rewriteIdentifierAsAccessor(expr, indexParam)
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* AST-aware engine behind `wrapLoopParamAsAccessor`'s plain-param branch and
|
|
754
|
+
* `wrapIndexParamAsAccessor`: rewrite every genuine value reference to
|
|
755
|
+
* `name` in `expr` into `${name}()`, while leaving alone every token that
|
|
756
|
+
* merely SPELLS `name` without referencing it — an object-literal key
|
|
757
|
+
* (`{ name: 1 }`), a shorthand property (`{ name }`, expanded to
|
|
758
|
+
* `{ name: name() }` in one edit — the same transformation #1244 gave the
|
|
759
|
+
* destructured-binding path via `expandShorthandBindings`), and a
|
|
760
|
+
* member/property name (`obj.name`, `obj?.name`).
|
|
761
|
+
*
|
|
762
|
+
* The previous implementation was a `\bname\b`-style regex
|
|
763
|
+
* (`ID_BOUNDARY_BEFORE`/`AFTER` only know about identifier-character
|
|
764
|
+
* boundaries, not JS grammar), so it matched those non-reference tokens too:
|
|
765
|
+
* a key or shorthand rewrite produces invalid JS (`{ name(): 1 }`,
|
|
766
|
+
* `{ name() }`) that fails at parse time; a member-name rewrite produces
|
|
767
|
+
* valid-but-wrong JS (`obj.name()`) that throws `TypeError: obj.name is not
|
|
768
|
+
* a function` at row-creation time (#3239). Parsing the real AST — the same
|
|
769
|
+
* technique `expandShorthandBindings` already uses below — makes each of
|
|
770
|
+
* those positions a type of AST node this function can name and skip,
|
|
771
|
+
* instead of a regex guessing from surrounding characters.
|
|
772
|
+
*
|
|
773
|
+
* A nested declaration that re-binds `name` (a parameter, a `const`/`let`,
|
|
774
|
+
* or a destructured local) is deliberately NOT skipped, unlike
|
|
775
|
+
* `analyzer.ts`'s rename `classify()`: this rewrite has no scope tracking,
|
|
776
|
+
* so it cannot tell a reference to the shadowing local from a reference to
|
|
777
|
+
* the outer loop param past that point, and silently wrapping only the
|
|
778
|
+
* OUTER-scope references while leaving the shadowed ones alone (or vice
|
|
779
|
+
* versa) would just move the #3239 bug rather than fix it. Wrapping the
|
|
780
|
+
* shadowing declaration's own name is always a syntax break at the
|
|
781
|
+
* declaration site itself (`const name = 1` → `const name() = 1`, `(name)
|
|
782
|
+
* => …` → `(name()) => …` — a call can't legally appear where a binding
|
|
783
|
+
* name is expected), so the module fails to parse instead of silently
|
|
784
|
+
* running with the wrong value — the same loud, build-time failure the old
|
|
785
|
+
* regex produced for this shape (it had no shadow-awareness either).
|
|
786
|
+
*
|
|
787
|
+
* A NAMED function expression is the one shadowing shape this function
|
|
788
|
+
* skips wholesale rather than leaving loud: `(function name() { ... })`'s
|
|
789
|
+
* own name is scoped to exactly that expression's body and nowhere else, so
|
|
790
|
+
* `visit` never descends into it at all once it sees the self-shadowing
|
|
791
|
+
* name — no reference inside can possibly mean the outer `name`. A
|
|
792
|
+
* `function`/`class` DECLARATION's name is different: its binding reaches
|
|
793
|
+
* into the surrounding scope too (a function declaration's name is hoisted
|
|
794
|
+
* above it; a class declaration's own static/instance members can
|
|
795
|
+
* self-reference it), so the same whole-subtree skip isn't sound here —
|
|
796
|
+
* a self-reference to a `function`/`class` declaration whose name happens
|
|
797
|
+
* to match `name` is still silently misrewritten, an accepted
|
|
798
|
+
* pre-existing-shaped gap the old regex had too (the "followed by `(`"
|
|
799
|
+
* exclusion below only protects the declaration's OWN name token, not
|
|
800
|
+
* references reachable from within or after it).
|
|
801
|
+
*/
|
|
802
|
+
function rewriteIdentifierAsAccessor(expr: string, name: string): string {
|
|
803
|
+
// Fast path: `name` doesn't occur in the text at all → nothing to rewrite.
|
|
804
|
+
// A cheap substring check only ever causes an unnecessary parse below
|
|
805
|
+
// (e.g. `name` occurs only as part of a longer identifier), never a wrong
|
|
806
|
+
// answer, since the AST walk re-checks the exact identifier text.
|
|
807
|
+
if (!expr.includes(name)) return expr
|
|
808
|
+
|
|
809
|
+
const wrapped = `(${expr})`
|
|
810
|
+
const sf = ts.createSourceFile('__bf_expr.ts', wrapped, ts.ScriptTarget.Latest, /* setParentNodes */ true)
|
|
811
|
+
const edits: Array<{ start: number; end: number; replacement: string }> = []
|
|
812
|
+
|
|
813
|
+
const visit = (node: ts.Node): void => {
|
|
814
|
+
// A named function expression's own name is scoped to exactly its own
|
|
815
|
+
// body, so nothing reachable inside it can refer to the outer `name` —
|
|
816
|
+
// skip the whole subtree instead of only its declaration-name
|
|
817
|
+
// identifier (see this function's docstring for why a `function`/
|
|
818
|
+
// `class` DECLARATION can't get the same treatment this cheaply).
|
|
819
|
+
if (ts.isFunctionExpression(node) && node.name?.text === name) return
|
|
820
|
+
|
|
821
|
+
if (ts.isIdentifier(node) && node.text === name) {
|
|
822
|
+
const p = node.parent
|
|
823
|
+
// Pure-key / non-reference positions — never rewrite. Shared with
|
|
824
|
+
// `analyzer.ts`'s factory-rename `classify()`, which answers the same
|
|
825
|
+
// "is this identifier actually a value reference" question.
|
|
826
|
+
if (isNonReferenceIdentifierPosition(node)) return
|
|
827
|
+
// A function declaration's own name is always followed by `(` in
|
|
828
|
+
// valid source, which is exactly the shape the old
|
|
829
|
+
// `\bname\b(?!\s*\()`-style regex used to recognize and skip. Leaving
|
|
830
|
+
// it unwrapped (rather than declining loudly, as the shadowing
|
|
831
|
+
// declarations below do) matches the old behavior instead of
|
|
832
|
+
// regressing code that used to compile. A `class name {}`
|
|
833
|
+
// declaration's name is followed by `{`/`extends`, not `(`, so the
|
|
834
|
+
// old regex did NOT protect it either — wrapping it is a pre-existing
|
|
835
|
+
// syntax break, not a regression, so it's left to the shadowing-decl
|
|
836
|
+
// path below like any other declaration name.
|
|
837
|
+
if (ts.isFunctionDeclaration(p) && p.name === node) return
|
|
838
|
+
if (ts.isCallExpression(p) && p.expression === node) return // already `name()` — no double-wrap (#2592)
|
|
839
|
+
if (ts.isNewExpression(p) && p.expression === node) return // `new name()` — same "followed by (" shape as a call
|
|
840
|
+
|
|
841
|
+
// Shorthand property (`{ name }`) expands key + wraps value in one
|
|
842
|
+
// edit — the plain-param analogue of `expandShorthandBindings` below.
|
|
843
|
+
// Every other reachable position here is a genuine value reference —
|
|
844
|
+
// OR a shadowing declaration name (nested parameter/`const`/`let`/
|
|
845
|
+
// destructured local): both get wrapped, per this function's
|
|
846
|
+
// docstring on why a shadow is left to fail loudly rather than
|
|
847
|
+
// silently misrewritten.
|
|
848
|
+
const isShorthand = ts.isShorthandPropertyAssignment(p) && p.name === node
|
|
849
|
+
const start = node.getStart(sf) - 1
|
|
850
|
+
const end = node.getEnd() - 1
|
|
851
|
+
edits.push({ start, end, replacement: isShorthand ? `${name}: ${name}()` : `${name}()` })
|
|
852
|
+
return
|
|
853
|
+
}
|
|
854
|
+
ts.forEachChild(node, visit)
|
|
855
|
+
}
|
|
856
|
+
visit(sf)
|
|
857
|
+
|
|
858
|
+
if (edits.length === 0) return expr
|
|
859
|
+
// Apply right-to-left so earlier offsets stay valid as later ones grow.
|
|
860
|
+
edits.sort((a, b) => b.start - a.start)
|
|
861
|
+
let out = expr
|
|
862
|
+
for (const e of edits) {
|
|
863
|
+
out = out.slice(0, e.start) + e.replacement + out.slice(e.end)
|
|
864
|
+
}
|
|
865
|
+
return out
|
|
751
866
|
}
|
|
752
867
|
|
|
753
868
|
/**
|