Repository navigation
fix(core): read the text of elements in {…} containers and switch cases like everywhere else (#612, #613) - #641
Merged
Conversation
…s template text (#612, #613) In an element inside a `{…}` container, the token after a closing tag was read as code, because the closing tag only let the parent read it as text outside every container. The text lost its leading space and a non-breaking space there failed to parse (#612). Only a parent opened inside the innermost container counts now, and the container's path baseline starts at 0 once a control-flow body in the container has replaced the path, so text after a closing tag or a child container in an element in such a body reads too. In an element in a `switch` case (`@switch` or a function's `switch`), the text was read as code whenever a `switch` label was in scope: leading spaces were lost, a non-breaking space failed to parse, and text before a tag overflowed the stack (#613). The label now only blocks text when the switch started after the innermost element, which is between its cases. The template body parser raises `Unexpected token` when a text read makes no progress, instead of reading the same token until the stack runs out. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-template-text-containers
This was referenced Sep 25, 2026
1 task done
This was referenced Sep 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #612.
Closes #613.
Template text in an element inside a
{…}container or aswitchcase now follows the JSX whitespace rules that #615 applied everywhere else, and renders on every target what the same TSX renders.The bugs
{…}container (a child container or an attribute value), the token after a closing tag was read as code. A closing tag lets the parent read that token as text only wheninside_parent_templateholds, and that required no enclosing container at all. So{x && <div><b>1</b> 2</div>}read"2"and rendered12, and a non-breaking space there failed withUnexpected character.#shouldReadTemplateRawTextTokencounts only elements above the container's path baseline, a#pathlength. A control-flow body in the container ({x && <section>@if (y) { <div>{a} 2</div> }</section>}) replaces#path, so that length no longer points into it. The text after a child container, or after a closing tag, in an element there lost its space the same way.switchcase, text was read as code.#shouldReadTemplateRawTextTokenreturned false whenever aswitchlabel was inthis.labels, and a case keeps its label while the elements in it parse.<div>1<b /></div>) overflowed the stack: the<after1was read as less-than, the template body parser read no text from it, and it read the same<again.@switchand for a function's ownswitchalike.function A() { switch (x) { case 1: return <div> 1<b /></div>; } }overflowed the stack in plain TSX.@switchsources from fix(core): start the text after a closing tag at the tag, and read a non-breaking space as text (#442, #444, #540) #615 with a non-breaking space right after a nested closing tag.The fix
All in
packages/tsrx/src/plugin.js:#expressionContainerPathBaselinesrecords the#patharray with its length.#containerPathBaseline()gives that length while#pathis the same array, and 0 once a directive body or setup statement in the container has replaced it, since every node on the new path opened inside the container.inside_parent_templatecounts only an ancestor opened inside the innermost container (this.#path.slice(this.#containerPathBaseline(), -1)) instead of requiring no container. Above that ancestor the container's expression goes on ({x ? <div>…</div> : <p />}), so the token after the container's own element stays code, as before.#shouldReadTemplateRawTextTokenuses the same baseline.parseElementrecordsthis.labelsand its length when each element starts (#elementLabels). Theswitchgate now applies only when aswitchbegan after the innermost element (#insideSwitchStartedAfter), that is, between the cases of a switch, where the case tests and@casekeywords are code. A function body starts a newthis.labels, so a switch in it counts as started after any element outside it.parseTemplateBodyraisesUnexpected tokenwhen a text read consumes nothing and leaves the same token, instead of reading it until the stack runs out, as [Bug]: tsrx-core: Text in an element in an @switch case is read as code: leading spaces are lost, and text before a tag overflows the stack #613's fix direction suggests. After the two changes above, nothing in this PR's scope reaches it.It's narrow in that each gate still applies wherever it did, except to an element opened inside the construct the gate describes. The comparison below changes one existing input. No upstream cause and no override: plain acorn-typescript has no templates.
The closing tag still requires
#templateScriptParsingDepth === 0, and#shouldReadTemplateRawTextTokenstill returns false while it is above 0. So text in an element in a setup statement (const a = <span><b>1</b> 2</span>;in a@{ … }body) is still read as code. That's a separate gate, filed as #636 (Findings).Rendered output on the targets
The shared runtime suite from #615 (
packages/tsrx/tests/shared/runtime/jsx-text-whitespace*) gets 11 cases, so it renders 20 on React, Preact, Solid, Vue, and Hono in jsdom. Each compares an element'sinnerHTMLwith what the same TSX renders:@ifbody in a container;@case: a space after an opening tag, after a closing tag, and after a child container, and text before a tag;@default: [Bug]: core drops the space after the closing tag of an element whose body ends in a line break #442's shape;switchcase: text before a tag;@case, with each target's compiler's rule for it (kept on Vue, trimmed elsewhere, as in fix(core): start the text after a closing tag at the tag, and read a non-breaking space as text (#442, #444, #540) #615).On
mainthe fixture doesn't compile:Not enough stack space to parse inputat the@case's4<b />.The container cases select the element inside the container, not the container's parent, because the targets render the container's own slot differently: Vue adds a text anchor and
<!--if-->. The suite leaves out an inline non-breaking space between children, as #615 did, since Solid's compiler writes it as a plain space for TSX too.Formatters
Both formatters format every generated container and
@switchsource below (8,816), and their output parses. Onmainmost of these sources failed to parse, so neither formatter could format them.@tsrx/prettier-pluginchanges the rendered text of none of them. 55 need a second pass, and none of them because of this change, since those shapes need a second pass onmaintoo:@switchcases, which needs a second pass in plain templates too ([Bug]: @tsrx/prettier-plugin: A comment on its own line before a multi-line JSX child keeps the text after the child on its closing line, and needs a second format pass #640).tsrx-prettier-pluginis stable on every source. 159 change what they render: 9 shapes with a block comment between children, which change the same way in plain templates ([Bug]: tsrx-prettier-plugin changes what an element renders when a block comment sits between its children #639).Verification
AST and error comparison,
main(4b38c47d) against this branch: strict,{ collect: true, errors: [], comments: [], preserveParens: true }, and{ loose: true }, in 4 worker threads with a hard timeout. The inputs are 17,952: the 70 tracked.tsrxfiles, the input and output of all 2,040 Prettier snapshot cases (readSnapshotEntries/readFormatCase), and 13,802 distinct string literals from test files.<>{label} none</>in an@defaultcase in aparser.test.jssource now reads" none", as TSX does, instead of"none", which was [Bug]: tsrx-core: Text in an element in an @switch case is read as code: leading spaces are lost, and text before a tag overflows the stack #613's lost space.Mutated inputs. 28,852 inputs made from the same corpus (truncated, a span deleted, or a line break, comment, tag, brace, or non-breaking space inserted), in the three modes. No hangs, and the same inputs parse. 7 change, all intended:
<of a type parameter list sits where an element's text starts (const f1 = <b><T,>() => 1;) threwNot enough stack space to parse input. They now throwUnexpected token (1:14)from the no-progress check.{now reads as text. That input fails with'}' expected.for the missing}instead ofUnexpected character([Bug]: tsrx-core: Text after a closing tag in an element inside {…} loses its leading space, and a non-breaking space there fails to parse #612)." none"source above.@switchcases now read as the same markup reads in an@ifbody (checked against it):@caseelement's opening tag now leads the{'Away'}after it;<followed by a tab is text (<em>{'rest'}<\t…, unclosed);<b>in an attribute value of an element in an@caseno longer gets theaafter it as a child.TSRX against TSX. 13,456 generated sources: 464 shapes in 29 places. Each shape combines one of 6 kinds of previous child, 16 kinds of whitespace, comments, and non-breaking spaces, and 5 kinds of next child. The places are fix(core): start the text after a closing tag at the tag, and read a non-breaking space as text (#442, #444, #540) #615's 10 plus 19 more:
@if, and an@switchinside a child container;returnwith a container;@default, a nested element, the component's top level,@ifinside a case, a case inside@if, a nested@switch, and a container and an attribute value inside a case;@case, and in a JSswitchin a component.The text children, cleaned by Babel's JSX rule, are compared with Babel's JSX children for the same TSX without the comments.
main: 4,485 mismatches and 2,585 errors.Tests.
vitest run --maxWorkers=4fortsrx-utils,tsrx-analyze, the five compilers, the five runtime projects,prettier-plugin, andtsrx-prettier-plugin: 51 files, 9,214 passed, 77 skipped. New tests:parse_in_worker_with_ast, and one for the no-progress check;@case, with a non-breaking space;All of them fail on
main.pnpm typecheckpasses.tsrx-tscisn't linked afterpnpm install --ignore-scripts, so I built@tsrx/typescript-pluginand ran the@tsrx/vite-plugin-honotypecheck:testsstep throughpackages/typescript-plugin/dist/tsc.js, then the steps after it.pnpm formatchanged nothing else, andpnpm format:checkandpnpm changeset:checkpass. Changeset:patchfor@tsrx/core.Findings
Filed, with other causes:
@{ … }body is read as code, through#templateScriptParsingDepth, the same mechanism as [Bug]: tsrx-core: Text in an element in an @switch case is read as code: leading spaces are lost, and text before a tag overflows the stack #613. Leading spaces are lost, a non-breaking space fails, and text right before a tag (const a = <span>Hello<b /></span>;) overflows the stack onmain. It's 229 of the 464 generated shapes in each setup-statement place.tryParsebranch, though, so it surfaces asA parse branch shortened the token context stack below its checkpoint([Bug]: tsrx-core: A syntax error right after an element's closing tag fails with acorn-typescript's internal 'A parse effect shortened an append-only array' #638).{…}container, a block comment between children is recorded as coming before the element's first child.jsx_readTokengives it element metadata before the preceding child is pushed, so comment attachment puts it in the element body, and@tsrx/prettier-pluginmoves it before the closing tag on the next pass.const el = <div>x</div;) fails with acorn-typescript's internalA parse effect shortened an append-only array. TSRX shortensthis.contextby assigning its length inside thetryParsebranch, bypassingparseEffects. 34 mutated inputs onmainend with one of the two internal messages.tsrx-prettier-pluginprints the spaces beside a comment between children as the comment's own separators, not as one JSX whitespace run, so it changes what 9 shapes render (<div><b>t</b> /* c */ </div>loses its space).@tsrx/prettier-pluginputs a child's leading comment and the child in onefillcontent.fitsstops at the comment's hard line break, so the text after a multi-line child stays on its closing line (</span> 3) when a comment is on its own line before it, and a block comment on the opening tag's line needs a second pass.For the user:
@switchcases too, and each target's compiler decides: Vue keeps them, and oxc, TypeScript, and Solid's compiler trim them. The new runtime cases follow that split.🤖 Generated with Claude Code
Note
Medium Risk
Touches core template/JSX tokenization in
plugin.js; behavior changes are targeted but affect parsing of containers and switch cases broadly.Overview
Fixes #612 and #613 so whitespace and text nodes inside elements nested in
{…}expression containers, attribute JSX values,@switchcases, and plainswitchreturns parse like normal template markup instead of as JavaScript.The TSRX parser now tracks expression-container path baselines with the actual
#pathreference (not only its length), so text after closing tags and child containers still counts as template text when control-flow bodies replace#path. Closing-tag handling uses the same baseline to decide whether the parent may read trailing text. Switch gating is scoped per element: raw text is blocked only when aswitchlabel began after that element opened (between cases), not for markup inside a case body.When raw-text consumption would leave the tokenizer unchanged,
parseTemplateBodyreportsUnexpected tokeninstead of looping until stack overflow.Adds parser, compile, and shared runtime whitespace coverage for container, attribute, directive-in-container,
@switch, and JSswitchshapes.Reviewed by Cursor Bugbot for commit a6d88ae. Bugbot is set up for automated code reviews on this repo. Configure here.