Repository navigation
fix(core): start an element at its <, and continue an element statement across a line break (#467, #496) - #500
Merged
Conversation
…ment across a line break (#467, #496) - An element or fragment with whitespace or a comment after its `<` (`< div>`, `< >`, `<` then a comment on the next line) now starts at the `<`, and so does its opening tag, from the `<` token's own position. It used to start one character before the tag name, inside the gap, with a negative column when the gap crossed a line. Like Prettier, a comment between a fragment's `<` and `>` now dangles on the opening fragment, and the formatter prints it, and a comment before a tag name, there. - An operator on the line after an element that starts a statement continues the expression, as in TSX: binary, logical, and relational operators, `**`, `?`, and `,`. `as` and `satisfies` still continue only on the element's line, a `<` that starts the next line is still the next element, and template render nodes and children don't change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Contributor
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Line comments break opening tags
- A line comment leading a tag name now breaks onto its own indented line after
<, so the opening tag stays valid instead of printing<// note.
- A line comment leading a tag name now breaks onto its own indented line after
Or push these changes by commenting:
@cursor push b67ab6e377
Preview (b67ab6e377)
diff --git a/.changeset/prettier-opening-tag-line-comments.md b/.changeset/prettier-opening-tag-line-comments.md
new file mode 100644
--- /dev/null
+++ b/.changeset/prettier-opening-tag-line-comments.md
@@ -1,0 +1,5 @@
+---
+'@tsrx/prettier-plugin': patch
+---
+
+A line comment between `<` and a tag name stays on its own line inside the opening tag. It used to print against the `<` (`<// note`), which comments out the rest of that line.
diff --git a/packages/prettier-plugin/src/index.js b/packages/prettier-plugin/src/index.js
--- a/packages/prettier-plugin/src/index.js
+++ b/packages/prettier-plugin/src/index.js
@@ -12494,14 +12494,20 @@
typeArgsDoc = path.call(print, 'openingElement', 'typeArguments');
}
// A comment before the tag name, as in `</* note */ div>`, prints before
- // it, and one after it, as in `<div // note`, prints after it
+ // it, and one after it, as in `<div // note`, prints after it.
+ // A line comment must not sit against `<` (`<// note` comments out the rest
+ // of that line). Break after `<`, as `printJSXOpeningFragment` does.
const nameNode = /** @type {AST.Node & AST.NodeWithMaybeComments} */ (openingElement.name);
- const openingTagName = finishTsrxNode(
+ const nameLeadingComments = nameNode.leadingComments ?? [];
+ let openingTagName = finishTsrxNode(
nameNode,
- printLeadingComments(nameNode, nameNode.leadingComments ?? [], options),
+ printLeadingComments(nameNode, nameLeadingComments, options),
tagName,
options,
);
+ if (nameLeadingComments[0]?.type === 'Line') {
+ openingTagName = indent([hardline, openingTagName]);
+ }
const nameHasComments =
hasComment(nameNode) ||
Boolean(
diff --git a/packages/prettier-plugin/src/index.test.js b/packages/prettier-plugin/src/index.test.js
--- a/packages/prettier-plugin/src/index.test.js
+++ b/packages/prettier-plugin/src/index.test.js
@@ -14784,6 +14784,34 @@
expect(await format(source)).toBeWithNewline(expected);
});
+ // A line comment glued to `<` (`<// note`) comments out the rest of that
+ // line. Keep it on its own line inside the tag, as a fragment does.
+ it.each([
+ [
+ 'const a = <\n // note\n div></div>;',
+ 'const a = (\n <\n // note\n div\n ></div>\n);',
+ ],
+ ['const a = <\n // note\n div />;', 'const a = (\n <\n // note\n div\n />\n);'],
+ [
+ 'const a = <\n // note\n div a="1"></div>;',
+ 'const a = (\n <\n // note\n div\n a="1"\n ></div>\n);',
+ ],
+ [
+ 'function App() {\n return (\n <\n // note\n div\n >\n test\n </div>\n );\n}',
+ 'function App() {\n return (\n <\n // note\n div\n >\n test\n </div>\n );\n}',
+ ],
+ [
+ 'export function App() @{\n <\n // note\n div\n >\n x\n </div>\n}',
+ 'export function App() @{\n <\n // note\n div\n >\n x\n </div>\n}',
+ ],
+ [
+ 'const a = <\n // note\n div<T> />;',
+ 'const a = (\n <\n // note\n div<T>\n />\n);',
+ ],
+ ])('keeps a line comment after the `<` of %j inside the tag', async (source, expected) => {
+ expect(await format(source)).toBeWithNewline(expected);
+ });
+
it('joins an operator on the next line to the element it continues, like Prettier', async () => {
const source = '<div />\n+ 1;\n\nfunction f() {\n <div />\n > 5;\n}';
expect(await format(source)).toBeWithNewline(You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit d0d2352. Configure here.
…er the `<` A line comment between an opening tag's `<` and its name printed right after the `<`, and `<//` reads as a closing tag in TSX. That comment, and a block comment on a line of its own (which joined the `<`'s line on the next format), now start on the line after the `<`, indented with the name and the attributes, as Prettier prints the comments of closing tags and fragments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 #467
Closes #496
Summary
Two parser fixes in
@tsrx/core, plus the formatter change the first one needs.const a = < div>x</div>;<)const a = < >x</>;const a = <+// c+>on the next lines{ line: 3, column: -1 }{ line: 1, column: 10 }<div />then> 5;,? a : b;,&& b;,=== x;on the next lineUnexpected token (2:0)ExpressionStatement(BinaryExpression,ConditionalExpression,LogicalExpression)<div />then+ 1;on the next line<div />and+1BinaryExpressionTypeScript 5.9.3's TSX parser gives the same statement structure for every #496 source, with no syntax diagnostics.
Changes
<starts inside the gap #467).parseElementruns after the<(jsxTagStart) token is consumed, and took the start as one character before the current token, the tag name or>. It now uses the<token's own position,lastTokStartandlastTokStartLoc, and starts the node withstartNodeAt. The opening element or fragment gets the same start, sincejsx_parseOpeningElementAtreceives it, and so does everything built from the element's start: theExpressionStatementand operators of fix(core): continue an expression after an element that starts a statement, and read type parameters on the line after a declaration name (#416, #419) #471's#parseElementExpressionStatement, and the editor mappings. Every caller ofparseElementconsumes the<withnext()right before the call (statement starts,@{ … }render nodes, directive bodies, template children, expression position, and the re-read paths), so the previous token is always the<.<starts inside the gap #467). Once the element contains the comment, comment attachment nests it, as Prettier does. A comment before the tag name already becomes the name's leading comment. For a fragment,get_comment_handlersnow keeps a comment between<and>on theJSXOpeningFragmentas a dangling (innerComments) comment, as Prettier's attachment does. Without that it went to the fragment's first child.@tsrx/prettier-plugin).printJSXElementprints the tag name's leading comments inside the tag (</* note */ div>), and a newprintJSXOpeningFragmentprints the opening fragment's comments between<and>, both like Prettier's JSX printer. Before this PR the comment sat before the node, so the plugin printed it before the element (/* note */ <div>). Without this change the plugin would have deleted a comment before a tag name, and printed a fragment's comment into its children, where a second pass deleted it. A line comment before the tag name, or a block comment on a line of its own, starts on the line after the<(46f82bb, from Bugbot's review): Prettier prints it right after the<, and<// creads as a closing tag in TSX.#continuesElementExpressionreturnedfalseafter any line break. Binary, logical, and relational operators,**,?, and,now continue the expression on the next line too, as in TSX.asandsatisfieskeep the same-line rule, since TypeScript stops at a line break before them. A lone<that starts the next line never continues: it's the next element's tag start, as fix(core): continue an expression after an element that starts a statement, and read type parameters on the line after a declaration name (#416, #419) #471 kept it, or a generic arrow (<T,>(x) => x), which TypeScript also reads as a tag after an element.<=and<<continue. The tokenizer already reads these tokens as operators after an element (a/stays a/token until Acorn re-reads it as a regex at a statement start), so no tokenizer state changes.Boundaries kept
@{ … }render node, a directive body's render node, an@casebody, and element children still don't go throughparseStatement:@{\n <div />\n > 5\n}, the same in@ifand@casebodies, still fail withUnexpected token;@{\n const a = 1\n <div />\n + 1\n}still reports "statements cannot follow the rendered output" with the same loose AST; and<div>\n <span />\n > 5\n</div>still has> 5as text. A plain block inside a setup statement (@{ if (x) { <div />\n > 5 } <span /> }) continues, like any function body.<div />then<span />on the next line is still two elements (TypeScript reports "JSX expressions must have one parent element").(,[, a template literal,!, and++on the next line start the next statement, as in TypeScript, and=is still rejected.Behavior change to note
As in TSX (and in JavaScript after any expression), a
/on the line after an element statement now divides.<div />followed by/re/.test(x);on the next line used to be two statements; it's now(<div />) / re / .test(x), which fails withUnexpected token (2:4). TypeScript reports an error there too. The changeset says a;after the element is needed.Verification
Issue repros. Every repro in both issues, with and without
{ collect: true, comments: [] }. [Bug]: tsrx-core: An element or fragment with whitespace or a comment after<starts inside the gap #467: the element and its opening tag start at the<with the rightloc, in expression position, at a statement start, in a function body, as a@{ … }render node, and in an@ifbody. [Bug]: tsrx-core: Parser ends an element statement before an operator on the next line, where TSX continues the expression #496: the statements matchts.createSourceFile('x.tsx', …, ScriptKind.TSX)for all five sources and for 25 more (every operator group,<=,<<,instanceof,in,??,>>>, fragments,</div>endings, a comment before the line break, a function body). The ones that still differ are errors in both parsers (<div />then< 5,as any,satisfies any,/re/.test(x)), plus<div />then<span />, which TypeScript also reports as an error.AST comparison. I parsed 9603 unique sources with
origin/main(e9274468) and with this branch, in strict mode, with the formatter's options (collect,comments,preserveParens), and in loose mode, and compared the full serialized AST (every node'sstart/end/loc, attached comments, metadata) and the collected errors: the 69 tracked.tsrxfiles, 10 more fixture sources, 6416 code-like string literals from 131 test files, and the 2040 inputs and 2040 outputs of the Prettier format snapshots on feat: add tsrx-prettier-plugin, built on Prettier's own printer and tested with Prettier's own tests #409's branch (read with itstests/snapshot-format.js). 9 of the 28809 parses differ, from 3 sources, all fixed cases:<div />\n+ 1;from fix(core): continue an expression after an element that starts a statement, and read type parameters on the line after a declaration name (#416, #419) #471's parser test, which pinned the old two-statement result (updated here).jsx/fragment/fragment.js. Its two fragments with a gap after<(</* open fragment */>and<+// open fragment+>) now start at the<(one of them hadcolumn: -1), and their comments are the opening fragments' inner comments instead of the fragments' leading comments.Of the 9512 elements and fragments in the corpus, those 4 are the only ones with a gap after
<, so [Bug]: tsrx-core: An element or fragment with whitespace or a comment after<starts inside the gap #467 moves no other position.Editor mappings. For React, Preact, Solid, Vue, and Hono,
compile_to_volar_mappingsgives the same virtual TypeScript asmainfor elements with a gap after<(expression position,@{ … }render node,@if/@elsebodies, comments in the gap). Only the mappings that started in the gap change:mainmapped the space or comment character before the tag name to the generated<, and they now map the<(and Solid's element-span mapping covers the whole element).compileoutput is unchanged. A new shared source-mapping test checks this for every target. The [Bug]: tsrx-core: Parser ends an element statement before an operator on the next line, where TSX continues the expression #496 shapes compile and map exactly like their same-line forms for every target.Formatters. The old plugin gives the same output as on
mainfor all 9603 corpus sources except the 3 above (<div />\n+ 1;now prints<div /> + 1;, and fragment.js keeps its opening-fragment comments in place). With a scratch copy of feat: add tsrx-prettier-plugin, built on Prettier's own printer and tested with Prettier's own tests #409'stsrx-prettier-plugin(at5463a78a) pointed at this core,jsx/fragment/fragment.js format 1no longer throws "Comment location overlaps with node location" and matches Prettier. It's the only one of the 2040 cases that changes (1954 → 1955 passing), so feat: add tsrx-prettier-plugin, built on Prettier's own printer and tested with Prettier's own tests #409'sprettier-known-failures.jsonneeds that entry removed once this lands. For the gap and next-line shapes, both plugins print what Prettier'stypescriptparser prints (except the old plugin's missing;after a top-level element, as before), withsemi: trueandfalse, and the output formats to itself.Tests. New parser tests in
packages/tsrx/tests/utils/parser.test.js(next-line continuation, the boundaries above including the template cases, element starts at the<in six positions, comment attachment in the gap), a shared mapping test inpackages/tsrx/tests/shared/source-mappings.js, and formatter tests inpackages/prettier-plugin/src/index.test.js. All of them fail withmain's sources. In the fullvitest run(118 files), 6909 of 6910 tests pass, 60 skipped. The one failure was atypescript-plugintest that timed out at 5 s whilepnpm typecheckran alongside it; thetypescript-pluginproject passes on its own (184 tests).pnpm typecheckpasses. As in fix(core): continue an expression after an element that starts a statement, and read type parameters on the line after a declaration name (#416, #419) #471, pnpm didn't link thetsrx-tscbin in this worktree, so I ranvite-plugin-hono'stypecheck:testsstep throughnode packages/typescript-plugin/dist/tsc.js.pnpm format:checkandpnpm changeset:checkpass.Related issues filed
<div>/* c */x</div>→<div>x</div>). Already onmain, separate cause.</div /* c */>) and moves one out of a closing fragment (</ /* c */>). It's the closing-tag counterpart of the opening-tag handling here, already onmain.🤖 Generated with Claude Code
Note
Medium Risk
Changes core JSX parse boundaries and node spans used for AST and source maps; behavior is intentionally aligned with TSX but can shift how some multi-line snippets parse (e.g.
/on the next line now divides).Overview
Aligns @tsrx/core parsing and @tsrx/prettier-plugin output with TypeScript/Prettier for two JSX edge cases.
Element start positions (#467): Elements and fragments with whitespace or comments after
<now begin at the<(vialastTokStart/startNodeAt), not in the gap before the tag name—fixing negative columns and wrong editor mappings. Comments in that gap attach like Prettier: leading on the tag name, or inner onJSXOpeningFragment. The formatter prints those comments inside the opening tag/fragment instead of before the node.Expression continuation (#496): When a JSX element starts a statement, binary/logical/relational operators,
**,?, and,on the next line now continue the same expression (e.g.<div />\n+ 1;). Same-line-only rules remain foras/satisfies; a<starting the next line is still a new tag. Template/@{…}render rules and in-template text behavior are unchanged.Adds changeset, parser/mapping tests, and formatter snapshot-style tests for these shapes.
Reviewed by Cursor Bugbot for commit d0d2352. Bugbot is set up for automated code reviews on this repo. Configure here.