@barefootjs/go-template 0.9.1 → 0.9.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.
@@ -17,6 +17,13 @@ export interface RenderOptions {
17
17
  props?: Record<string, unknown>;
18
18
  /** Additional component files (filename → source) */
19
19
  components?: Record<string, string>;
20
+ /**
21
+ * Explicit component to render when `source` declares multiple
22
+ * exports (e.g. `ReactiveProps.tsx` → `PropsReactivityComparison`).
23
+ * Mirrors the Hono reference's `componentName`; omitted for
24
+ * single-export fixtures, which fall back to the default/first export.
25
+ */
26
+ componentName?: string;
20
27
  }
21
28
  export declare function renderGoTemplateComponent(options: RenderOptions): Promise<string>;
22
29
  //# sourceMappingURL=test-render.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"test-render.d.ts","sourceRoot":"","sources":["../src/test-render.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAe,MAAM,iBAAiB,CAAA;AAOnE,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,YAAY,OAAO,EAAE,MAAM,EAG1B;CACF;AAgCD,MAAM,WAAW,aAAa;IAC5B,sBAAsB;IACtB,MAAM,EAAE,MAAM,CAAA;IACd,8BAA8B;IAC9B,OAAO,EAAE,eAAe,CAAA;IACxB,iCAAiC;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,qDAAqD;IACrD,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACpC;AAED,wBAAsB,yBAAyB,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAsRvF"}
1
+ {"version":3,"file":"test-render.d.ts","sourceRoot":"","sources":["../src/test-render.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAe,MAAM,iBAAiB,CAAA;AAqBnE,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,YAAY,OAAO,EAAE,MAAM,EAG1B;CACF;AAgCD,MAAM,WAAW,aAAa;IAC5B,sBAAsB;IACtB,MAAM,EAAE,MAAM,CAAA;IACd,8BAA8B;IAC9B,OAAO,EAAE,eAAe,CAAA;IACxB,iCAAiC;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,qDAAqD;IACrD,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACnC;;;;;OAKG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED,wBAAsB,yBAAyB,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CA6RvF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@barefootjs/go-template",
3
- "version": "0.9.1",
3
+ "version": "0.9.3",
4
4
  "description": "Go html/template adapter for BarefootJS - generates Go template files from IR",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -54,6 +54,6 @@
54
54
  },
55
55
  "devDependencies": {
56
56
  "@barefootjs/adapter-tests": "0.1.0",
57
- "@barefootjs/jsx": "0.9.1"
57
+ "@barefootjs/jsx": "0.9.3"
58
58
  }
59
59
  }
@@ -34,38 +34,10 @@ runAdapterConformanceTests({
34
34
  // below, asserting that the adapter emits `BF101` / `BF103` /
35
35
  // `BF104` at build time instead of silently emitting invalid
36
36
  // template syntax (#1266).
37
- skipJsx: [
38
- // #1244 stress catalog (#1326): `children={<span/>}` the IR
39
- // hoists the span with `needsScope: true` so the Hono reference
40
- // emits `bf-s` on the inner `<span>`. The Go adapter renders the
41
- // span up front as a compile-time HTML fragment containing the
42
- // `{{bfScopeAttr .}}` action, then passes it via `template.HTML`
43
- // through the parent's `{{.Children}}` interpolation — but
44
- // `template.HTML` is marked-as-safe-output, not recursively
45
- // parsed, so the action survives as literal text in the rendered
46
- // HTML. Fixing this requires either (a) re-emitting the inner
47
- // span as its own named template definition the outer template
48
- // can pass its struct to, or (b) embedding the resolved scope ID
49
- // at compile time. Neither lands in this PR; the Mojo sibling
50
- // case is handled by routing the hoisted JSX through the same
51
- // `begin %>…<% end` capture as nested children (see #1326 fix).
52
- 'children-jsx-expression',
53
- // #1335: fragment-wrapped form of the same shape. Now that the IR
54
- // unwraps `<><span/></>` into the bare-element form, the Go adapter
55
- // hits the identical `template.HTML` interpolation gap as
56
- // `children-jsx-expression` above.
57
- 'fragment-wrapped-children-jsx-expression',
58
- // Shared-component multi-component fixtures (#1466). Boolean
59
- // attribute divergence is now collapsed by `normalizeHTML`, so
60
- // single-root variants (`conditional-return-*`, `form`, `portal`,
61
- // `reactive-props`) participate again. These two still diverge
62
- // because the harness's child renderer pins child `bf-s` to a
63
- // `test_<sN>` literal rather than `<ChildName>_<id>_<sN>`. Same
64
- // class of test-harness scope-id plumbing the `componentName`
65
- // option fixed on the Hono side. Separate follow-up.
66
- 'toggle-shared',
67
- 'props-reactivity-comparison',
68
- ],
37
+ // No JSX-render skips: every shared conformance fixture renders to Hono
38
+ // parity on real Go. Shapes the adapter intentionally refuses at build time
39
+ // are pinned in `expectedDiagnostics` below.
40
+ skipJsx: [],
69
41
  // Per-fixture build-time contracts for shapes the Go template
70
42
  // adapter intentionally refuses to lower. Lives here (not on the
71
43
  // shared fixtures) so adding a new adapter doesn't require touching
@@ -1212,6 +1184,33 @@ export function Page() {
1212
1184
  expect(types).not.toContain('template.HTML')
1213
1185
  })
1214
1186
 
1187
+ test('bakes hoisted children={<span/>} with the parent scopeID spliced into bf-s (#1326 / #1335)', () => {
1188
+ // `children` passed as an attribute lands as a `jsx-children` prop and
1189
+ // its span carries `needsScope: true`. The root `bf-s` must resolve to
1190
+ // the *parent* scope at render time, so the bake splices `scopeID`
1191
+ // (matching the client `__BF_PARENT_SCOPE__` placeholder) rather than
1192
+ // emitting a static string or dropping the child.
1193
+ const adapter = new GoTemplateAdapter()
1194
+ const ir = compileToIR(`
1195
+ export function Host() { return <Box children={<span>x</span>} /> }
1196
+ function Box({ children }: { children: any }) { return <div>{children}</div> }
1197
+ `)
1198
+ const types = adapter.generateTypes(ir)!
1199
+ expect(types).toContain('Children: template.HTML("<span bf-s=\\"" + scopeID + "\\">x</span>")')
1200
+ expect(types).toContain('"html/template"')
1201
+ })
1202
+
1203
+
1204
+ test('fragment-wrapped hoisted children bake to the same scoped shape (#1335)', () => {
1205
+ const adapter = new GoTemplateAdapter()
1206
+ const ir = compileToIR(`
1207
+ export function Host() { return <Box children={<><span>x</span></>} /> }
1208
+ function Box({ children }: { children: any }) { return <div>{children}</div> }
1209
+ `)
1210
+ const types = adapter.generateTypes(ir)!
1211
+ expect(types).toContain('Children: template.HTML("<span bf-s=\\"" + scopeID + "\\">x</span>")')
1212
+ })
1213
+
1215
1214
  test('drops dynamic children that would emit Go template actions', () => {
1216
1215
  // V1 limitation: a `template.HTML` value isn't re-parsed by the
1217
1216
  // parent's `{{.Children}}` pipeline, so any `{{...}}` inside the
@@ -2489,6 +2488,42 @@ import { fixture as arrayEntriesFixture } from '../../../adapter-tests/fixtures/
2489
2488
  import { fixture as arrayKeysFixture } from '../../../adapter-tests/fixtures/methods/array-keys'
2490
2489
  import { fixture as arrayValuesFixture } from '../../../adapter-tests/fixtures/methods/array-values'
2491
2490
 
2491
+ describe('GoTemplateAdapter - keyed loop-child data-key (#1297, toggle-shared)', () => {
2492
+ // A keyed `.map` of a child component stamps each item's `data-key` from the
2493
+ // loop `key` expression, emitted on the child component's scope root —
2494
+ // matching Hono.
2495
+ // `List` is declared first so `compileToIR` (which picks the first IR)
2496
+ // returns the parent that owns the keyed loop.
2497
+ const source = `
2498
+ "use client"
2499
+ import { createSignal } from "@barefootjs/client"
2500
+ type ItemProps = { label: string; defaultOn?: boolean }
2501
+ export function List({ items }: { items: ItemProps[] }) {
2502
+ return <ul>{items.map((item) => <Item key={item.label} label={item.label} defaultOn={item.defaultOn} />)}</ul>
2503
+ }
2504
+ function Item(props: ItemProps) {
2505
+ const [on] = createSignal(props.defaultOn ?? false)
2506
+ return <div className="item">{on() ? props.label : ''}</div>
2507
+ }
2508
+ `
2509
+ test('Props carries a BfDataKey field', () => {
2510
+ const { types } = compileAndGenerate(source)
2511
+ expect(types).toContain('BfDataKey string `json:"-"`')
2512
+ })
2513
+
2514
+ test('loop-child init stamps BfDataKey from the loop key (item.Label)', () => {
2515
+ const { types } = compileAndGenerate(source)
2516
+ expect(types).toContain('[i].BfDataKey = fmt.Sprint(item.Label)')
2517
+ expect(types).toContain('\t"fmt"')
2518
+ })
2519
+
2520
+ test('child component root emits data-key from BfDataKey', () => {
2521
+ const { template } = compileAndGenerate(source)
2522
+ // Space is inside the `{{if}}` so a non-keyed render adds nothing.
2523
+ expect(template).toContain('{{if .BfDataKey}} data-key="{{.BfDataKey}}"{{end}}')
2524
+ })
2525
+ })
2526
+
2492
2527
  describe('GoTemplateAdapter - #1448 Tier A/B fixture-driven lowering pins', () => {
2493
2528
  const cases = [
2494
2529
  // The `.includes` fixtures sit at condition position
@@ -82,6 +82,10 @@ type GoRenderCtx = {
82
82
  interface NestedComponentInfo extends IRLoopChildComponent {
83
83
  isDynamic: boolean
84
84
  isPropDerived: boolean
85
+ /** The enclosing loop's `key` expression (e.g. `item.label`) and map param
86
+ * name (`item`), so the loop-child init can stamp `data-key` per item. */
87
+ loopKey?: string
88
+ loopParam?: string
85
89
  }
86
90
 
87
91
  interface StaticChildInstance {
@@ -104,6 +108,16 @@ interface StaticChildInstance {
104
108
  * through the parent's `{{.Children}}` read; those cases stay on
105
109
  * the existing drop path. */
106
110
  childrenHtml: string | null
111
+ /** Go string-concat expression for hoisted-JSX children that carry a
112
+ * `needsScope` root (`children={<span/>}` — #1326 / #1335). The root's
113
+ * `bf-s` resolves to the PARENT scope (mirroring the client
114
+ * `__BF_PARENT_SCOPE__` placeholder + Mojo's begin/end capture), so the
115
+ * fragment can't bake to a static string — the runtime `scopeID` is
116
+ * spliced in (`"<span bf-s=\"" + scopeID + "\">x</span>"`). Null when the
117
+ * static `childrenHtml` path already covers the children, or when any
118
+ * other template action survives (genuinely dynamic — kept on the drop
119
+ * path). */
120
+ childrenScopedHtmlExpr: string | null
107
121
  /**
108
122
  * Context values from enclosing `<Ctx.Provider value>` ancestors
109
123
  * (`createContext` identifier → Go value literal), wired into this child
@@ -287,6 +301,48 @@ function capitalize(s: string): string {
287
301
  return s[0].toUpperCase() + s.slice(1)
288
302
  }
289
303
 
304
+ /**
305
+ * Lower a keyed-loop `key` expression to the Go field path on the loop's range
306
+ * variable (always `item` in the generated `for i, item := range …`), e.g.
307
+ * `item.label` → `item.Label`. Returns null for a non-simple key (computed
308
+ * expression, whole-element key, mismatched param) so the loop-child init just
309
+ * skips `data-key` rather than emitting something that won't compile. (#1297)
310
+ */
311
+ function loopKeyToGoFieldPath(key: string | undefined, param: string | undefined): string | null {
312
+ if (!key || !param) return null
313
+ const segs = key.split('.')
314
+ if (segs[0] !== param) return null
315
+ const rest = segs.slice(1)
316
+ if (rest.length === 0) return null
317
+ if (!rest.every(s => /^[A-Za-z_]\w*$/.test(s))) return null
318
+ return 'item.' + rest.map(capitalize).join('.')
319
+ }
320
+
321
+ /**
322
+ * Collect the component's root scope element node(s) — the elements that become
323
+ * the rendered root and so carry `data-key` for a keyed loop item. A plain
324
+ * element root is itself; an `if-statement` (early-return) root contributes the
325
+ * top element of each branch, since exactly one renders at runtime. (#1297)
326
+ */
327
+ function collectRootScopeNodes(node: IRNode): Set<IRNode> {
328
+ const out = new Set<IRNode>()
329
+ const visit = (n: IRNode | null): void => {
330
+ if (!n) return
331
+ if (n.type === 'element') { out.add(n); return }
332
+ if (n.type === 'if-statement') {
333
+ const s = n as IRIfStatement
334
+ visit(s.consequent)
335
+ visit(s.alternate)
336
+ return
337
+ }
338
+ if (n.type === 'fragment') {
339
+ for (const c of (n as IRFragment).children) visit(c)
340
+ }
341
+ }
342
+ visit(node)
343
+ return out
344
+ }
345
+
290
346
  /**
291
347
  * Convert a slot ID (e.g., 's6') to a Go struct field suffix (e.g., 'Slot6').
292
348
  * Keeps field names human-readable regardless of the internal slot ID format.
@@ -342,6 +398,11 @@ const GO_TEMPLATE_PRIMITIVES: Record<string, PrimitiveSpec> = {
342
398
  export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter, IRNodeEmitter<GoRenderCtx> {
343
399
  name = 'go-template'
344
400
  extension = '.tmpl'
401
+
402
+ // Sentinel marking a parent-scope `bf-s` slot inside a hoisted-JSX
403
+ // children bake (see `extractScopedHtmlChildren`). The token can't appear
404
+ // in real HTML text, so splitting on it is unambiguous.
405
+ private static readonly SCOPE_SENTINEL = '__BF_SCOPE_SENTINEL__'
345
406
  // Template-string target with no component layer: `bf build` emits a static
346
407
  // `barefoot-importmap.html` to `{{ template }}` into the page <head> (#1644).
347
408
  importMapInjection = 'html-snippet' as const
@@ -440,6 +501,10 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
440
501
  /** Set during type generation when any emit references
441
502
  * `template.HTML(...)`; toggles the `"html/template"` import. */
442
503
  private usesHtmlTemplate: boolean = false
504
+ /** Component root scope element(s) — each carries `data-key` for a keyed loop
505
+ * item. A plain element root is one node; an `if-statement` (early-return)
506
+ * root contributes the top element of every branch. (#1297) */
507
+ private rootScopeNodes: Set<IRNode> = new Set()
443
508
 
444
509
  /** Set during type generation when any emit references
445
510
  * `fmt.Sprint(...)` — e.g. a `Record<staticKeys, scalar>[propKey]`
@@ -566,6 +631,7 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
566
631
  const isRootComponent = ir.root.type === 'component'
567
632
  const isIfStatement = ir.root.type === 'if-statement'
568
633
 
634
+ this.rootScopeNodes = collectRootScopeNodes(ir.root)
569
635
  const templateBody = isIfStatement
570
636
  ? this.renderIfStatement(ir.root as IRIfStatement, { isRootOfClientComponent: hasInteractivity })
571
637
  : this.renderNode(ir.root, { isRootOfClientComponent: hasInteractivity && isRootComponent })
@@ -1343,6 +1409,9 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
1343
1409
  // Emitted as bf-h / bf-m HTML attributes by `bfHydrationAttrs`.
1344
1410
  lines.push('\tBfParent string `json:"-"`')
1345
1411
  lines.push('\tBfMount string `json:"-"`')
1412
+ // (#1297) Keyed-loop reconciliation key, stamped per item by the parent's
1413
+ // loop init and emitted as `data-key` on this component's scope root.
1414
+ lines.push('\tBfDataKey string `json:"-"`')
1346
1415
 
1347
1416
  // Add Scripts field for dynamic script collection
1348
1417
  lines.push('\tScripts *bf.ScriptCollector `json:"-"`')
@@ -1533,6 +1602,13 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
1533
1602
  // mark it as a slot-attached child of this scope.
1534
1603
  lines.push(`\t\t${varName}[i].BfParent = scopeID`)
1535
1604
  lines.push(`\t\t${varName}[i].BfMount = "${nested.slotId}"`)
1605
+ // (#1297) Stamp the keyed-loop `data-key` per item from the loop's
1606
+ // `key` expression (`item.label` → `item.Label`), matching Hono.
1607
+ const keyField = loopKeyToGoFieldPath(nested.loopKey, nested.loopParam)
1608
+ if (keyField) {
1609
+ lines.push(`\t\t${varName}[i].BfDataKey = fmt.Sprint(${keyField})`)
1610
+ this.usesFmt = true
1611
+ }
1536
1612
  lines.push('\t}')
1537
1613
  lines.push('')
1538
1614
  }
@@ -1764,6 +1840,11 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
1764
1840
  } else if (child.childrenHtml !== null) {
1765
1841
  this.usesHtmlTemplate = true
1766
1842
  lines.push(`\t\t\tChildren: template.HTML(${JSON.stringify(child.childrenHtml)}),`)
1843
+ } else if (child.childrenScopedHtmlExpr !== null) {
1844
+ // Hoisted-JSX children with a needsScope root (#1326 / #1335): the
1845
+ // root `bf-s` is the runtime parent scopeID, spliced into the bake.
1846
+ this.usesHtmlTemplate = true
1847
+ lines.push(`\t\t\tChildren: template.HTML(${child.childrenScopedHtmlExpr}),`)
1767
1848
  }
1768
1849
  lines.push(`\t\t}),`)
1769
1850
  }
@@ -1823,6 +1904,8 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
1823
1904
  ...loop.childComponent,
1824
1905
  isDynamic: !loop.isStaticArray,
1825
1906
  isPropDerived: !!loop.isPropDerivedArray,
1907
+ loopKey: loop.key ?? undefined,
1908
+ loopParam: loop.param ?? undefined,
1826
1909
  })
1827
1910
  }
1828
1911
  }
@@ -1890,6 +1973,17 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
1890
1973
  * "drop children" fallback. Dynamic / component-bearing children
1891
1974
  * stay on the drop path until a re-evaluation hook lands.
1892
1975
  */
1976
+ /**
1977
+ * Pull the IR nodes out of a `children={<…/>}` attribute (a `jsx-children`
1978
+ * prop value). Empty when the component takes no such prop. (#1326 / #1335)
1979
+ */
1980
+ private jsxChildrenPropNodes(props: IRProp[]): IRNode[] {
1981
+ for (const p of props) {
1982
+ if (p.value.kind === 'jsx-children') return p.value.children
1983
+ }
1984
+ return []
1985
+ }
1986
+
1893
1987
  private extractHtmlChildren(children: IRNode[]): string | null {
1894
1988
  if (children.length === 0) return null
1895
1989
  if (children.every(c => c.type === 'text')) return null
@@ -1898,6 +1992,38 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
1898
1992
  return html
1899
1993
  }
1900
1994
 
1995
+ /**
1996
+ * Build a Go string-concat expression for hoisted-JSX children whose root
1997
+ * carries `needsScope` (`children={<span/>}` — #1326 / #1335). Such roots
1998
+ * render in the PARENT's scope, so their `bf-s` is the runtime parent
1999
+ * `scopeID`, not a bake-time constant. We render the fragment, swap the
2000
+ * parent-scope hydration marker for a sentinel, and splice `scopeID` back
2001
+ * in. Returns null when the plain static `childrenHtml` path already
2002
+ * applies, or when any other template action survives (genuinely dynamic —
2003
+ * those stay on the drop path).
2004
+ */
2005
+ private extractScopedHtmlChildren(children: IRNode[]): string | null {
2006
+ if (children.length === 0) return null
2007
+ if (children.every(c => c.type === 'text')) return null
2008
+ const html = this.renderChildren(children)
2009
+ // The needsScope marker renders parent-scope hydration attrs; in a
2010
+ // hoisted fragment every needsScope root resolves to the parent scopeID,
2011
+ // so collapse the whole marker to a bare `bf-s` sentinel (the empty
2012
+ // bf-h / bf-m attrs are dropped — same shape the client emits).
2013
+ const marker = this.renderScopeMarker('.ScopeID')
2014
+ const withSentinel = html
2015
+ .split(marker)
2016
+ .join(`bf-s="${GoTemplateAdapter.SCOPE_SENTINEL}"`)
2017
+ // No sentinel → no needsScope root → the static childrenHtml path covers it.
2018
+ if (!withSentinel.includes(GoTemplateAdapter.SCOPE_SENTINEL)) return null
2019
+ // Any surviving action means the fragment is genuinely dynamic.
2020
+ if (withSentinel.includes('{{')) return null
2021
+ return withSentinel
2022
+ .split(GoTemplateAdapter.SCOPE_SENTINEL)
2023
+ .map(seg => JSON.stringify(seg))
2024
+ .join(' + scopeID + ')
2025
+ }
2026
+
1901
2027
  private collectStaticChildInstancesRecursive(
1902
2028
  node: IRNode,
1903
2029
  result: StaticChildInstance[],
@@ -1920,13 +2046,21 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
1920
2046
  // Skip components inside loops (handled by nestedComponents)
1921
2047
  if (comp.name !== 'Portal' && !inLoop && comp.slotId) {
1922
2048
  const suffix = slotIdToFieldSuffix(comp.slotId)
2049
+ // Children handed in as a `children={<…/>}` attribute (#1326 / #1335)
2050
+ // land as a `jsx-children` prop rather than nested between the tags;
2051
+ // treat them as the child's effective children when no nested ones
2052
+ // exist, so the bake paths below see them.
2053
+ const effectiveChildren = comp.children.length > 0
2054
+ ? comp.children
2055
+ : this.jsxChildrenPropNodes(comp.props)
1923
2056
  result.push({
1924
2057
  name: comp.name,
1925
2058
  slotId: comp.slotId,
1926
2059
  props: comp.props,
1927
2060
  fieldName: `${comp.name}${suffix}`,
1928
- childrenText: this.extractTextChildren(comp.children),
1929
- childrenHtml: this.extractHtmlChildren(comp.children),
2061
+ childrenText: this.extractTextChildren(effectiveChildren),
2062
+ childrenHtml: this.extractHtmlChildren(effectiveChildren),
2063
+ childrenScopedHtmlExpr: this.extractScopedHtmlChildren(effectiveChildren),
1930
2064
  contextBindings: providerCtx.size > 0 ? providerCtx : undefined,
1931
2065
  })
1932
2066
  }
@@ -3664,6 +3798,14 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
3664
3798
  if (element.needsScope) {
3665
3799
  hydrationAttrs += ` ${this.renderScopeMarker('.ScopeID')}`
3666
3800
  }
3801
+ // (#1297) A root scope element carries `data-key` for a keyed loop item —
3802
+ // the parent's loop init stamped `.BfDataKey`, so a non-keyed render emits
3803
+ // nothing. Mirrors Hono stamping data-key on each loop item's scope root,
3804
+ // including early-return (if-statement) roots where every branch's top
3805
+ // element qualifies.
3806
+ if (this.rootScopeNodes.has(element) && element.needsScope) {
3807
+ hydrationAttrs += `{{if .BfDataKey}} data-key="{{.BfDataKey}}"{{end}}`
3808
+ }
3667
3809
  if (element.slotId) {
3668
3810
  hydrationAttrs += ` ${this.renderSlotMarker(element.slotId)}`
3669
3811
  }
@@ -5711,7 +5853,7 @@ export class GoTemplateAdapter extends BaseAdapter implements ParsedExprEmitter,
5711
5853
  return `{{block "${slotName}" .}}{{end}}`
5712
5854
  }
5713
5855
 
5714
- renderAsync(node: IRAsync): string {
5856
+ override renderAsync(node: IRAsync): string {
5715
5857
  const fallback = this.renderNode(node.fallback)
5716
5858
  const children = this.renderChildren(node.children)
5717
5859
  // Go templates use the OOS protocol: render a placeholder with fallback,
@@ -2,5 +2,5 @@
2
2
  * Go html/template Adapter Exports
3
3
  */
4
4
 
5
- export { GoTemplateAdapter, goTemplateAdapter } from './go-template-adapter'
6
- export type { GoTemplateAdapterOptions } from './go-template-adapter'
5
+ export { GoTemplateAdapter, goTemplateAdapter } from './go-template-adapter.ts'
6
+ export type { GoTemplateAdapterOptions } from './go-template-adapter.ts'
package/src/build.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  // Go template build config factory for barefoot.config.ts
2
2
 
3
3
  import type { BuildOptions, PostBuildContext } from '@barefootjs/jsx'
4
- import { GoTemplateAdapter } from './adapter'
5
- import type { GoTemplateAdapterOptions } from './adapter'
4
+ import { GoTemplateAdapter } from './adapter/index.ts'
5
+ import type { GoTemplateAdapterOptions } from './adapter/index.ts'
6
6
 
7
7
  export interface GoTemplateBuildOptions extends BuildOptions {
8
8
  /** Adapter-specific options passed to GoTemplateAdapter */
@@ -156,13 +156,26 @@ export function combineGoTypes(options: {
156
156
  combinedContent = transformTypes(combinedContent)
157
157
  }
158
158
 
159
+ // Conditionally pull in stdlib packages the combined component code uses.
160
+ // Per-component import blocks are stripped above, so the merged file needs
161
+ // its own block — `fmt` (e.g. `fmt.Sprint` for keyed-loop data-key /
162
+ // indexed-map spread) and `html/template` (`template.HTML` for forwarded
163
+ // JSX children) are only imported when actually referenced, so an app that
164
+ // uses neither doesn't get an "imported and not used" error.
165
+ const usageScan = combinedContent + '\n' + (manualTypes ?? '')
166
+ const stdlibImports: string[] = [`\t"math/rand"`]
167
+ if (/\bfmt\./.test(usageScan)) stdlibImports.push(`\t"fmt"`)
168
+ if (/\btemplate\.HTML\b/.test(usageScan)) stdlibImports.push(`\t"html/template"`)
169
+ // gofmt sorts the stdlib group alphabetically by import path.
170
+ stdlibImports.sort()
171
+
159
172
  // Build final file
160
173
  const parts = [
161
174
  `// Code generated by BarefootJS. DO NOT EDIT.`,
162
175
  `package ${packageName}`,
163
176
  '',
164
177
  `import (`,
165
- `\t"math/rand"`,
178
+ ...stdlibImports,
166
179
  '',
167
180
  `\tbf "github.com/barefootjs/runtime/bf"`,
168
181
  `)`,
package/src/index.ts CHANGED
@@ -4,5 +4,5 @@
4
4
  * Generates Go html/template files from BarefootJS IR.
5
5
  */
6
6
 
7
- export { GoTemplateAdapter, goTemplateAdapter } from './adapter'
8
- export type { GoTemplateAdapterOptions } from './adapter'
7
+ export { GoTemplateAdapter, goTemplateAdapter } from './adapter/index.ts'
8
+ export type { GoTemplateAdapterOptions } from './adapter/index.ts'
@@ -7,6 +7,20 @@
7
7
 
8
8
  import { compileJSX } from '@barefootjs/jsx'
9
9
  import type { TemplateAdapter, ComponentIR } from '@barefootjs/jsx'
10
+ import { GoTemplateAdapter } from './adapter/go-template-adapter.ts'
11
+
12
+ /**
13
+ * Capitalize a JSON key to its Go struct field name using the same
14
+ * initialism rules as the adapter (`capitalizeFieldName`): a whole-word Go
15
+ * initialism uppercases entirely (`id` → `ID`), otherwise just the first
16
+ * letter. Keeps harness-emitted struct literals (`ItemInput{ID: …}`) matching
17
+ * the generated exported field names. (#1297)
18
+ */
19
+ function capitalizeGoField(name: string): string {
20
+ if (!name) return name
21
+ if (GoTemplateAdapter.GO_INITIALISMS.has(name.toLowerCase())) return name.toUpperCase()
22
+ return name.charAt(0).toUpperCase() + name.slice(1)
23
+ }
10
24
  import { mkdir, rm } from 'node:fs/promises'
11
25
  import { resolve } from 'node:path'
12
26
 
@@ -59,10 +73,17 @@ export interface RenderOptions {
59
73
  props?: Record<string, unknown>
60
74
  /** Additional component files (filename → source) */
61
75
  components?: Record<string, string>
76
+ /**
77
+ * Explicit component to render when `source` declares multiple
78
+ * exports (e.g. `ReactiveProps.tsx` → `PropsReactivityComparison`).
79
+ * Mirrors the Hono reference's `componentName`; omitted for
80
+ * single-export fixtures, which fall back to the default/first export.
81
+ */
82
+ componentName?: string
62
83
  }
63
84
 
64
85
  export async function renderGoTemplateComponent(options: RenderOptions): Promise<string> {
65
- const { source, adapter, props, components } = options
86
+ const { source, adapter, props, components, componentName: requestedName } = options
66
87
 
67
88
  if (!adapter.generateTypes) {
68
89
  throw new Error('Go Template adapter must implement generateTypes()')
@@ -139,7 +160,13 @@ export async function renderGoTemplateComponent(options: RenderOptions): Promise
139
160
  const irFiles = result.files.filter(f => f.type === 'ir')
140
161
  if (irFiles.length === 0) throw new Error('No IR output (set outputIR: true)')
141
162
  const irs = irFiles.map(f => JSON.parse(f.content) as ComponentIR)
163
+ // Explicit `componentName` wins (multi-export sources pin which export
164
+ // is the render target); otherwise default-export, then first inline-
165
+ // exported, then first IR. Mirrors the Hono reference's selection so
166
+ // multi-component fixtures (e.g. `ReactiveProps.tsx`) render the same
167
+ // export across adapters.
142
168
  const ir =
169
+ (requestedName ? irs.find(i => i.metadata.componentName === requestedName) : undefined) ??
143
170
  irs.find(i => i.metadata.hasDefaultExport) ??
144
171
  irs.find(i => i.metadata.isExported) ??
145
172
  irs[0]
@@ -246,8 +273,9 @@ export async function renderGoTemplateComponent(options: RenderOptions): Promise
246
273
  // template content as Go raw string
247
274
  const escapedTemplate = template.replace(/`/g, '` + "`" + `')
248
275
 
249
- // Build props initialization
250
- const propsInit = buildGoPropsInit(componentName, props, ir)
276
+ // Build props initialization (typed against the generated Input struct so
277
+ // an array-of-objects prop emits e.g. `[]ToggleItemInput{…}`, not `[]any`).
278
+ const propsInit = buildGoPropsInit(componentName, props, ir, goTypes)
251
279
 
252
280
  // Honour `__instanceId` from props for the root scope id so
253
281
  // shared-component fixtures (which pin `<ComponentName>_test`) match
@@ -457,9 +485,10 @@ function ensureMergedStdlibImports(goTypes: string): string {
457
485
  * Build Go struct field initializers from props.
458
486
  */
459
487
  function buildGoPropsInit(
460
- _componentName: string,
488
+ componentName: string,
461
489
  props?: Record<string, unknown>,
462
490
  ir?: ComponentIR,
491
+ goTypes?: string,
463
492
  ): string {
464
493
  if (!props) return ''
465
494
 
@@ -504,16 +533,25 @@ function buildGoPropsInit(
504
533
  } else if (typeof value === 'boolean') {
505
534
  lines.push(`\t\t${goField}: ${value},`)
506
535
  } else if (Array.isArray(value)) {
507
- // Array → Go `[]any` literal. Fixtures that exercise
508
- // array-receiver methods (`items.every(...)`, `items.join(' - ')`,
509
- // etc. — #1448 method catalog) need the prop value to reach
510
- // the rendered template as a real slice so `range .Items` /
511
- // `bf_join (.Items) ...` see actual elements; without this
512
- // branch the prop was silently dropped, the input-struct
513
- // field stayed at its zero value, and the template rendered
514
- // empty content alongside the expected wrappers (the bug
515
- // surfaced as "expected 'idx: 1' / got 'idx:'" on CI).
516
- lines.push(`\t\t${goField}: ${goArrayLiteralFromArray(value)},`)
536
+ // Array → Go slice literal. Fixtures that exercise array-receiver
537
+ // methods (`items.every(...)`, `items.join(' - ')`, etc. — #1448
538
+ // method catalog) need the prop value to reach the rendered template
539
+ // as a real slice so `range .Items` / `bf_join (.Items) ...` see
540
+ // actual elements.
541
+ //
542
+ // When the Input field is a typed slice (`ToggleItems
543
+ // []ToggleItemInput`, a loop-child array prop), emit a matching
544
+ // typed literal (`[]ToggleItemInput{ToggleItemInput{Label: …}, …}`);
545
+ // a bare `[]any{}` would fail to compile against the typed field.
546
+ // Fall back to `[]any` when the field type is `[]any` / unknown.
547
+ const elemType = goSliceElemType(goTypes, componentName, goField)
548
+ lines.push(
549
+ `\t\t${goField}: ${
550
+ elemType
551
+ ? goTypedSliceLiteralFromArray(value, elemType)
552
+ : goArrayLiteralFromArray(value)
553
+ },`,
554
+ )
517
555
  } else if (value && typeof value === 'object') {
518
556
  // Plain object → Go `map[string]any` literal (#1407 follow-up).
519
557
  // Used by `jsx-spread-rest-prop` to populate the input-bag
@@ -533,6 +571,66 @@ function buildGoPropsInit(
533
571
  return lines.join('\n')
534
572
  }
535
573
 
574
+ /**
575
+ * Look up the element type of a typed slice field on the entry component's
576
+ * `<Component>Input` struct (e.g. `ToggleItems []ToggleItemInput` →
577
+ * `ToggleItemInput`). Returns null when the field is absent, isn't a slice, or
578
+ * is an untyped `[]any` / `[]interface{}` (those keep the generic `[]any`
579
+ * harness literal). (#1297, toggle-shared)
580
+ */
581
+ function goSliceElemType(
582
+ goTypes: string | undefined,
583
+ componentName: string,
584
+ goField: string,
585
+ ): string | null {
586
+ if (!goTypes) return null
587
+ const struct = goTypes.match(
588
+ new RegExp(`type ${componentName}Input struct \\{([\\s\\S]*?)\\n\\}`),
589
+ )
590
+ if (!struct) return null
591
+ const field = struct[1].match(new RegExp(`\\n\\s*${goField}\\s+\\[\\]([\\w.]+)`))
592
+ if (!field) return null
593
+ const elem = field[1]
594
+ if (elem === 'any' || elem === 'interface{}') return null
595
+ return elem
596
+ }
597
+
598
+ /**
599
+ * Emit a typed Go slice literal (`[]Elem{Elem{…}, …}`). Object elements become
600
+ * keyed struct literals with PascalCase field names; scalar elements (for an
601
+ * `[]string` / `[]int` field) are emitted bare. (#1297, toggle-shared)
602
+ */
603
+ function goTypedSliceLiteralFromArray(arr: unknown[], elemType: string): string {
604
+ const entries = arr.map(v => {
605
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
606
+ return goStructLiteral(v as Record<string, unknown>, elemType)
607
+ }
608
+ if (typeof v === 'string') return `"${v.replace(/"/g, '\\"')}"`
609
+ if (typeof v === 'number' || typeof v === 'boolean') return String(v)
610
+ if (v === null) return 'nil'
611
+ return goArrayLiteralFromArray(v as unknown[])
612
+ })
613
+ return `[]${elemType}{${entries.join(', ')}}`
614
+ }
615
+
616
+ /**
617
+ * Emit a keyed Go struct literal (`Elem{Field: val, …}`) with PascalCase field
618
+ * names. Only the keys the caller supplied are set, so an omitted optional prop
619
+ * (e.g. `defaultOn` on the third toggle item) takes the Go zero value. (#1297)
620
+ */
621
+ function goStructLiteral(obj: Record<string, unknown>, typeName: string): string {
622
+ const fields: string[] = []
623
+ for (const [k, v] of Object.entries(obj)) {
624
+ const goField = capitalizeGoField(k)
625
+ if (typeof v === 'string') fields.push(`${goField}: "${v.replace(/"/g, '\\"')}"`)
626
+ else if (typeof v === 'number' || typeof v === 'boolean') fields.push(`${goField}: ${v}`)
627
+ else if (v === null) fields.push(`${goField}: nil`)
628
+ else if (Array.isArray(v)) fields.push(`${goField}: ${goArrayLiteralFromArray(v)}`)
629
+ else if (v && typeof v === 'object') fields.push(`${goField}: ${goMapLiteralFromObject(v as Record<string, unknown>, true)}`)
630
+ }
631
+ return `${typeName}{${fields.join(', ')}}`
632
+ }
633
+
536
634
  function goArrayLiteralFromArray(arr: unknown[]): string {
537
635
  const entries: string[] = []
538
636
  for (const v of arr) {