@barefootjs/jsx 0.4.0 → 0.5.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 (67) hide show
  1. package/dist/adapters/interface.d.ts +20 -0
  2. package/dist/adapters/interface.d.ts.map +1 -1
  3. package/dist/adapters/test-adapter.d.ts.map +1 -1
  4. package/dist/expression-parser.d.ts +36 -19
  5. package/dist/expression-parser.d.ts.map +1 -1
  6. package/dist/import-map.d.ts +56 -0
  7. package/dist/import-map.d.ts.map +1 -0
  8. package/dist/import-map.js +18 -0
  9. package/dist/index.d.ts +3 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +333 -199
  12. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  13. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  14. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +14 -0
  15. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  16. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/html-template.d.ts +0 -14
  19. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  20. package/dist/ir-to-client-js/imports.d.ts +2 -2
  21. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  22. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/types.d.ts +7 -0
  24. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/utils.d.ts +2 -2
  26. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  27. package/dist/scanner/js-scanner.d.ts +10 -0
  28. package/dist/scanner/js-scanner.d.ts.map +1 -1
  29. package/dist/scanner/js-scanner.js +5 -0
  30. package/dist/types.d.ts +11 -0
  31. package/dist/types.d.ts.map +1 -1
  32. package/package.json +7 -3
  33. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +438 -190
  34. package/src/__tests__/adapter-output.test.ts +49 -0
  35. package/src/__tests__/child-components-in-map.test.ts +76 -0
  36. package/src/__tests__/client-js-generation.test.ts +5 -2
  37. package/src/__tests__/import-map.test.ts +75 -0
  38. package/src/__tests__/inline-jsx-callback.test.ts +95 -0
  39. package/src/__tests__/ir-jsx-props.test.ts +5 -2
  40. package/src/__tests__/ir-sort-comparator.test.ts +212 -9
  41. package/src/__tests__/loop-item-conditional-codegen.test.ts +81 -0
  42. package/src/__tests__/map-logical-jsx-helper.test.ts +159 -0
  43. package/src/__tests__/missing-key-in-list.test.ts +49 -0
  44. package/src/__tests__/reactive-attrs-in-map.test.ts +41 -0
  45. package/src/__tests__/token-contains-ident.test.ts +27 -0
  46. package/src/__tests__/unsupported-expression.test.ts +42 -13
  47. package/src/adapters/interface.ts +20 -0
  48. package/src/adapters/test-adapter.ts +16 -1
  49. package/src/expression-parser.ts +265 -50
  50. package/src/import-map.ts +72 -0
  51. package/src/index.ts +5 -1
  52. package/src/ir-to-client-js/collect-elements.ts +3 -0
  53. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +17 -0
  54. package/src/ir-to-client-js/control-flow/plan/loop.ts +14 -0
  55. package/src/ir-to-client-js/control-flow/stringify/insert.ts +7 -2
  56. package/src/ir-to-client-js/control-flow/stringify/loop.ts +60 -0
  57. package/src/ir-to-client-js/emit-reactive.ts +12 -3
  58. package/src/ir-to-client-js/html-template.ts +29 -3
  59. package/src/ir-to-client-js/imports.ts +2 -2
  60. package/src/ir-to-client-js/reactivity.ts +17 -1
  61. package/src/ir-to-client-js/stringify/static-array-child-init.ts +8 -4
  62. package/src/ir-to-client-js/types.ts +7 -0
  63. package/src/ir-to-client-js/utils.ts +31 -116
  64. package/src/jsx-to-ir.ts +161 -12
  65. package/src/preprocess-inline-jsx-callbacks.ts +28 -10
  66. package/src/scanner/js-scanner.ts +16 -1
  67. package/src/types.ts +12 -0
package/src/jsx-to-ir.ts CHANGED
@@ -1703,6 +1703,33 @@ function containsJsxInExpression(node: ts.Node): boolean {
1703
1703
  return ts.forEachChild(node, containsJsxInExpression) ?? false
1704
1704
  }
1705
1705
 
1706
+ /**
1707
+ * Check if an expression calls a module/local JSX-returning helper (one
1708
+ * tracked in `jsxFunctions` / `jsxMultiReturnFunctions` for IR-level
1709
+ * inlining). Used alongside `containsJsxInExpression` so a map callback
1710
+ * body like `cond && themeLogo(t.id)` is recognised as renderable JSX
1711
+ * control flow even though it has no inline JSX literal (#1665).
1712
+ */
1713
+ function callsJsxHelper(node: ts.Node, ctx: TransformContext): boolean {
1714
+ let found = false
1715
+ const visit = (n: ts.Node): void => {
1716
+ if (found) return
1717
+ if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
1718
+ const name = n.expression.text
1719
+ if (
1720
+ ctx.analyzer.jsxFunctions.has(name) ||
1721
+ ctx.analyzer.jsxMultiReturnFunctions.has(name)
1722
+ ) {
1723
+ found = true
1724
+ return
1725
+ }
1726
+ }
1727
+ ts.forEachChild(n, visit)
1728
+ }
1729
+ visit(node)
1730
+ return found
1731
+ }
1732
+
1706
1733
  function containsAwaitExpression(node: ts.Node): boolean {
1707
1734
  if (ts.isAwaitExpression(node)) return true
1708
1735
  if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)) return false
@@ -1893,7 +1920,7 @@ function transformJsxExpression(
1893
1920
  if (
1894
1921
  (node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken ||
1895
1922
  node.operatorToken.kind === ts.SyntaxKind.BarBarToken) &&
1896
- containsJsxInExpression(node.right)
1923
+ (containsJsxInExpression(node.right) || callsJsxHelper(node.right, ctx))
1897
1924
  ) {
1898
1925
  return transformNullishCoalescing(node, ctx)
1899
1926
  }
@@ -2642,18 +2669,34 @@ function checkLoopKey(
2642
2669
  }
2643
2670
  while (ts.isParenthesizedExpression(body)) body = body.expression
2644
2671
 
2672
+ // Check a JSX operand (unwrapping parentheses) if it is an element.
2673
+ function checkJsxOperand(node: ts.Node): void {
2674
+ let n = node
2675
+ while (ts.isParenthesizedExpression(n)) n = n.expression
2676
+ if (ts.isJsxElement(n)) checkOpening(n.openingElement)
2677
+ else if (ts.isJsxSelfClosingElement(n)) checkOpening(n)
2678
+ }
2679
+
2645
2680
  if (ts.isConditionalExpression(body)) {
2646
2681
  // Check both branches independently
2647
- const whenTrue = body.whenTrue
2648
- const whenFalse = body.whenFalse
2649
- let wt: ts.Node = whenTrue
2650
- let wf: ts.Node = whenFalse
2651
- while (ts.isParenthesizedExpression(wt)) wt = wt.expression
2652
- while (ts.isParenthesizedExpression(wf)) wf = wf.expression
2653
- if (ts.isJsxElement(wt)) checkOpening(wt.openingElement)
2654
- else if (ts.isJsxSelfClosingElement(wt)) checkOpening(wt)
2655
- if (ts.isJsxElement(wf)) checkOpening(wf.openingElement)
2656
- else if (ts.isJsxSelfClosingElement(wf)) checkOpening(wf)
2682
+ checkJsxOperand(body.whenTrue)
2683
+ checkJsxOperand(body.whenFalse)
2684
+ return
2685
+ }
2686
+
2687
+ // Logical `cond && <jsx>` / `cond || <jsx>` / `a ?? <jsx>` whole-item
2688
+ // conditionals (#1665). The JSX operand renders 0-or-1 element per
2689
+ // iteration and still needs a key for correct reconciliation, exactly
2690
+ // like a ternary branch. Without this case the binary-expression body
2691
+ // silently skipped key validation.
2692
+ if (
2693
+ ts.isBinaryExpression(body) &&
2694
+ (body.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
2695
+ body.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
2696
+ body.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken)
2697
+ ) {
2698
+ checkJsxOperand(body.left)
2699
+ checkJsxOperand(body.right)
2657
2700
  return
2658
2701
  }
2659
2702
 
@@ -2679,6 +2722,69 @@ function loopBodyIsMultiRoot(children: IRNode[]): boolean {
2679
2722
  return loopBodyIsMultiRoot(only.children)
2680
2723
  }
2681
2724
 
2725
+ /**
2726
+ * True when a conditional branch does NOT render exactly one root element —
2727
+ * the element-less side of a whole-item conditional. Covers the empty branch
2728
+ * of `cond && <li/>` (`null`) and `cond ? <li/> : null`, and the scalar side
2729
+ * of `expr || <li/>` / `expr ?? <li/>` (the left operand renders as text or
2730
+ * nothing, never a tracked element). Any such branch makes the loop item
2731
+ * render 0-or-1 element across states, which the element-tracking `mapArray`
2732
+ * cannot represent — the loop must use anchored emission instead.
2733
+ *
2734
+ * Element / component branches return `false`; a fragment is element-like
2735
+ * only when it flattens to exactly one element child.
2736
+ */
2737
+ function branchHasNoElement(node: IRNode): boolean {
2738
+ if (node.type === 'element' || node.type === 'component') return false
2739
+ if (node.type === 'conditional') {
2740
+ return branchHasNoElement(node.whenTrue) || branchHasNoElement(node.whenFalse)
2741
+ }
2742
+ if (node.type === 'fragment') {
2743
+ const real = node.children.filter(
2744
+ (c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim())
2745
+ )
2746
+ return real.length !== 1 || branchHasNoElement(real[0])
2747
+ }
2748
+ // expression, text, and everything else: not a single tracked element.
2749
+ return true
2750
+ }
2751
+
2752
+ /**
2753
+ * When the loop body is a single whole-item conditional with an element-less
2754
+ * branch (the #1665 shapes: `&&`, `|| <jsx>`, `?? <jsx>`, `? <jsx> : null`),
2755
+ * return that conditional so the caller can route the loop through anchored
2756
+ * emission. Returns `null` for single-element bodies and for both-branch-
2757
+ * element ternaries (which always render exactly one element and stay on the
2758
+ * legacy `mapArray` path).
2759
+ */
2760
+ function loopBodyItemConditional(children: IRNode[]): IRConditional | null {
2761
+ const real = children.filter(
2762
+ (c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim())
2763
+ )
2764
+ if (real.length !== 1) return null
2765
+ const only = real[0]
2766
+ if (only.type !== 'conditional') return null
2767
+ if (branchHasNoElement(only.whenTrue) || branchHasNoElement(only.whenFalse)) {
2768
+ return only
2769
+ }
2770
+ return null
2771
+ }
2772
+
2773
+ /**
2774
+ * Hoist a key expression out of a whole-item conditional for `mapArray`'s
2775
+ * keyFn. Ignores element-less branches (they carry no element and thus no
2776
+ * key) and requires the rendering branch(es) to agree on the key expression.
2777
+ * Returns `null` when no key can be determined.
2778
+ */
2779
+ function extractItemConditionalKey(cond: IRConditional): string | null {
2780
+ const a = branchHasNoElement(cond.whenTrue) ? null : extractLoopKey(cond.whenTrue)
2781
+ const b = branchHasNoElement(cond.whenFalse) ? null : extractLoopKey(cond.whenFalse)
2782
+ if (a !== null && b !== null) {
2783
+ return normalizeKeyExpr(a) === normalizeKeyExpr(b) ? a : null
2784
+ }
2785
+ return a ?? b
2786
+ }
2787
+
2682
2788
  function transformMapCall(
2683
2789
  node: ts.CallExpression,
2684
2790
  ctx: TransformContext,
@@ -2947,6 +3053,36 @@ function transformMapCall(
2947
3053
  }
2948
3054
  if (index) ctx.loopParams.add(index)
2949
3055
 
3056
+ // Logical control flow (`cond && <X/>`, `a ?? themeLogo()`) as the map
3057
+ // body. This is not a JSX literal, ternary, or block, so without this
3058
+ // the dispatch below leaves `children` empty and the whole `.map(...)`
3059
+ // falls through to the reactive-text path — emitting the callback
3060
+ // verbatim. That left inline JSX uncompiled and module-level JSX
3061
+ // helpers undeclared (ReferenceError at hydration, #1665). Route the
3062
+ // logical body through the shared JSX expression transformer, which
3063
+ // lowers it into an IRConditional and inlines any JSX helper, exactly
3064
+ // like the ternary form.
3065
+ //
3066
+ // Scoped deliberately to logical operators that actually render JSX
3067
+ // (inline literal or a tracked helper call): a bare call body
3068
+ // (`map(t => renderItem(t))`) stays on the existing reactive-text path
3069
+ // that #546 owns, and a scalar logical body (`t.active && t.label`)
3070
+ // keeps rendering its value.
3071
+ const tryTransformRenderableBody = (expr: ts.Expression): void => {
3072
+ if (!ts.isBinaryExpression(expr)) return
3073
+ const op = expr.operatorToken.kind
3074
+ if (
3075
+ op !== ts.SyntaxKind.AmpersandAmpersandToken &&
3076
+ op !== ts.SyntaxKind.BarBarToken &&
3077
+ op !== ts.SyntaxKind.QuestionQuestionToken
3078
+ ) {
3079
+ return
3080
+ }
3081
+ if (!containsJsxInExpression(expr) && !callsJsxHelper(expr, ctx)) return
3082
+ const transformed = transformJsxExpression(expr, ctx, isClientOnly)
3083
+ if (transformed) children = [transformed]
3084
+ }
3085
+
2950
3086
  // Transform callback body
2951
3087
  const body = callback.body
2952
3088
  if (ts.isJsxElement(body) || ts.isJsxSelfClosingElement(body) || ts.isJsxFragment(body)) {
@@ -2973,6 +3109,8 @@ function transformMapCall(
2973
3109
  } else if (method === 'flatMap' && ts.isArrayLiteralExpression(inner)) {
2974
3110
  // flatMap arrow with array literal: items.flatMap(item => ([<A/>, <B/>]))
2975
3111
  children = transformArrayLiteralChildren(inner, ctx)
3112
+ } else {
3113
+ tryTransformRenderableBody(inner)
2976
3114
  }
2977
3115
  } else if (method === 'flatMap' && ts.isArrayLiteralExpression(body)) {
2978
3116
  // flatMap arrow with array literal: items.flatMap(item => [<A/>, <B/>])
@@ -3025,6 +3163,8 @@ function transformMapCall(
3025
3163
  if (method === 'flatMap' && children.length === 0) {
3026
3164
  flatMapCallback = buildFlatMapCallback(callback, body, ctx)
3027
3165
  }
3166
+ } else {
3167
+ tryTransformRenderableBody(body)
3028
3168
  }
3029
3169
 
3030
3170
  // Unregister loop params
@@ -3055,7 +3195,15 @@ function transformMapCall(
3055
3195
  // same `key={EXPR}`, that EXPR is lifted out to mapArray's keyFn so a
3056
3196
  // shape change (e.g. `<polygon>` ↔ `<circle>`) replaces the DOM node
3057
3197
  // instead of mutating attributes on the wrong tag.
3058
- const key = children.length > 0 ? extractLoopKey(children[0]) : null
3198
+ // Whole-item conditional bodies (#1665): the loop item is a single
3199
+ // conditional whose at-least-one branch renders nothing, so an item shows
3200
+ // 0-or-1 element. The key lives inside the rendering branch, so hoist it
3201
+ // from there; a flag routes the loop through anchored emission downstream.
3202
+ const itemConditional = children.length > 0 ? loopBodyItemConditional(children) : null
3203
+ const bodyIsItemConditional = itemConditional !== null
3204
+ const key = bodyIsItemConditional
3205
+ ? extractItemConditionalKey(itemConditional!)
3206
+ : (children.length > 0 ? extractLoopKey(children[0]) : null)
3059
3207
 
3060
3208
  // Extract childComponent info if the loop body is a single component
3061
3209
  // This enables createComponent-based rendering with proper prop passing
@@ -3137,6 +3285,7 @@ function transformMapCall(
3137
3285
  callsReactiveGetters: callsReactive || undefined,
3138
3286
  hasFunctionCalls: hasCalls || undefined,
3139
3287
  bodyIsMultiRoot: bodyIsMultiRoot || undefined,
3288
+ bodyIsItemConditional: bodyIsItemConditional || undefined,
3140
3289
  childComponent,
3141
3290
  nestedComponents,
3142
3291
  filterPredicate,
@@ -128,22 +128,40 @@ function runSinglePass(
128
128
  }
129
129
 
130
130
  function visit(node: ts.Node): void {
131
+ // `renderNode={(n) => <div/>}` — arrow in JsxAttribute position.
131
132
  if (ts.isJsxAttribute(node) && node.initializer && ts.isJsxExpression(node.initializer) && node.initializer.expression) {
132
- let expr: ts.Expression = node.initializer.expression
133
- while (ts.isParenthesizedExpression(expr)) expr = expr.expression
134
- if (ts.isArrowFunction(expr) && arrowBodyContainsJsx(expr)) {
135
- const handled = handleInlineArrow(expr)
136
- if (handled) {
137
- // Don't dive into the arrow's body in this pass — the next
138
- // fixpoint iteration will see the synthesized component at
139
- // module scope and process any nested inline arrows there.
140
- return
141
- }
133
+ if (tryHandleArrowValue(node.initializer.expression)) {
134
+ // Don't dive into the arrow's body in this pass — the next
135
+ // fixpoint iteration will see the synthesized component at
136
+ // module scope and process any nested inline arrows there.
137
+ return
142
138
  }
143
139
  }
140
+ // `{ piconic: () => <BrandLogo/> }` — arrow as an object-literal
141
+ // property value (e.g. a `Record<K, () => JSX>` lookup map). Without
142
+ // this the JSX leaks untransformed into both the SSR template and the
143
+ // client bundle (#1663).
144
+ if (ts.isPropertyAssignment(node) && node.initializer) {
145
+ if (tryHandleArrowValue(node.initializer)) return
146
+ }
144
147
  ts.forEachChild(node, visit)
145
148
  }
146
149
 
150
+ /**
151
+ * If `initializer` is (a parenthesized chain wrapping) an arrow function
152
+ * whose body contains JSX, hoist it into a synthesized component and
153
+ * record the replacement. Returns true when the arrow was successfully
154
+ * hoisted, so the caller can skip recursing into the arrow body.
155
+ */
156
+ function tryHandleArrowValue(initializer: ts.Expression): boolean {
157
+ let expr: ts.Expression = initializer
158
+ while (ts.isParenthesizedExpression(expr)) expr = expr.expression
159
+ if (ts.isArrowFunction(expr) && arrowBodyContainsJsx(expr)) {
160
+ return handleInlineArrow(expr)
161
+ }
162
+ return false
163
+ }
164
+
147
165
  function handleInlineArrow(arrow: ts.ArrowFunction): boolean {
148
166
  const paramNames = collectArrowParamNames(arrow)
149
167
  const free = collectFreeIdentifiers(arrow)
@@ -110,7 +110,7 @@ export function* iterateJsTokens(
110
110
  }
111
111
  }
112
112
 
113
- function isTriviaKind(kind: ts.SyntaxKind): boolean {
113
+ export function isTriviaKind(kind: ts.SyntaxKind): boolean {
114
114
  return (
115
115
  kind === ts.SyntaxKind.WhitespaceTrivia
116
116
  || kind === ts.SyntaxKind.NewLineTrivia
@@ -164,6 +164,21 @@ function canRegexStartHere(prev: ts.SyntaxKind | undefined): boolean {
164
164
  // ---------------------------------------------------------------------------
165
165
  // Token classification helpers used by the consumers below.
166
166
 
167
+ /**
168
+ * Whether `kind` is an identifier-like token — a plain identifier or any
169
+ * reserved/contextual keyword. Keywords lex to their own token kinds but
170
+ * still match the `[A-Za-z_$][\w$]*` shape the previous hand-rolled
171
+ * scanners treated as candidate identifier tokens, so consumers that want
172
+ * "every bare word in code context" (e.g. `tokenContainsIdent`) include
173
+ * them and compare the slice text themselves.
174
+ */
175
+ export function isIdentifierLikeToken(kind: ts.SyntaxKind): boolean {
176
+ return (
177
+ kind === ts.SyntaxKind.Identifier
178
+ || (kind >= ts.SyntaxKind.FirstKeyword && kind <= ts.SyntaxKind.LastKeyword)
179
+ )
180
+ }
181
+
167
182
  /** A token whose textual content is a non-code region (string body, regex, comment). */
168
183
  function isOpaqueContentKind(kind: ts.SyntaxKind): boolean {
169
184
  return (
package/src/types.ts CHANGED
@@ -532,6 +532,18 @@ export interface IRLoop {
532
532
  */
533
533
  bodyIsMultiRoot?: boolean
534
534
 
535
+ /**
536
+ * True when the loop body is a single whole-item conditional whose at
537
+ * least one branch renders no element (`arr.map(t => cond && <li/>)` or
538
+ * `cond ? <li/> : null`), so an item renders 0-or-1 element per pass
539
+ * (#1665). Drives anchored emission: per-item `<!--bf-loop-i:KEY-->`
540
+ * anchors in the template and a `mapArrayAnchored` call whose renderItem
541
+ * lets `insert()` own the (possibly empty) content. Single-element bodies
542
+ * and both-branch-element ternaries set this false and keep the legacy
543
+ * `mapArray` emission.
544
+ */
545
+ bodyIsItemConditional?: boolean
546
+
535
547
  /**
536
548
  * Raw JS of pre-return statements in block body .map() callback.
537
549
  * Example: `items.map(item => { const label = item.name.toUpperCase(); return <li>{label}</li> })`