@tsrx/prettier-plugin 0.7.11 → 0.7.12

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.
package/README.md CHANGED
@@ -4,7 +4,9 @@ A Prettier plugin for formatting [TSRX](https://tsrx.dev) files.
4
4
 
5
5
  The goal is Prettier's output wherever TSRX is TSX, so TSRX only differs where its
6
6
  syntax does: `@{ … }` blocks, `@if`/`@for`/`@switch`/`@try`, `{value}` shorthand
7
- props, `<style>`/`<script>` bodies, and comments between JSX children.
7
+ props, `<style>`/`<script>` bodies, and comments between JSX children. It also
8
+ differs where the compiler reads markup differently: an element's only text keeps
9
+ a space at its edge beside its tag, so the element still gets one child.
8
10
 
9
11
  ## Usage
10
12
 
@@ -106,12 +108,33 @@ config (step 2).
106
108
  - Comments between a directive's branches are placed by Prettier's own comment
107
109
  handling for `if` and `try`, while `@if` and `@try` present themselves as
108
110
  those statements. A comment before `@empty` is handled like one before `else`.
111
+ - **`@` before a space in text:** where Prettier breaks a line at a space, it
112
+ prints the space as `{" "}`. After a word that ends in `@`, TSRX would read `@{`
113
+ as the start of a code block, so there the `{" "}` starts the next line, and a
114
+ line break between an `@` and a `{` stays. An element or fragment whose text has
115
+ an `@` before whitespace is laid out by the copy of Prettier's JSX printing in
116
+ `src/jsx.js` for that.
109
117
  - **JSX children** (`src/jsx.js`): a comment between children prints without the
110
118
  braces, as written. An element with such comments is laid out by a copy of
111
119
  Prettier's `printJsxElementInternal` and `printJsxChildren` with the two rules a
112
120
  bare comment needs: a line comment ends its line, and it keeps whitespace before
113
121
  it after text or a comment (touching them, `//` is text); text that starts with
114
- `//` right after a block comment stays on its line. Every other element is
122
+ `//` right after a block comment stays on its line. An element whose only child
123
+ is text with a space or tab at an edge (besides comments, which the compiler
124
+ leaves out, and which stay beside the text) is laid out by the plugin too, when
125
+ the compiler prints that text as one literal (`{' a '}`, so that a `<textarea>`,
126
+ a `<title>` or a component that takes `children: string` gets one string):
127
+ Prettier would move the space into a `{" "}` child once the element breaks. The
128
+ space stays beside its tag (`<p> Some text…`, `…more text </p>`), and the words
129
+ fill the lines between. A text that the compiler would split over lines (with a
130
+ non-breaking space, U+200B or a reference to whitespace) stays on one line, and
131
+ a text it splits anyway prints as before. On Vue, whose compiler keeps a text's
132
+ line breaks, a text the formatter fills renders with them, and keeping the space
133
+ beside the opening tag fills some texts that Prettier's layout left on a line of
134
+ their own: a text that fits on a line by itself but not after its tag, as in a
135
+ `<textarea className="notes">`, renders a line break and the next line's
136
+ indentation on Vue. Prettier's layout kept such a text on one line on Vue, but
137
+ gave the element two or three children on every target. Every other element is
115
138
  printed by Prettier itself. Keep the copy in step with Prettier when upgrading.
116
139
 
117
140
  The plugin needs no other Prettier plugin, including in `prettier/standalone`,
@@ -190,7 +213,8 @@ run with 3.6.0.
190
213
  - `tests/prettier-overrides.js` holds the cases where TSRX deliberately differs
191
214
  from Prettier, each with its reason. An override skips the case (for example,
192
215
  syntax that is only a proposal), expects Prettier's output for the input as a
193
- `.tsx` file, or replaces the input or the expected output.
216
+ `.tsx` file, replaces the input or the expected output, or replaces a few lines
217
+ of the expected output (`replace`).
194
218
 
195
219
  The files in `tests/prettier/` come from Prettier and are under
196
220
  [Prettier's MIT license](tests/prettier/LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsrx/prettier-plugin",
3
- "version": "0.7.11",
3
+ "version": "0.7.12",
4
4
  "description": "TSRX plugin for Prettier",
5
5
  "type": "module",
6
6
  "module": "src/index.js",
@@ -27,7 +27,7 @@
27
27
  "prettier-3-6": "npm:prettier@3.6.0"
28
28
  },
29
29
  "dependencies": {
30
- "@tsrx/core": "0.7.1"
30
+ "@tsrx/core": "0.8.0"
31
31
  },
32
32
  "files": [
33
33
  "src/"
package/src/jsx.js CHANGED
@@ -2,24 +2,30 @@
2
2
  * Prettier's layout of a JSX element's children, for the elements whose
3
3
  * children include TSRX comments (`// …` and `/* … *\/` between children,
4
4
  * which TSX reads as text, and which `parse.js` gives Prettier as the `{…}`
5
- * children `{/* … *\/}` would be), and for an element that keeps its
6
- * parentheses at the start of a statement (`keepStatementParens`). Every other
7
- * element is printed by Prettier itself.
5
+ * children `{/* … *\/}` would be), for an element whose children render one
6
+ * text that the compiler prints as one literal (`onlyTextEdges`), and for an
7
+ * element that keeps its parentheses at the start of a statement
8
+ * (`keepStatementParens`). Every other element is printed by Prettier itself.
8
9
  *
9
10
  * `printJsxElementInternal` and `printJsxChildren` are copied from Prettier
10
11
  * 3.9.9 (`src/language-js/print/jsx.js`, MIT license, Copyright © James Long and
11
- * contributors). The only changes, marked `TSRX:`, are in `printJsxChildren`,
12
- * where a bare `//` differs from `{// … }`: a `//` is a comment only after
12
+ * contributors). The only changes are marked `TSRX:`. An element's only text
13
+ * keeps the spaces at its edges (`printOnlyText`). In `printJsxChildren`, a
14
+ * bare `//` differs from `{// … }`: a `//` is a comment only after
13
15
  * whitespace (or at the start of a line, or right after a tag), and it runs to
14
16
  * the end of its line. So a line comment ends its line, keeps whitespace
15
17
  * between it and text or a comment before it, and text that starts with `//`
16
- * (right after a block comment) stays on that line. Keep the rest in step with
17
- * Prettier when upgrading.
18
+ * (right after a block comment) stays on that line. And a `{" "}` never
19
+ * follows an `@`, where TSRX would read `@{` as the start of a code block
20
+ * (`endsWithAt`); an element whose text has an `@` before whitespace is printed
21
+ * here for that (`hasAtBeforeWhitespace`). Keep the rest in step with Prettier
22
+ * when upgrading.
18
23
  *
19
24
  * @import { AstPath, Doc, ParserOptions } from 'prettier'
20
25
  * @import { Node } from './parse.js'
21
26
  */
22
27
 
28
+ import { isLayoutWhitespace, renderChildren, wrapEdgeWhitespace } from '@tsrx/core';
23
29
  import { builders, utils } from 'prettier/doc';
24
30
 
25
31
  const {
@@ -31,6 +37,7 @@ const {
31
37
  hardline,
32
38
  ifBreak,
33
39
  indent,
40
+ join,
34
41
  line,
35
42
  softline,
36
43
  } = builders;
@@ -139,6 +146,10 @@ export function printJsxElementInternal(path, options, print) {
139
146
  return [print('openingElement'), print('closingElement')];
140
147
  }
141
148
 
149
+ // TSRX: an element's only rendered text keeps the spaces at its edges.
150
+ const edges = onlyTextEdges(node);
151
+ if (edges) return printOnlyText(path, options, print, edges);
152
+
142
153
  const openingLines =
143
154
  node.type === 'JSXElement' ? print('openingElement') : print('openingFragment');
144
155
  const closingLines =
@@ -266,7 +277,9 @@ export function printJsxElementInternal(path, options, print) {
266
277
 
267
278
  if (i === children.length - 1) {
268
279
  // Trailing whitespace
269
- multilineChildren.push([/** @type {Doc} */ (multilineChildren.pop()), rawJsxWhitespace]);
280
+ const previous = /** @type {Doc} */ (multilineChildren.pop());
281
+ // TSRX: not right after an `@`, where `@{` would start a code block.
282
+ multilineChildren.push([previous, endsWithAt(previous) ? hardline : '', rawJsxWhitespace]);
270
283
  continue;
271
284
  }
272
285
 
@@ -283,6 +296,10 @@ export function printJsxElementInternal(path, options, print) {
283
296
  if (i % 2 === 0) {
284
297
  // non-line-like
285
298
  multilineChildren.push([/** @type {Doc} */ (multilineChildren.pop()), child]);
299
+ } else if (child === whitespace && endsWithAt(/** @type {Doc} */ (multilineChildren.at(-1)))) {
300
+ // TSRX: a `{" "}` right after an `@` would start an `@{ … }` code block, so
301
+ // where the line breaks, it starts the next line.
302
+ multilineChildren.push(ifBreak([softline, rawJsxWhitespace], ' '), '');
286
303
  } else {
287
304
  // line-like
288
305
  multilineChildren.push(child, '');
@@ -330,6 +347,229 @@ export function printJsxElementInternal(path, options, print) {
330
347
  return conditionalGroup([group([openingLines, ...children, closingLines]), multiLineElem]);
331
348
  }
332
349
 
350
+ /**
351
+ * TSRX: where the children an element renders are one text that the compiler
352
+ * prints as one literal (`{' a '}`, `wrapEdgeWhitespace` in `@tsrx/core`),
353
+ * that text's index and which of its edges have a space or tab (no line break
354
+ * in the whitespace there). The compiler does that for an element's only text
355
+ * with a space or tab at an edge, so a `<textarea>`, a `<title>` or a
356
+ * component that takes `children: string` gets one string (#1368). A comment
357
+ * container before or after the text (`{/* c *\/}`, or a TSRX `/* c *\/`)
358
+ * renders nothing, and the compiler leaves it out (`renderChildren`), unless it
359
+ * holds a tooling comment such as `@ts-expect-error`. Prettier would print such
360
+ * an edge as a `{" "}` child once the element breaks, which gives the element
361
+ * two or three children. `null` for any other element, and so for a fragment,
362
+ * whose only text the compiler splits, and for a text the compiler splits
363
+ * anyway, which Prettier prints as before. The compiler is asked with the
364
+ * reading of React, Preact and Hono; Solid and Vue keep the split for more
365
+ * texts. Besides the text, only comments printed on its line are laid out: no
366
+ * other text, and no TSRX `//` comment, which ends its line.
367
+ * @param {Node} node
368
+ * @returns {{ index: number, start: boolean, end: boolean } | null}
369
+ */
370
+ export function onlyTextEdges(node) {
371
+ if (node.type !== 'JSXElement') return null;
372
+ const children = /** @type {Node[]} */ (node.children);
373
+ const index = children.findIndex(
374
+ (/** @type {Node} */ child) => child.type === 'JSXText' && !isLayoutWhitespace(child),
375
+ );
376
+ if (index === -1) return null;
377
+ const text = children[index];
378
+ let comments = false;
379
+ for (const [i, child] of children.entries()) {
380
+ if (i === index || isLayoutWhitespace(child)) continue;
381
+ if (!isInlineCommentContainer(child)) return null;
382
+ comments = true;
383
+ }
384
+ // Beside a comment, a text whose words can't go on separate lines is left to
385
+ // Prettier: whether the compiler splits it depends on its line breaks, and
386
+ // Prettier's layout keeps the spaces beside a comment, so the next format
387
+ // would lay it out here.
388
+ if (comments && !wordsCanBreak(text)) return null;
389
+ const raw = getRaw(text);
390
+ // Counted from each end: a regular expression ending in `$` tries every start
391
+ // in a long run of whitespace.
392
+ let start = 0;
393
+ while (start < raw.length && isJsxWhitespaceCharacter(raw[start])) start++;
394
+ let end = raw.length;
395
+ while (end > start && isJsxWhitespaceCharacter(raw[end - 1])) end--;
396
+ const edges = {
397
+ index,
398
+ start: start > 0 && !raw.slice(0, start).includes('\n'),
399
+ end: end < raw.length && !raw.slice(end).includes('\n'),
400
+ };
401
+ if (start === end || !(edges.start || edges.end)) return null;
402
+ const compilerText = { type: 'JSXText', raw, value: text.value, metadata: { path: [] } };
403
+ const rendered = renderChildren(
404
+ /** @type {any} */ ({
405
+ type: 'JSXElement',
406
+ children: children.map((/** @type {Node} */ child) =>
407
+ child === text
408
+ ? compilerText
409
+ : child.type === 'JSXText'
410
+ ? child
411
+ : {
412
+ type: 'JSXExpressionContainer',
413
+ expression: {
414
+ type: 'JSXEmptyExpression',
415
+ innerComments: child.tsrxComment
416
+ ? [child.tsrxComment]
417
+ : (child.expression.comments ?? []),
418
+ },
419
+ },
420
+ ),
421
+ }),
422
+ );
423
+ if (rendered.length !== 1 || rendered[0] !== compilerText) return null;
424
+ const compiled = wrapEdgeWhitespace(/** @type {any[]} */ ([compilerText]), true);
425
+ return compiled.length === 1 && compiled[0].type === 'JSXExpressionContainer' ? edges : null;
426
+ }
427
+
428
+ /**
429
+ * TSRX: a child that holds only a comment printed on one line with what comes
430
+ * after it: `{/* c *\/}`, `{// c}` (whose `}` ends the line comment's line) or a
431
+ * TSRX `/* c *\/`. A TSRX `// c` ends its line, so the text can't follow it.
432
+ * @param {Node} child
433
+ * @returns {boolean}
434
+ */
435
+ function isInlineCommentContainer(child) {
436
+ return (
437
+ child.type === 'JSXExpressionContainer' &&
438
+ child.expression.type === 'JSXEmptyExpression' &&
439
+ child.tsrxComment?.type !== 'Line'
440
+ );
441
+ }
442
+
443
+ /** @param {string} character */
444
+ const isJsxWhitespaceCharacter = (character) =>
445
+ character === ' ' || character === '\n' || character === '\r' || character === '\t';
446
+
447
+ /**
448
+ * TSRX: an element's only rendered text, which the compiler prints as one
449
+ * literal (`onlyTextEdges`) and which stays one text. Its words fill lines as
450
+ * Prettier fills text, and a space at an edge stays one, beside its tag: the
451
+ * opening tag, the space and the first word start a line, and the last word,
452
+ * the space and the closing tag end one. A comment before the text prints
453
+ * after the opening tag, and one after it before the closing tag. An edge
454
+ * without a space breaks as Prettier breaks it. A text whose words can't go on
455
+ * separate lines (`wordsCanBreak`) stays on one line with its tags. Where the
456
+ * element fits on one line, it stays there, as Prettier prints it, except that
457
+ * several attributes don't break it.
458
+ * @param {AstPath<Node>} path
459
+ * @param {ParserOptions<Node>} options
460
+ * @param {Print} print
461
+ * @param {{ index: number, start: boolean, end: boolean }} edges
462
+ * @returns {Doc}
463
+ */
464
+ function printOnlyText(path, options, print, edges) {
465
+ const { node } = path;
466
+ const text = node.children[edges.index];
467
+ const openingLines = print('openingElement');
468
+ const closingLines = print('closingElement');
469
+ /** @type {Doc[]} */
470
+ const before = [];
471
+ /** @type {Doc[]} */
472
+ const after = [];
473
+ // The comments around the text; text that renders nothing (a line break and
474
+ // indentation) is left out, as the compiler leaves it out.
475
+ /** @type {Node | undefined} */
476
+ let firstAfter;
477
+ path.each((childPath, index) => {
478
+ if (index === edges.index || isLayoutWhitespace(childPath.node)) return;
479
+ if (index > edges.index) firstAfter ??= /** @type {Node} */ (childPath.node);
480
+ (index < edges.index ? before : after).push(print());
481
+ }, 'children');
482
+ const words = getRaw(text)
483
+ .split(/[ \n\r\t]+/u)
484
+ .filter((/** @type {string} */ word) => word !== '');
485
+ const breaks = wordsCanBreak(text);
486
+ // `print` isn't called on the text, so print the cursor around it, its
487
+ // edges too, as Prettier's `mainPrint` prints it around a node: around the
488
+ // text that holds it, after the text before it, and before the text after it.
489
+ const cursorOptions = /** @type {Record<string, any>} */ (options);
490
+ const [first, last] =
491
+ cursorOptions.cursorNode === text
492
+ ? [cursor, cursor]
493
+ : cursorOptions.nodeBeforeCursor === text
494
+ ? ['', cursor]
495
+ : cursorOptions.nodeAfterCursor === text
496
+ ? [cursor, '']
497
+ : ['', ''];
498
+ /** @type {Doc[]} */
499
+ const parts = breaks ? join(line, words) : [words.join(' ')];
500
+ parts.push([
501
+ /** @type {Doc} */ (parts.pop()),
502
+ edges.end ? [' ', last, ...after, closingLines] : last,
503
+ ]);
504
+ const edgeBreak = breaks ? softline : '';
505
+ return group([
506
+ openingLines,
507
+ indent([
508
+ ...before,
509
+ // A text right after a comment stays there: a TSRX `/* c */` before
510
+ // `// …` keeps the `//` text, which at the start of a line would be a
511
+ // comment.
512
+ edges.start ? [first, ' '] : before.length ? first : [edgeBreak, first],
513
+ fill(parts),
514
+ edges.end || after.length === 0
515
+ ? ''
516
+ : // A `{…}` comment after a text that ends in `@` stays on its own
517
+ // line: `@{` would start a code block.
518
+ [
519
+ words.at(-1)?.endsWith('@') && !firstAfter?.tsrxComment ? hardline : edgeBreak,
520
+ ...after,
521
+ ],
522
+ ]),
523
+ edges.end ? '' : [edgeBreak, closingLines],
524
+ ]);
525
+ }
526
+
527
+ /**
528
+ * TSRX: whether the compiler still prints the text as one literal when it
529
+ * spans lines. There it keeps the split where compilers trim a line's edge
530
+ * differently (`only_text_value` in `@tsrx/core`): for whitespace other than
531
+ * spaces, tabs and line breaks anywhere in the text, and for U+200B or a
532
+ * reference to whitespace (`&#32;`, `&nbsp;`) next to a line break. A text
533
+ * that has any of these stays on one line, where it compiles to one literal.
534
+ * A reference to a space, tab or line break shows as whitespace that the
535
+ * decoded text has and the text as written doesn't.
536
+ * @param {Node} text
537
+ * @returns {boolean}
538
+ */
539
+ function wordsCanBreak(text) {
540
+ if (/[^\S \t\n\r]|\u200b/u.test(text.value)) return false;
541
+ /** @param {string} value */
542
+ const whitespace = (value) => value.replaceAll('\r\n', '\n').replace(/[^ \t\n\r]/gu, '').length;
543
+ return whitespace(text.value) === whitespace(getRaw(text));
544
+ }
545
+
546
+ /**
547
+ * TSRX: whether the text a doc prints ends with `@`. TSRX reads `@{` in
548
+ * markup as the start of a code block, so a `{" "}` can't follow it.
549
+ * @param {Doc} doc
550
+ * @returns {boolean}
551
+ */
552
+ function endsWithAt(doc) {
553
+ while (Array.isArray(doc)) {
554
+ const last = doc.findLast((part) => part !== '');
555
+ if (last === undefined) return false;
556
+ doc = last;
557
+ }
558
+ return typeof doc === 'string' && doc.endsWith('@');
559
+ }
560
+
561
+ /**
562
+ * TSRX: whether an element's or fragment's text has an `@` before whitespace,
563
+ * where Prettier could print a `{" "}` (`printJsxElementInternal`).
564
+ * @param {Node} node
565
+ * @returns {boolean}
566
+ */
567
+ export function hasAtBeforeWhitespace(node) {
568
+ return node.children.some(
569
+ (/** @type {Node} */ child) => child.type === 'JSXText' && /@[ \n\r\t]/u.test(getRaw(child)),
570
+ );
571
+ }
572
+
333
573
  /**
334
574
  * JSX children are strange, mostly for two reasons:
335
575
  * 1. JSX reads newlines into string values, instead of skipping them like JS
@@ -417,7 +657,15 @@ function printJsxChildren(path, options, print, whitespace, isFacebookTranslatio
417
657
 
418
658
  if (endWhitespace !== undefined) {
419
659
  if (/\n/u.test(endWhitespace)) {
420
- pushLine(separatorWithWhitespace(isFacebookTranslationTag, prevPart, node, next));
660
+ // TSRX: the line break between an `@` and a `{` stays, where `@{`
661
+ // would start a code block.
662
+ pushLine(
663
+ endsWithAt(prevPart) &&
664
+ ((next?.type === 'JSXExpressionContainer' && !next.tsrxComment) ||
665
+ next?.type === 'JSXSpreadChild')
666
+ ? hardline
667
+ : separatorWithWhitespace(isFacebookTranslationTag, prevPart, node, next),
668
+ );
421
669
  } else {
422
670
  pushLine(whitespace);
423
671
  }
package/src/printer.js CHANGED
@@ -7,7 +7,7 @@ import { isLayoutWhitespace } from '@tsrx/core';
7
7
  import { builders, utils } from 'prettier/doc';
8
8
  import * as estreePlugin from 'prettier/plugins/estree';
9
9
  import * as standalone from 'prettier/standalone';
10
- import { printJsxElementInternal } from './jsx.js';
10
+ import { hasAtBeforeWhitespace, onlyTextEdges, printJsxElementInternal } from './jsx.js';
11
11
  import { TSRX_DIRECTIVES, isRawScriptElement } from './parse.js';
12
12
 
13
13
  const {
@@ -788,7 +788,14 @@ function printTsrx(path, options, print) {
788
788
  return printRawTextKept(path, options, print);
789
789
  }
790
790
  if (huggedCodeBlock(node) !== -1) return printHuggedCodeBlock(path, options, print);
791
- if (!node.tsrxPrintsChildren && !node.tsrxKeepParens) return null;
791
+ if (
792
+ !node.tsrxPrintsChildren &&
793
+ !node.tsrxKeepParens &&
794
+ !onlyTextEdges(node) &&
795
+ !hasAtBeforeWhitespace(node)
796
+ ) {
797
+ return null;
798
+ }
792
799
  return printElement(path, options, printJsxElementInternal(path, options, print));
793
800
 
794
801
  case 'JSXExpressionContainer':