@barefootjs/jsx 0.39.0 → 0.39.1

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 (47) hide show
  1. package/dist/adapters/interface.d.ts +19 -0
  2. package/dist/adapters/interface.d.ts.map +1 -1
  3. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  4. package/dist/analyzer.d.ts +19 -0
  5. package/dist/analyzer.d.ts.map +1 -1
  6. package/dist/compiler.d.ts.map +1 -1
  7. package/dist/debug.d.ts.map +1 -1
  8. package/dist/html-types.d.ts +5 -0
  9. package/dist/html-types.d.ts.map +1 -1
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +195 -68
  13. package/dist/ir-to-client-js/collect-elements.d.ts +17 -1
  14. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  15. package/dist/ir-to-client-js/reactivity.d.ts +10 -2
  16. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/utils.d.ts +11 -7
  18. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  19. package/dist/ssr-defaults.d.ts.map +1 -1
  20. package/dist/ssr-seed-plan.d.ts.map +1 -1
  21. package/dist/types.d.ts +44 -0
  22. package/dist/types.d.ts.map +1 -1
  23. package/package.json +2 -2
  24. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +4 -4
  25. package/src/__tests__/adapter-output.test.ts +142 -0
  26. package/src/__tests__/create-mutation.test.ts +30 -0
  27. package/src/__tests__/create-query.test.ts +52 -0
  28. package/src/__tests__/debug.test.ts +83 -0
  29. package/src/__tests__/ir-fragment-transparency.test.ts +23 -0
  30. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +245 -0
  31. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +80 -0
  32. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +445 -0
  33. package/src/adapters/interface.ts +19 -0
  34. package/src/adapters/jsx-adapter.ts +30 -20
  35. package/src/analyzer.ts +35 -11
  36. package/src/compiler.ts +78 -46
  37. package/src/debug.ts +34 -2
  38. package/src/html-types.ts +14 -0
  39. package/src/index.ts +1 -0
  40. package/src/ir-to-client-js/collect-elements.ts +64 -4
  41. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +112 -3
  42. package/src/ir-to-client-js/reactivity.ts +31 -1
  43. package/src/ir-to-client-js/utils.ts +130 -15
  44. package/src/jsx-to-ir.ts +75 -12
  45. package/src/ssr-defaults.ts +10 -0
  46. package/src/ssr-seed-plan.ts +12 -1
  47. package/src/types.ts +47 -0
package/src/compiler.ts CHANGED
@@ -166,6 +166,14 @@ function compileMultipleComponents(
166
166
  const files: FileOutput[] = []
167
167
  const errors: CompileResult['errors'] = []
168
168
  const adapter = options.adapter
169
+ // `emitsTemplates: false` (CSR) — nothing will ever read this file's
170
+ // markedTemplate, so every assembly step below (per-component module
171
+ // exports AND the combined multi-component template) skips straight to
172
+ // empty rather than trusting `generate()`'s own output to already be
173
+ // empty. One flag, read at both sites, so the invariant can't drift
174
+ // between them the way `moduleExports`-only skip did before it covered
175
+ // the combined-template site too (#3234).
176
+ const skipTemplateAssembly = adapter.emitsTemplates === false
169
177
 
170
178
  // --- Pass 1: analyze + jsxToIR for ALL components ---
171
179
  const entries: { componentIR: ComponentIR; ctx: ReturnType<typeof analyzeComponent> }[] = []
@@ -437,12 +445,14 @@ function compileMultipleComponents(
437
445
  scriptAssets: options.scriptAssets,
438
446
  preloadAssets: options.preloadAssets,
439
447
  })
440
- const moduleExports = generateModuleExports(
441
- componentIR,
442
- fileWideInlineExported,
443
- options.rewriteRelativeImport,
444
- { skipValueDeclarations: adapterOutput.sections.moduleConstantsIncludeExports },
445
- )
448
+ const moduleExports = skipTemplateAssembly
449
+ ? ''
450
+ : generateModuleExports(
451
+ componentIR,
452
+ fileWideInlineExported,
453
+ options.rewriteRelativeImport,
454
+ { skipValueDeclarations: adapterOutput.sections.moduleConstantsIncludeExports },
455
+ )
446
456
 
447
457
  const s = adapterOutput.sections
448
458
  const imports = s.imports
@@ -523,52 +533,66 @@ function compileMultipleComponents(
523
533
  return { files, errors }
524
534
  }
525
535
 
526
- // Merge imports from all components. Named imports from the same source
527
- // are combined into their first occurrence rather than deduplicated by
528
- // exact line: in a multi-component file each component emits its own
529
- // `import { … } from '@barefootjs/hono/utils'` listing only the symbols
530
- // it uses, so plain line-dedup leaves several statements that re-declare
531
- // the same binding (e.g. `bfComment`). Bun tolerates the redeclaration,
532
- // but stricter ESM parsers — including Deno, used to render the SSR
533
- // template — reject it as a SyntaxError.
534
- const mergedImports = mergeTemplateImports(
535
- allOutputs.flatMap(o => (o.imports ? o.imports.split('\n') : [])),
536
- )
537
-
538
- // Combine unique type definitions
539
- const seenTypes = new Set<string>()
540
- const uniqueTypes: string[] = []
541
- for (const output of allOutputs) {
542
- if (output.types && !seenTypes.has(output.types)) {
543
- seenTypes.add(output.types)
544
- uniqueTypes.push(output.types)
536
+ // `generate()`'s own `sections` (imports/types/component) aren't
537
+ // guaranteed empty just because `moduleExports` was skipped above —
538
+ // nothing in the `TemplateAdapter` contract stops a future
539
+ // `emitsTemplates: false` adapter from returning non-empty sections.
540
+ // Reusing `skipTemplateAssembly` here mirrors `compileJSX`'s
541
+ // single-component short-circuit, so the invariant ("this adapter's
542
+ // markedTemplate is always empty") is enforced once per adapter, not
543
+ // once per adapter per component-count code path (#3234).
544
+ let combinedTemplate: string
545
+ if (skipTemplateAssembly) {
546
+ combinedTemplate = ''
547
+ } else {
548
+ // Merge imports from all components. Named imports from the same
549
+ // source are combined into their first occurrence rather than
550
+ // deduplicated by exact line: in a multi-component file each
551
+ // component emits its own `import { … } from '@barefootjs/hono/utils'`
552
+ // listing only the symbols it uses, so plain line-dedup leaves
553
+ // several statements that re-declare the same binding (e.g.
554
+ // `bfComment`). Bun tolerates the redeclaration, but stricter ESM
555
+ // parsers — including Deno, used to render the SSR template — reject
556
+ // it as a SyntaxError.
557
+ const mergedImports = mergeTemplateImports(
558
+ allOutputs.flatMap(o => (o.imports ? o.imports.split('\n') : [])),
559
+ )
560
+
561
+ // Combine unique type definitions
562
+ const seenTypes = new Set<string>()
563
+ const uniqueTypes: string[] = []
564
+ for (const output of allOutputs) {
565
+ if (output.types && !seenTypes.has(output.types)) {
566
+ seenTypes.add(output.types)
567
+ uniqueTypes.push(output.types)
568
+ }
545
569
  }
546
- }
547
570
 
548
- // Deduplicate module-level exports across components
549
- const seenModuleExports = new Set<string>()
550
- const uniqueModuleExports: string[] = []
551
- for (const output of allOutputs) {
552
- if (output.moduleExports) {
553
- for (const line of output.moduleExports.split('\n')) {
554
- if (line.trim() && !seenModuleExports.has(line)) {
555
- seenModuleExports.add(line)
556
- uniqueModuleExports.push(line)
571
+ // Deduplicate module-level exports across components
572
+ const seenModuleExports = new Set<string>()
573
+ const uniqueModuleExports: string[] = []
574
+ for (const output of allOutputs) {
575
+ if (output.moduleExports) {
576
+ for (const line of output.moduleExports.split('\n')) {
577
+ if (line.trim() && !seenModuleExports.has(line)) {
578
+ seenModuleExports.add(line)
579
+ uniqueModuleExports.push(line)
580
+ }
557
581
  }
558
582
  }
559
583
  }
560
- }
561
584
 
562
- // Combine all components
563
- const combinedTemplate = [
564
- mergedImports,
565
- moduleStatementsOrdered.join('\n\n'),
566
- uniqueTypes.join('\n\n'),
567
- uniqueModuleExports.length > 0 ? uniqueModuleExports.join('\n') : '',
568
- ...allOutputs.map(o => o.component),
569
- ]
570
- .filter(Boolean)
571
- .join('\n\n')
585
+ // Combine all components
586
+ combinedTemplate = [
587
+ mergedImports,
588
+ moduleStatementsOrdered.join('\n\n'),
589
+ uniqueTypes.join('\n\n'),
590
+ uniqueModuleExports.length > 0 ? uniqueModuleExports.join('\n') : '',
591
+ ...allOutputs.map(o => o.component),
592
+ ]
593
+ .filter(Boolean)
594
+ .join('\n\n')
595
+ }
572
596
 
573
597
  files.push({
574
598
  path: filePath.replace(/\.tsx?$/, adapter.extension),
@@ -856,6 +880,14 @@ export function compileJSX(
856
880
  let content: string
857
881
  if (adapter.templatesPerComponent) {
858
882
  content = adapterOutput.template
883
+ } else if (adapter.emitsTemplates === false) {
884
+ // Nothing will ever read this file's markedTemplate (CSR) — skip
885
+ // assembly entirely, module-level value exports included. Otherwise a
886
+ // component file that also exports a plain constant/function would
887
+ // produce a markedTemplate whose only content is that export, which
888
+ // `@barefootjs/vite`'s `assertNoRealTemplateOutput` treats as real
889
+ // template output requiring a configured `templates` dir (#3234).
890
+ content = ''
859
891
  } else {
860
892
  const moduleExports = generateModuleExports(componentIR, undefined, options.rewriteRelativeImport, {
861
893
  skipValueDeclarations: s.moduleConstantsIncludeExports,
package/src/debug.ts CHANGED
@@ -23,6 +23,7 @@ import type {
23
23
  SourceLocation,
24
24
  OriginInfo,
25
25
  } from './types.ts'
26
+ import { isElidedFactoryGetter } from './types.ts'
26
27
  import { analyzeComponent, listComponentFunctions } from './analyzer.ts'
27
28
  import { jsxToIR } from './jsx-to-ir.ts'
28
29
  import { buildMetadata } from './compiler.ts'
@@ -567,7 +568,7 @@ export function buildGraphFromIR(ir: ComponentIR): ComponentGraph {
567
568
  for (const f of factories) for (const dep of f.requestDeps) addConsumer(dep, `query:${f.key}`, true)
568
569
  for (const m of memos) m.consumers = memoConsumers.get(m.name) ?? []
569
570
 
570
- const signals: SignalNode[] = meta.signals.filter(s => !(s.factory && s.getterElided)).map(s => {
571
+ const signals: SignalNode[] = meta.signals.filter(s => !isElidedFactoryGetter(s)).map(s => {
571
572
  const factory = factoryOf.get(s)
572
573
  return {
573
574
  kind: 'signal',
@@ -2181,7 +2182,38 @@ function collectDomBindings(
2181
2182
  // `hasFunctionCalls` without reactive-getter hit is the fallback case
2182
2183
  // (e.g. `getItems().map(...)` with an opaque helper).
2183
2184
  if (node.slotId) {
2184
- const deps = extractReactiveDeps(node.array, signalGetters, memoNames)
2185
+ // #3246: `.filter()` / `.sort()` predicates are lifted off the chain
2186
+ // into `IRLoop.filterPredicate` / `.sortComparator` during IR
2187
+ // construction (`loop-chain.ts`) and kept separate from `array` — so
2188
+ // a signal/memo read inside either callback (`items().filter(t =>
2189
+ // filter() === 'all' || !t.done)`) never showed up in the loop's own
2190
+ // deps, even though that read is exactly why the loop re-renders.
2191
+ // (The `/* @client */` path keeps the whole chain in `array`, which
2192
+ // is why the edge was already there in that case.) Collect each
2193
+ // callback's reads too, shadow-guarded via the shared `BindingScope`
2194
+ // service — `enterCallback` exists for exactly this ("a filter
2195
+ // predicate's `x`, a sort comparator's `(a, b)`", see its doc
2196
+ // comment) — so a predicate/comparator that names its parameter the
2197
+ // same as an unrelated signal isn't mistaken for a real read of it.
2198
+ // Built on `scope` (not `childScope` below): the filter/sort
2199
+ // callback's own param(s) are a sibling scope to the loop row, not
2200
+ // nested under it.
2201
+ //
2202
+ // The `sortComparator` half is defensive: `classifySortOperand`
2203
+ // (expression-parser.ts) can't route a signal call into it under
2204
+ // today's grammar, so this branch is untested in practice.
2205
+ const { filterPredicate, sortComparator } = node
2206
+ const callbackDeps = (raw: string, params: string[]) => {
2207
+ const callbackScope = scope.enterCallback(params)
2208
+ return extractReactiveDeps(raw, signalGetters, memoNames).filter(name => !callbackScope.isBound(name))
2209
+ }
2210
+ const deps = [
2211
+ ...new Set([
2212
+ ...extractReactiveDeps(node.array, signalGetters, memoNames),
2213
+ ...(filterPredicate ? callbackDeps(filterPredicate.raw, [filterPredicate.param]) : []),
2214
+ ...(sortComparator ? callbackDeps(sortComparator.raw, [sortComparator.paramA, sortComparator.paramB]) : []),
2215
+ ]),
2216
+ ]
2185
2217
  // An inner loop whose array reads an outer loop param (`r.tags.map(...)`)
2186
2218
  // is reactive per item — use the resolved `arrayFreeIdentifiers`.
2187
2219
  const loopReactive =
package/src/html-types.ts CHANGED
@@ -93,6 +93,16 @@ export interface HTMLBaseAttributes extends BaseEventAttributes {
93
93
  lang?: string
94
94
  slot?: string
95
95
 
96
+ // Popover API (global attribute — any element can opt into being a popover).
97
+ // No `boolean` arm: `popover` isn't in BOOLEAN_ATTRS (`@barefootjs/shared`'s
98
+ // `dom-prop.ts`), so a boolean value stringifies instead of toggling the
99
+ // attribute's presence. `popover={false}` would render `popover="false"` —
100
+ // an invalid keyword the spec maps to `manual`, so the element is STILL a
101
+ // popover, not opted out — and the client runtime's `applyRestAttrs`
102
+ // disagrees by removing the attribute outright on `false`, an SSR/CSR
103
+ // mismatch. `popover={true}` renders `"true"`, also `manual`, not `auto`.
104
+ popover?: '' | 'auto' | 'manual' | 'hint'
105
+
96
106
  // Data attributes
97
107
  [key: `data-${string}`]: string | number | boolean | undefined
98
108
 
@@ -323,6 +333,8 @@ export interface ButtonHTMLAttributes extends Omit<HTMLBaseAttributes,
323
333
  name?: string
324
334
  type?: 'submit' | 'reset' | 'button'
325
335
  value?: string
336
+ popovertarget?: string
337
+ popovertargetaction?: 'toggle' | 'show' | 'hide'
326
338
 
327
339
  onClick?: MouseEventHandler<HTMLButtonElement>
328
340
  onBlur?: FocusEventHandler<HTMLButtonElement>
@@ -363,6 +375,8 @@ export interface InputHTMLAttributes extends Omit<HTMLBaseAttributes,
363
375
  name?: string
364
376
  pattern?: string
365
377
  placeholder?: string
378
+ popovertarget?: string
379
+ popovertargetaction?: 'toggle' | 'show' | 'hide'
366
380
  readonly?: boolean | null
367
381
  required?: boolean | null
368
382
  size?: number
package/src/index.ts CHANGED
@@ -87,6 +87,7 @@ export type {
87
87
  RenderDivergences,
88
88
  ImportInfo,
89
89
  } from './types.ts'
90
+ export { isElidedFactoryGetter } from './types.ts'
90
91
 
91
92
  // Analyzer
92
93
  export { analyzeComponent, listComponentFunctions, listComponentFunctions as listExportedComponents, scanComponentFile, createProgramForFile, createAnchoredProgram, needsTypeBasedDetection, resolveRelativeImportToFile, REACTIVE_PRIMITIVES, BROWSER_ONLY_CLIENT_APIS, type AnalyzerContext, type ComponentFileScan } from './analyzer.ts'
@@ -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
 
@@ -1132,6 +1138,60 @@ function collectFromElement(element: IRElement, ctx: ClientJsContext, insideCond
1132
1138
  const valueStr = attrValueToString(attr.value)
1133
1139
  if (!valueStr) continue
1134
1140
 
1141
+ // #3057: a statically expanded rest-key attribute (`{...rest}` onto
1142
+ // this element, unrolled per-key by `expandSpreadAttribute` because
1143
+ // the rest type is closed) reads the destructured rest OBJECT
1144
+ // (`rest.tag`) — a snapshot taken once when the component
1145
+ // initializes, never a live prop read. The string-level heuristics
1146
+ // below (`needsEffectWrapper`/`decideWrapForAttr`) don't recognize
1147
+ // `rest`/the expanded key as a tracked prop name, so this would
1148
+ // otherwise be classified static and never get a `createEffect` —
1149
+ // exactly the bug this issue reports. Bind it straight to a live
1150
+ // `_p.<key>` read instead, unconditionally: forwarding a prop via
1151
+ // `{...rest}` means it tracks the caller's current value by
1152
+ // definition, so it can never be "static" the way an ordinary
1153
+ // attribute expression can. `insideConditional` below just skips
1154
+ // this element the same way the generic path does (#1071) — unlike
1155
+ // the generic path, `collectBranchReactiveAttrs` does not read
1156
+ // `restExpandedKey`, so a rest key inside a conditional branch gets
1157
+ // no binding at all; that gap is intentionally out of scope for
1158
+ // #3057 (see the PR description). Two cases
1159
+ // fall back to the pre-#3057 classification below instead of this
1160
+ // fast path (both found by review on #3252):
1161
+ // - `attr.name` is an explicit JSX attribute's HTML name too
1162
+ // (e.g. a closed `id` rest key alongside a literal `id="fixed"`
1163
+ // on the same element). An unconditional `_p.id` write would
1164
+ // `removeAttribute` the SSR value whenever the caller doesn't
1165
+ // pass `id`, clobbering the explicit attribute.
1166
+ // - `classifyDOMProp` says this key doesn't reach the DOM as a
1167
+ // plain attribute at all (`ref` / `event` / `skip`, e.g.
1168
+ // `onPing` or `children`). `applyRestAttrs` already excludes
1169
+ // these from its own attribute set for the same reason; an
1170
+ // unconditional `setAttribute` here would stringify a function
1171
+ // or children value onto the element, which the pre-#3057
1172
+ // path never did.
1173
+ const restKeyHtmlName = toHtmlAttrName(attr.name)
1174
+ const collidesWithExplicitAttr = element.attrs.some(
1175
+ other => other !== attr && other.name !== '...' && toHtmlAttrName(other.name) === restKeyHtmlName,
1176
+ )
1177
+ const restKeyDomKind = classifyDOMProp(attr.name).kind
1178
+ if (
1179
+ attr.restExpandedKey &&
1180
+ !collidesWithExplicitAttr &&
1181
+ restKeyDomKind !== 'ref' &&
1182
+ restKeyDomKind !== 'event' &&
1183
+ restKeyDomKind !== 'skip'
1184
+ ) {
1185
+ if (insideConditional) continue
1186
+ ctx.reactiveAttrs.push({
1187
+ slotId: element.slotId,
1188
+ attrName: attr.name,
1189
+ expression: `${PROPS_PARAM}.${attr.name}`,
1190
+ ...pickAttrMetaFromIR(attr),
1191
+ })
1192
+ continue
1193
+ }
1194
+
1135
1195
  // Expand local constant references to detect transitive prop dependencies.
1136
1196
  // e.g., `classes` → `` `${baseClasses} ${variantClasses[variant]} ${className}` ``
1137
1197
  const expandedResult = expandConstantForReactivity(valueStr, ctx, attr.freeIdentifiers)
@@ -1544,7 +1604,7 @@ export function collectLoopChildBindings(
1544
1604
  ): LoopChildBindings {
1545
1605
  const bindings = emptyLoopChildBindings()
1546
1606
  for (const child of children) {
1547
- bindings.events.push(...collectLoopChildEventsWithNesting(child))
1607
+ bindings.events.push(...collectLoopChildEventsWithNesting(child, [], siblingOffsets))
1548
1608
  // stopAtReactiveConditionals=true (#2347): this function always also
1549
1609
  // collects nested reactive conditionals below via
1550
1610
  // `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
- if (preambleLine) ls.push(` ${preambleLine}`)
328
- if (idxLine) ls.push(` ${idxLine}`)
329
- ls.push(` ;${handlerCall}`)
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
  })