@tsrx/prettier-plugin 0.4.11 → 0.5.0

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/src/jsx.js ADDED
@@ -0,0 +1,533 @@
1
+ /**
2
+ * Prettier's layout of a JSX element's children, for the elements whose
3
+ * children include TSRX comments (`// …` and `/* … *\/` between children,
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.
8
+ *
9
+ * `printJsxElementInternal` and `printJsxChildren` are copied from Prettier
10
+ * 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
13
+ * whitespace (or at the start of a line, or right after a tag), and it runs to
14
+ * the end of its line. So a line comment ends its line, keeps whitespace
15
+ * 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
+ *
19
+ * @import { AstPath, Doc, ParserOptions } from 'prettier'
20
+ * @import { Node } from './parse.js'
21
+ */
22
+
23
+ import { builders, utils } from 'prettier/doc';
24
+
25
+ const {
26
+ breakParent,
27
+ conditionalGroup,
28
+ cursor,
29
+ fill,
30
+ group,
31
+ hardline,
32
+ ifBreak,
33
+ indent,
34
+ line,
35
+ softline,
36
+ } = builders;
37
+ const { findInDoc, willBreak } = utils;
38
+
39
+ /**
40
+ * @typedef {(selector?: string | number | Array<string | number> | AstPath) => Doc} Print
41
+ */
42
+
43
+ // Prettier's `jsxWhitespace`: only these characters are whitespace in JSX.
44
+ const jsxWhitespace = {
45
+ /**
46
+ * @param {string} text
47
+ * @param {boolean} [captureWhitespace]
48
+ */
49
+ split: (text, captureWhitespace = false) =>
50
+ text.split(captureWhitespace ? /([ \n\r\t]+)/u : /[ \n\r\t]+/u),
51
+ /** @param {string} text */
52
+ trim: (text) => text.replace(/^[ \n\r\t]+|[ \n\r\t]+$/gu, ''),
53
+ /** @param {string} text */
54
+ hasNonWhitespaceCharacter: (text) => /[^ \n\r\t]/u.test(text),
55
+ };
56
+
57
+ /** @param {Node} node */
58
+ const getRaw = (node) => node.extra?.raw ?? node.raw;
59
+
60
+ /** @param {Node} node */
61
+ const isJsxElement = (node) => node.type === 'JSXElement' || node.type === 'JSXFragment';
62
+
63
+ /**
64
+ * Meaningful if it contains non-whitespace characters, or it contains
65
+ * whitespace without a new line.
66
+ * @param {Node} node
67
+ */
68
+ function isMeaningfulJsxText(node) {
69
+ return (
70
+ node.type === 'JSXText' &&
71
+ (jsxWhitespace.hasNonWhitespaceCharacter(getRaw(node)) || !/\n/u.test(getRaw(node)))
72
+ );
73
+ }
74
+
75
+ /**
76
+ * An element without children, or with only whitespace that has a line break.
77
+ * @param {Node} node
78
+ */
79
+ function isEmptyJsxElement(node) {
80
+ if (node.children.length === 0) return true;
81
+ if (node.children.length > 1) return false;
82
+ const child = node.children[0];
83
+ return child.type === 'JSXText' && !isMeaningfulJsxText(child);
84
+ }
85
+
86
+ /**
87
+ * Detect an expression node representing `{" "}`.
88
+ * @param {Node} node
89
+ */
90
+ function isJsxWhitespaceExpression(node) {
91
+ return (
92
+ node.type === 'JSXExpressionContainer' &&
93
+ node.expression.type === 'Literal' &&
94
+ node.expression.value === ' ' &&
95
+ !node.expression.comments?.length
96
+ );
97
+ }
98
+
99
+ /**
100
+ * Prettier's `isEmptyDoc`: no text, and no line or other printed part.
101
+ * `findInDoc` stops at the first result that isn't `undefined`, so an empty
102
+ * string must not return one.
103
+ * @param {Doc} doc
104
+ */
105
+ function isEmptyDoc(doc) {
106
+ return !findInDoc(
107
+ doc,
108
+ (part) =>
109
+ (typeof part === 'string'
110
+ ? part !== ''
111
+ : ['trim', 'line-suffix-boundary', 'line', 'break-parent'].includes(
112
+ /** @type {{ type: string }} */ (part).type,
113
+ )) || undefined,
114
+ false,
115
+ );
116
+ }
117
+
118
+ /**
119
+ * TSRX: the line break around a line comment. Inside `{…}` it would be part of
120
+ * the child; bare, it's a separator that Prettier's clean-up of the children,
121
+ * which removes a line break before JSX whitespace, must leave in place.
122
+ */
123
+ const lineCommentBreak = [hardline];
124
+
125
+ /** @param {Doc} doc */
126
+ const isEmptyStringOrAnyLine = (doc) =>
127
+ doc === '' || doc === line || doc === hardline || doc === softline || doc === lineCommentBreak;
128
+
129
+ /**
130
+ * @param {AstPath<Node>} path
131
+ * @param {ParserOptions<Node>} options
132
+ * @param {Print} print
133
+ * @returns {Doc}
134
+ */
135
+ export function printJsxElementInternal(path, options, print) {
136
+ const { node } = path;
137
+
138
+ if (node.type === 'JSXElement' && isEmptyJsxElement(node)) {
139
+ return [print('openingElement'), print('closingElement')];
140
+ }
141
+
142
+ const openingLines =
143
+ node.type === 'JSXElement' ? print('openingElement') : print('openingFragment');
144
+ const closingLines =
145
+ node.type === 'JSXElement' ? print('closingElement') : print('closingFragment');
146
+
147
+ if (
148
+ node.children.length === 1 &&
149
+ node.children[0].type === 'JSXExpressionContainer' &&
150
+ (node.children[0].expression.type === 'TemplateLiteral' ||
151
+ node.children[0].expression.type === 'TaggedTemplateExpression')
152
+ ) {
153
+ return [openingLines, ...path.map(print, 'children'), closingLines];
154
+ }
155
+
156
+ // Convert `{" "}` to text nodes containing a space.
157
+ // This makes it easy to turn them into `jsxWhitespace` which
158
+ // can then print as either a space or `{" "}` when breaking.
159
+ node.children = node.children.map((/** @type {Node} */ child) => {
160
+ if (isJsxWhitespaceExpression(child)) {
161
+ return { type: 'JSXText', value: ' ', raw: ' ' };
162
+ }
163
+ return child;
164
+ });
165
+
166
+ const containsTag = node.children.some(isJsxElement);
167
+ const containsMultipleExpressions =
168
+ node.children.filter((/** @type {Node} */ child) => child.type === 'JSXExpressionContainer')
169
+ .length > 1;
170
+ const containsMultipleAttributes =
171
+ node.type === 'JSXElement' && node.openingElement.attributes.length > 1;
172
+
173
+ // Record any breaks. Should never go from true to false, only false to true.
174
+ let forcedBreak =
175
+ willBreak(openingLines) ||
176
+ containsTag ||
177
+ containsMultipleAttributes ||
178
+ containsMultipleExpressions;
179
+
180
+ const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
181
+ const whitespace = ifBreak([rawJsxWhitespace, softline], ' ');
182
+
183
+ const isFacebookTranslationTag = node.openingElement?.name?.name === 'fbt';
184
+
185
+ const children = printJsxChildren(path, options, print, whitespace, isFacebookTranslationTag);
186
+
187
+ const containsText = node.children.some(isMeaningfulJsxText);
188
+
189
+ // We can end up we multiple whitespace elements with empty string
190
+ // content between them.
191
+ // We need to remove empty whitespace and softlines before JSX whitespace
192
+ // to get the correct output.
193
+ for (let i = children.length - 2; i >= 0; i--) {
194
+ const isPairOfEmptyStrings = children[i] === '' && children[i + 1] === '';
195
+ const isPairOfHardlines =
196
+ children[i] === hardline && children[i + 1] === '' && children[i + 2] === hardline;
197
+ const isLineFollowedByJsxWhitespace =
198
+ (children[i] === softline || children[i] === hardline) &&
199
+ children[i + 1] === '' &&
200
+ children[i + 2] === whitespace;
201
+ const isJsxWhitespaceFollowedByLine =
202
+ children[i] === whitespace &&
203
+ children[i + 1] === '' &&
204
+ (children[i + 2] === softline || children[i + 2] === hardline);
205
+ const isDoubleJsxWhitespace =
206
+ children[i] === whitespace && children[i + 1] === '' && children[i + 2] === whitespace;
207
+ const isPairOfHardOrSoftLines =
208
+ (children[i] === softline && children[i + 1] === '' && children[i + 2] === hardline) ||
209
+ (children[i] === hardline && children[i + 1] === '' && children[i + 2] === softline);
210
+
211
+ // TSRX: a line break after a line comment's, as after `{// …}`.
212
+ const isLineCommentBreakFollowedByHardline =
213
+ children[i] === lineCommentBreak && children[i + 1] === '' && children[i + 2] === hardline;
214
+ if (isLineCommentBreakFollowedByHardline && containsText) {
215
+ children.splice(i + 1, 2);
216
+ continue;
217
+ }
218
+
219
+ if (
220
+ (isPairOfHardlines && containsText) ||
221
+ isPairOfEmptyStrings ||
222
+ isLineFollowedByJsxWhitespace ||
223
+ isDoubleJsxWhitespace ||
224
+ isPairOfHardOrSoftLines
225
+ ) {
226
+ children.splice(i, 2);
227
+ } else if (isJsxWhitespaceFollowedByLine) {
228
+ children.splice(i + 1, 2);
229
+ }
230
+ }
231
+
232
+ // Trim trailing lines (or empty strings)
233
+ while (children.length > 0 && isEmptyStringOrAnyLine(/** @type {Doc} */ (children.at(-1)))) {
234
+ children.pop();
235
+ }
236
+
237
+ // Trim leading lines (or empty strings)
238
+ while (
239
+ children.length > 1 &&
240
+ isEmptyStringOrAnyLine(children[0]) &&
241
+ isEmptyStringOrAnyLine(children[1])
242
+ ) {
243
+ children.shift();
244
+ children.shift();
245
+ }
246
+
247
+ // Tweak how we format children if outputting this element over multiple
248
+ // lines. Also detect whether we will force this element to output over
249
+ // multiple lines. Line-like docs stay at odd indexes (the rule of `fill()`).
250
+ /** @type {Doc[]} */
251
+ const multilineChildren = [''];
252
+ for (const [i, child] of children.entries()) {
253
+ // There are a number of situations where we need to ensure we display
254
+ // whitespace as `{" "}` when outputting this element over multiple lines.
255
+ if (child === whitespace) {
256
+ if (i === 1 && isEmptyDoc(children[i - 1])) {
257
+ if (children.length === 2) {
258
+ // Solitary whitespace
259
+ multilineChildren.push([/** @type {Doc} */ (multilineChildren.pop()), rawJsxWhitespace]);
260
+ continue;
261
+ }
262
+ // Leading whitespace
263
+ multilineChildren.push([rawJsxWhitespace, hardline], '');
264
+ continue;
265
+ }
266
+
267
+ if (i === children.length - 1) {
268
+ // Trailing whitespace
269
+ multilineChildren.push([/** @type {Doc} */ (multilineChildren.pop()), rawJsxWhitespace]);
270
+ continue;
271
+ }
272
+
273
+ if (
274
+ children[i - 1] === '' &&
275
+ (children[i - 2] === hardline || children[i - 2] === lineCommentBreak)
276
+ ) {
277
+ // Whitespace after line break
278
+ multilineChildren.push([/** @type {Doc} */ (multilineChildren.pop()), rawJsxWhitespace]);
279
+ continue;
280
+ }
281
+ }
282
+
283
+ if (i % 2 === 0) {
284
+ // non-line-like
285
+ multilineChildren.push([/** @type {Doc} */ (multilineChildren.pop()), child]);
286
+ } else {
287
+ // line-like
288
+ multilineChildren.push(child, '');
289
+ }
290
+
291
+ if (willBreak(child)) {
292
+ forcedBreak = true;
293
+ }
294
+ }
295
+
296
+ // If there is text we use `fill` to fit as much onto each line as possible.
297
+ // When there is no text (just tags and expressions) we use `group`
298
+ // to output each on a separate line.
299
+ /** @type {Doc} */
300
+ let content = containsText
301
+ ? fill(multilineChildren)
302
+ : group(multilineChildren, { shouldBreak: true });
303
+
304
+ // `printJsxChildren` doesn't call `print` on `JSXText`, so print the cursor
305
+ // around the children when it is inside one.
306
+ const cursorOptions = /** @type {Record<string, any>} */ (options);
307
+ if (
308
+ cursorOptions.cursorNode?.type === 'JSXText' &&
309
+ node.children.includes(cursorOptions.cursorNode)
310
+ ) {
311
+ content = [cursor, content, cursor];
312
+ } else if (
313
+ cursorOptions.nodeBeforeCursor?.type === 'JSXText' &&
314
+ node.children.includes(cursorOptions.nodeBeforeCursor)
315
+ ) {
316
+ content = [cursor, content];
317
+ } else if (
318
+ cursorOptions.nodeAfterCursor?.type === 'JSXText' &&
319
+ node.children.includes(cursorOptions.nodeAfterCursor)
320
+ ) {
321
+ content = [content, cursor];
322
+ }
323
+
324
+ const multiLineElem = group([openingLines, indent([hardline, content]), hardline, closingLines]);
325
+
326
+ if (forcedBreak) {
327
+ return multiLineElem;
328
+ }
329
+
330
+ return conditionalGroup([group([openingLines, ...children, closingLines]), multiLineElem]);
331
+ }
332
+
333
+ /**
334
+ * JSX children are strange, mostly for two reasons:
335
+ * 1. JSX reads newlines into string values, instead of skipping them like JS
336
+ * 2. up to one whitespace between elements within a line is significant,
337
+ * but not between lines.
338
+ *
339
+ * Leading, trailing, and lone whitespace all need to turn themselves into the
340
+ * rather ugly `{' '}` when breaking.
341
+ *
342
+ * Returns a Doc array that satisfies the rule of `fill()`.
343
+ * @param {AstPath<Node>} path
344
+ * @param {ParserOptions<Node>} options
345
+ * @param {Print} print
346
+ * @param {Doc} whitespace
347
+ * @param {boolean} isFacebookTranslationTag
348
+ * @returns {Doc[]}
349
+ */
350
+ function printJsxChildren(path, options, print, whitespace, isFacebookTranslationTag) {
351
+ /** @type {Doc} */
352
+ let prevPart = '';
353
+ /** @type {Doc[]} */
354
+ const parts = [prevPart];
355
+ // To ensure rule of `fill()`, we use `push()` and `pushLine()` instead of `parts.push()`.
356
+ /** @param {Doc} doc */
357
+ function push(doc) {
358
+ prevPart = doc;
359
+ parts.push([/** @type {Doc} */ (parts.pop()), doc]);
360
+ }
361
+ /** @param {Doc} doc */
362
+ function pushLine(doc) {
363
+ if (doc === '') {
364
+ return;
365
+ }
366
+ prevPart = doc;
367
+ parts.push(doc, '');
368
+ }
369
+
370
+ // TSRX: whether the child before is a line comment, which ends its line.
371
+ let afterLineComment = false;
372
+
373
+ path.each((childPath) => {
374
+ const { node, index, siblings, next } = /** @type {AstPath<Node>} */ (childPath);
375
+ const followsLineComment = afterLineComment;
376
+ afterLineComment = node.tsrxComment?.type === 'Line';
377
+ if (node.type === 'JSXText') {
378
+ const text = getRaw(node);
379
+
380
+ // Contains a non-whitespace character
381
+ if (isMeaningfulJsxText(node)) {
382
+ const words = jsxWhitespace.split(text, /* captureWhitespace */ true);
383
+
384
+ // Starts with whitespace
385
+ if (words[0] === '') {
386
+ words.shift();
387
+ if (/\n/u.test(words[0])) {
388
+ // TSRX: after a line comment, its line break separates them.
389
+ if (!followsLineComment) {
390
+ pushLine(separatorWithWhitespace(isFacebookTranslationTag, words[1], node, next));
391
+ }
392
+ } else {
393
+ pushLine(whitespace);
394
+ }
395
+ words.shift();
396
+ }
397
+
398
+ let endWhitespace;
399
+ // Ends with whitespace
400
+ if (words.at(-1) === '') {
401
+ words.pop();
402
+ endWhitespace = words.pop();
403
+ }
404
+
405
+ // This was whitespace only without a new line.
406
+ if (words.length === 0) {
407
+ return;
408
+ }
409
+
410
+ for (const [i, word] of words.entries()) {
411
+ if (i % 2 === 1) {
412
+ pushLine(line);
413
+ } else {
414
+ push(word);
415
+ }
416
+ }
417
+
418
+ if (endWhitespace !== undefined) {
419
+ if (/\n/u.test(endWhitespace)) {
420
+ pushLine(separatorWithWhitespace(isFacebookTranslationTag, prevPart, node, next));
421
+ } else {
422
+ pushLine(whitespace);
423
+ }
424
+ } else {
425
+ pushLine(separatorNoWhitespace(isFacebookTranslationTag, prevPart, node, next));
426
+ }
427
+ } else if (/\n/u.test(text)) {
428
+ // Keep (up to one) blank line between tags/expressions/text.
429
+ // Note: We don't keep blank lines between text elements.
430
+ if (/** @type {RegExpMatchArray} */ (text.match(/\n/gu)).length > 1) {
431
+ pushLine(hardline);
432
+ }
433
+ } else {
434
+ pushLine(whitespace);
435
+ }
436
+ } else {
437
+ const printedChild = print();
438
+ const lineComment = node.tsrxComment?.type === 'Line';
439
+ // TSRX: a line comment after text or a comment needs whitespace before
440
+ // it: touching them, it would be text. Where Prettier would leave no
441
+ // space (a line break in the source), it starts its own line.
442
+ if (
443
+ lineComment &&
444
+ followsText(/** @type {Node[]} */ (siblings), /** @type {number} */ (index)) &&
445
+ !(parts.length > 1 && parts.at(-1) === '' && parts.at(-2) === whitespace)
446
+ ) {
447
+ if (parts.length > 1 && parts.at(-1) === '') parts[parts.length - 2] = lineCommentBreak;
448
+ else pushLine(lineCommentBreak);
449
+ }
450
+ push(printedChild);
451
+
452
+ const directlyFollowedByMeaningfulText = next && isMeaningfulJsxText(next);
453
+ if (lineComment) {
454
+ // TSRX: a line comment ends its line.
455
+ pushLine(lineCommentBreak);
456
+ } else if (directlyFollowedByMeaningfulText) {
457
+ const trimmed = jsxWhitespace.trim(getRaw(next));
458
+ const [firstWord] = jsxWhitespace.split(trimmed);
459
+ // TSRX: text that starts with `//` right after a block comment is
460
+ // text only there; at the start of a line, it would be a comment.
461
+ if (!(node.tsrxComment && getRaw(next).startsWith('//'))) {
462
+ pushLine(separatorNoWhitespace(isFacebookTranslationTag, firstWord, node, next));
463
+ }
464
+ } else {
465
+ pushLine(hardline);
466
+ }
467
+ }
468
+ }, 'children');
469
+
470
+ return parts;
471
+ }
472
+
473
+ /**
474
+ * TSRX: whether text or a comment, rather than an element or an expression,
475
+ * comes before the child at `index`, past any whitespace, which Prettier may put
476
+ * on one line. A line comment there would be text.
477
+ * @param {Node[]} siblings
478
+ * @param {number} index
479
+ * @returns {boolean}
480
+ */
481
+ function followsText(siblings, index) {
482
+ for (let i = index - 1; i >= 0; i--) {
483
+ const sibling = siblings[i];
484
+ if (sibling.tsrxComment) return true;
485
+ if (sibling.type !== 'JSXText') return false;
486
+ if (jsxWhitespace.hasNonWhitespaceCharacter(getRaw(sibling))) return true;
487
+ }
488
+ return false;
489
+ }
490
+
491
+ /**
492
+ * @param {boolean} isFacebookTranslationTag
493
+ * @param {Doc} child
494
+ * @param {Node} childNode
495
+ * @param {Node | null | undefined} nextNode
496
+ * @returns {Doc}
497
+ */
498
+ function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
499
+ if (isFacebookTranslationTag) {
500
+ return '';
501
+ }
502
+
503
+ if (
504
+ (childNode.type === 'JSXElement' && !childNode.closingElement) ||
505
+ (nextNode?.type === 'JSXElement' && !nextNode.closingElement)
506
+ ) {
507
+ return /** @type {string} */ (child).length === 1 ? softline : hardline;
508
+ }
509
+
510
+ return softline;
511
+ }
512
+
513
+ /**
514
+ * @param {boolean} isFacebookTranslationTag
515
+ * @param {Doc} child
516
+ * @param {Node} childNode
517
+ * @param {Node | null | undefined} nextNode
518
+ * @returns {Doc}
519
+ */
520
+ function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
521
+ if (isFacebookTranslationTag) {
522
+ return hardline;
523
+ }
524
+
525
+ if (/** @type {string} */ (child).length === 1) {
526
+ return (childNode.type === 'JSXElement' && !childNode.closingElement) ||
527
+ (nextNode?.type === 'JSXElement' && !nextNode.closingElement)
528
+ ? hardline
529
+ : softline;
530
+ }
531
+
532
+ return hardline;
533
+ }