-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
printer-glimmer.js
651 lines (544 loc) · 17 KB
/
printer-glimmer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
"use strict";
const {
builders: { concat, group, hardline, ifBreak, indent, join, line, softline },
} = require("../document");
const { locStart, locEnd } = require("./loc");
const clean = require("./clean");
const {
getNextNode,
getPreviousNode,
hasPrettierIgnore,
isNextNodeOfSomeType,
isNodeOfSomeType,
isParentOfSomeType,
isPreviousNodeOfSomeType,
isVoid,
isWhitespaceNode,
} = require("./utils");
// Formatter based on @glimmerjs/syntax's built-in test formatter:
// https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
function print(path, options, print) {
const n = path.getValue();
/* istanbul ignore if*/
if (!n) {
return "";
}
if (hasPrettierIgnore(path)) {
return options.originalText.slice(locStart(n), locEnd(n));
}
switch (n.type) {
case "Block":
case "Program":
case "Template": {
return group(concat(path.map(print, "body")));
}
case "ElementNode": {
// TODO: make it whitespace sensitive
const bim = isNextNodeOfSomeType(path, ["ElementNode"]) ? hardline : "";
if (isVoid(n)) {
return concat([group(printStartingTag(path, print)), bim]);
}
const isWhitespaceOnly = n.children.every((n) => isWhitespaceNode(n));
return concat([
group(printStartingTag(path, print)),
group(
concat([
isWhitespaceOnly ? "" : indent(printChildren(path, options, print)),
n.children.length ? hardline : "",
concat(["</", n.tag, ">"]),
])
),
bim,
]);
}
case "BlockStatement": {
const pp = path.getParentNode(1);
const isElseIf =
pp &&
pp.inverse &&
pp.inverse.body.length === 1 &&
pp.inverse.body[0] === n &&
pp.inverse.body[0].path.parts[0] === "if";
if (isElseIf) {
return concat([
printElseIfBlock(path, print),
printProgram(path, print),
printInverse(path, print),
]);
}
return concat([
printOpenBlock(path, print),
group(
concat([
printProgram(path, print),
printInverse(path, print),
printCloseBlock(path, print),
])
),
]);
}
case "ElementModifierStatement": {
return group(
concat(["{{", printPathAndParams(path, print), softline, "}}"])
);
}
case "MustacheStatement": {
const isParentOfSpecifiedTypes = isParentOfSomeType(path, [
"AttrNode",
"ConcatStatement",
]);
const isChildOfElementNodeAndDoesNotHaveParams =
isParentOfSomeType(path, ["ElementNode"]) &&
doesNotHaveHashParams(n) &&
doesNotHavePositionalParams(n);
const shouldBreakOpeningMustache =
isParentOfSpecifiedTypes || isChildOfElementNodeAndDoesNotHaveParams;
return group(
concat([
printOpeningMustache(n),
shouldBreakOpeningMustache ? indent(softline) : "",
printPathAndParams(path, print),
softline,
printClosingMustache(n),
])
);
}
case "SubExpression": {
return group(
concat([
"(",
printSubExpressionPathAndParams(path, print),
softline,
")",
])
);
}
case "AttrNode": {
const isText = n.value.type === "TextNode";
const isEmptyText = isText && n.value.chars === "";
// If the text is empty and the value's loc start and end offsets are the
// same, there is no value for this AttrNode and it should be printed
// without the `=""`. Example: `<img data-test>` -> `<img data-test>`
if (isEmptyText && locStart(n.value) === locEnd(n.value)) {
return concat([n.name]);
}
const value = path.call(print, "value");
const quotedValue = isText
? printStringLiteral(value.parts.join(), options)
: value;
return concat([n.name, "=", quotedValue]);
}
case "ConcatStatement": {
const quote = options.singleQuote ? "'" : '"';
return concat([
quote,
...path.map((partPath) => print(partPath), "parts"),
quote,
]);
}
case "Hash": {
return concat([join(line, path.map(print, "pairs"))]);
}
case "HashPair": {
return concat([n.key, "=", path.call(print, "value")]);
}
case "TextNode": {
const maxLineBreaksToPreserve = 2;
const isFirstElement = !getPreviousNode(path);
const isLastElement = !getNextNode(path);
const isWhitespaceOnly = !/\S/.test(n.chars);
const lineBreaksCount = countNewLines(n.chars);
let leadingLineBreaksCount = countLeadingNewLines(n.chars);
let trailingLineBreaksCount = countTrailingNewLines(n.chars);
if (
(isFirstElement || isLastElement) &&
isWhitespaceOnly &&
isParentOfSomeType(path, ["Block", "ElementNode", "Template"])
) {
return "";
}
if (isWhitespaceOnly && lineBreaksCount) {
leadingLineBreaksCount = Math.min(
lineBreaksCount,
maxLineBreaksToPreserve
);
trailingLineBreaksCount = 0;
} else {
if (isNextNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) {
trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
}
if (isPreviousNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) {
leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
}
}
const inAttrNode = path.stack.includes("attributes");
if (inAttrNode) {
// TODO: format style and srcset attributes
// and cleanup concat that is not necessary
if (!isInAttributeOfName(path, "class")) {
return concat([n.chars]);
}
let leadingSpace = "";
let trailingSpace = "";
if (isParentOfSomeType(path, ["ConcatStatement"])) {
if (isPreviousNodeOfSomeType(path, ["MustacheStatement"])) {
leadingSpace = " ";
}
if (isNextNodeOfSomeType(path, ["MustacheStatement"])) {
trailingSpace = " ";
}
}
return concat([
...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve),
n.chars.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace),
...generateHardlines(
trailingLineBreaksCount,
maxLineBreaksToPreserve
),
]);
}
let leadingSpace = "";
let trailingSpace = "";
if (
trailingLineBreaksCount === 0 &&
isNextNodeOfSomeType(path, ["MustacheStatement"])
) {
trailingSpace = " ";
}
if (
leadingLineBreaksCount === 0 &&
isPreviousNodeOfSomeType(path, ["MustacheStatement"])
) {
leadingSpace = " ";
}
if (isFirstElement) {
leadingLineBreaksCount = 0;
leadingSpace = "";
}
if (isLastElement) {
trailingLineBreaksCount = 0;
trailingSpace = "";
}
let text = n.chars;
/* if `{{my-component}}` (or any text starting with a mustache)
* makes it to the TextNode,
* it means it was escaped,
* so let's print it escaped, ie.; `\{{my-component}}` */
if (text.startsWith("{{") && text.includes("}}")) {
text = "\\" + text;
}
return concat([
...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve),
text.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace),
...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve),
]);
}
case "MustacheCommentStatement": {
const dashes = n.value.includes("}}") ? "--" : "";
return concat(["{{!", dashes, n.value, dashes, "}}"]);
}
case "PathExpression": {
return n.original;
}
case "BooleanLiteral": {
return String(n.value);
}
case "CommentStatement": {
return concat(["<!--", n.value, "-->"]);
}
case "StringLiteral": {
return printStringLiteral(n.value, options);
}
case "NumberLiteral": {
return String(n.value);
}
case "UndefinedLiteral": {
return "undefined";
}
case "NullLiteral": {
return "null";
}
/* istanbul ignore next */
default:
throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
}
}
/* ElementNode print helpers */
function printStartingTag(path, print) {
const node = path.getValue();
return concat([
"<",
node.tag,
printAttributesLike(path, print),
printBlockParams(node),
printStartingTagEndMarker(node),
]);
}
function printAttributesLike(path, print) {
const node = path.getValue();
return indent(
concat([
node.attributes.length ? line : "",
join(line, path.map(print, "attributes")),
node.modifiers.length ? line : "",
join(line, path.map(print, "modifiers")),
node.comments.length ? line : "",
join(line, path.map(print, "comments")),
])
);
}
function printChildren(path, options, print) {
return concat(
path.map((childPath, childIndex) => {
if (childIndex === 0) {
return concat([softline, print(childPath, options, print)]);
}
return print(childPath, options, print);
}, "children")
);
}
function printStartingTagEndMarker(node) {
if (isVoid(node)) {
return ifBreak(concat([softline, "/>"]), concat([" />", softline]));
}
return ifBreak(concat([softline, ">"]), ">");
}
/* MustacheStatement print helpers */
function printOpeningMustache(node) {
const mustache = node.escaped === false ? "{{{" : "{{";
const strip = node.strip && node.strip.open ? "~" : "";
return concat([mustache, strip]);
}
function printClosingMustache(node) {
const mustache = node.escaped === false ? "}}}" : "}}";
const strip = node.strip && node.strip.close ? "~" : "";
return concat([strip, mustache]);
}
/* BlockStatement print helpers */
function printOpeningBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.openStrip.open ? "~" : "";
return concat([opening, strip, "#"]);
}
function printOpeningBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.openStrip.close ? "~" : "";
return concat([strip, closing]);
}
function printClosingBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.closeStrip.open ? "~" : "";
return concat([opening, strip, "/"]);
}
function printClosingBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.closeStrip.close ? "~" : "";
return concat([strip, closing]);
}
function printInverseBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.inverseStrip.open ? "~" : "";
return concat([opening, strip]);
}
function printInverseBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.inverseStrip.close ? "~" : "";
return concat([strip, closing]);
}
function printOpenBlock(path, print) {
const node = path.getValue();
return group(
concat([
printOpeningBlockOpeningMustache(node),
printPathAndParams(path, print),
printBlockParams(node.program),
softline,
printOpeningBlockClosingMustache(node),
])
);
}
function printElseBlock(node) {
return concat([
hardline,
printInverseBlockOpeningMustache(node),
"else",
printInverseBlockClosingMustache(node),
]);
}
function printElseIfBlock(path, print) {
const parentNode = path.getParentNode(1);
return concat([
printInverseBlockOpeningMustache(parentNode),
"else ",
printPathAndParams(path, print),
printInverseBlockClosingMustache(parentNode),
]);
}
function printCloseBlock(path, print) {
const node = path.getValue();
return concat([
blockStatementHasOnlyWhitespaceInProgram(node) ? softline : hardline,
printClosingBlockOpeningMustache(node),
path.call(print, "path"),
printClosingBlockClosingMustache(node),
]);
}
function blockStatementHasOnlyWhitespaceInProgram(node) {
return (
isNodeOfSomeType(node, ["BlockStatement"]) &&
node.program.body.every((n) => isWhitespaceNode(n))
);
}
function blockStatementHasElseIf(node) {
return (
blockStatementHasElse(node) &&
node.inverse.body.length === 1 &&
isNodeOfSomeType(node.inverse.body[0], ["BlockStatement"]) &&
node.inverse.body[0].path.parts[0] === "if"
);
}
function blockStatementHasElse(node) {
return isNodeOfSomeType(node, ["BlockStatement"]) && node.inverse;
}
function printProgram(path, print) {
const node = path.getValue();
if (blockStatementHasOnlyWhitespaceInProgram(node)) {
return "";
}
const program = path.call(print, "program");
return indent(concat([hardline, program]));
}
function printInverse(path, print) {
const node = path.getValue();
const inverse = path.call(print, "inverse");
const parts = concat([hardline, inverse]);
if (blockStatementHasElseIf(node)) {
return parts;
}
if (blockStatementHasElse(node)) {
return concat([printElseBlock(node), indent(parts)]);
}
return "";
}
/* TextNode print helpers */
function isInAttributeOfName(path, type) {
return (
(isParentOfSomeType(path, ["AttrNode"]) &&
path.getParentNode().name.toLowerCase() === type) ||
(isParentOfSomeType(path, ["ConcatStatement"]) &&
path.getParentNode(1).name.toLowerCase() === type)
);
}
function countNewLines(string) {
/* istanbul ignore next */
string = typeof string === "string" ? string : "";
return string.split("\n").length - 1;
}
function countLeadingNewLines(string) {
/* istanbul ignore next */
string = typeof string === "string" ? string : "";
const newLines = (string.match(/^([^\S\n\r]*[\n\r])+/g) || [])[0] || "";
return countNewLines(newLines);
}
function countTrailingNewLines(string) {
/* istanbul ignore next */
string = typeof string === "string" ? string : "";
const newLines = (string.match(/([\n\r][^\S\n\r]*)+$/g) || [])[0] || "";
return countNewLines(newLines);
}
function generateHardlines(number = 0, max = 0) {
return new Array(Math.min(number, max)).fill(hardline);
}
/* StringLiteral print helpers */
/**
* Prints a string literal with the correct surrounding quotes based on
* `options.singleQuote` and the number of escaped quotes contained in
* the string literal. This function is the glimmer equivalent of `printString`
* in `common/util`, but has differences because of the way escaped characters
* are treated in hbs string literals.
* @param {string} stringLiteral - the string literal value
* @param {object} options - the prettier options object
*/
function printStringLiteral(stringLiteral, options) {
const double = { quote: '"', regex: /"/g };
const single = { quote: "'", regex: /'/g };
const preferred = options.singleQuote ? single : double;
const alternate = preferred === single ? double : single;
let shouldUseAlternateQuote = false;
// If `stringLiteral` contains at least one of the quote preferred for
// enclosing the string, we might want to enclose with the alternate quote
// instead, to minimize the number of escaped quotes.
if (
stringLiteral.includes(preferred.quote) ||
stringLiteral.includes(alternate.quote)
) {
const numPreferredQuotes = (stringLiteral.match(preferred.regex) || [])
.length;
const numAlternateQuotes = (stringLiteral.match(alternate.regex) || [])
.length;
shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
}
const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
const escapedStringLiteral = stringLiteral.replace(
enclosingQuote.regex,
`\\${enclosingQuote.quote}`
);
return concat([
enclosingQuote.quote,
escapedStringLiteral,
enclosingQuote.quote,
]);
}
/* SubExpression print helpers */
function printSubExpressionPathAndParams(path, print) {
const p = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return p;
}
return indent(concat([p, line, group(params)]));
}
/* misc. print helpers */
function printPathAndParams(path, print) {
const p = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return p;
}
return indent(group(concat([p, line, params])));
}
function printPath(path, print) {
return path.call(print, "path");
}
function printParams(path, print) {
const node = path.getValue();
const parts = [];
if (node.params.length) {
const params = path.map(print, "params");
parts.push(...params);
}
if (node.hash && node.hash.pairs.length > 0) {
const hash = path.call(print, "hash");
parts.push(hash);
}
if (!parts.length) {
return "";
}
return join(line, parts);
}
function printBlockParams(node) {
if (!node || !node.blockParams.length) {
return "";
}
return concat([" as |", node.blockParams.join(" "), "|"]);
}
function doesNotHaveHashParams(node) {
return node.hash.pairs.length === 0;
}
function doesNotHavePositionalParams(node) {
return node.params.length === 0;
}
module.exports = {
print,
massageAstNode: clean,
};