/
embed.js
658 lines (578 loc) · 17.6 KB
/
embed.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
652
653
654
655
656
657
658
"use strict";
const {
builders: {
indent,
join,
line,
hardline,
softline,
literalline,
concat,
group,
dedentToRoot,
},
utils: { mapDoc, replaceNewlinesWithLiterallines },
} = require("../document");
const { isBlockComment, hasLeadingComment } = require("./comments");
function embed(path, print, textToDoc, options) {
const node = path.getValue();
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
switch (node.type) {
case "TemplateLiteral": {
const isCss = [
isStyledJsx,
isStyledComponents,
isCssProp,
isAngularComponentStyles,
].some((isIt) => isIt(path));
if (isCss) {
// Get full template literal with expressions replaced by placeholders
const rawQuasis = node.quasis.map((q) => q.value.raw);
let placeholderID = 0;
const text = rawQuasis.reduce((prevVal, currVal, idx) => {
return idx === 0
? currVal
: prevVal +
"@prettier-placeholder-" +
placeholderID++ +
"-id" +
currVal;
}, "");
const doc = textToDoc(
text,
{ parser: "scss" },
{ stripTrailingHardline: true }
);
return transformCssDoc(doc, path, print);
}
/*
* react-relay and graphql-tag
* graphql`...`
* graphql.experimental`...`
* gql`...`
*
* This intentionally excludes Relay Classic tags, as Prettier does not
* support Relay Classic formatting.
*/
if (isGraphQL(path)) {
const expressionDocs = node.expressions
? path.map(print, "expressions")
: [];
const numQuasis = node.quasis.length;
if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
return "``";
}
const parts = [];
for (let i = 0; i < numQuasis; i++) {
const templateElement = node.quasis[i];
const isFirst = i === 0;
const isLast = i === numQuasis - 1;
const text = templateElement.value.cooked;
// Bail out if any of the quasis have an invalid escape sequence
// (which would make the `cooked` value be `null` or `undefined`)
if (typeof text !== "string") {
return null;
}
const lines = text.split("\n");
const numLines = lines.length;
const expressionDoc = expressionDocs[i];
const startsWithBlankLine =
numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
const endsWithBlankLine =
numLines > 2 &&
lines[numLines - 1].trim() === "" &&
lines[numLines - 2].trim() === "";
const commentsAndWhitespaceOnly = lines.every((line) =>
/^\s*(?:#[^\n\r]*)?$/.test(line)
);
// Bail out if an interpolation occurs within a comment.
if (!isLast && /#[^\n\r]*$/.test(lines[numLines - 1])) {
return null;
}
let doc = null;
if (commentsAndWhitespaceOnly) {
doc = printGraphqlComments(lines);
} else {
doc = textToDoc(
text,
{ parser: "graphql" },
{ stripTrailingHardline: true }
);
}
if (doc) {
doc = escapeTemplateCharacters(doc, false);
if (!isFirst && startsWithBlankLine) {
parts.push("");
}
parts.push(doc);
if (!isLast && endsWithBlankLine) {
parts.push("");
}
} else if (!isFirst && !isLast && startsWithBlankLine) {
parts.push("");
}
if (expressionDoc) {
parts.push(concat(["${", expressionDoc, "}"]));
}
}
return concat([
"`",
indent(concat([hardline, join(hardline, parts)])),
hardline,
"`",
]);
}
const htmlParser = isHtml(path)
? "html"
: isAngularComponentTemplate(path)
? "angular"
: undefined;
if (htmlParser) {
return printHtmlTemplateLiteral(
path,
print,
textToDoc,
htmlParser,
options
);
}
break;
}
case "TemplateElement": {
/**
* md`...`
* markdown`...`
*/
if (
parentParent &&
parentParent.type === "TaggedTemplateExpression" &&
parent.quasis.length === 1 &&
parentParent.tag.type === "Identifier" &&
(parentParent.tag.name === "md" || parentParent.tag.name === "markdown")
) {
const text = parent.quasis[0].value.raw.replace(
/((?:\\\\)*)\\`/g,
(_, backslashes) => "\\".repeat(backslashes.length / 2) + "`"
);
const indentation = getIndentation(text);
const hasIndent = indentation !== "";
return concat([
hasIndent
? indent(
concat([
softline,
printMarkdown(
text.replace(new RegExp(`^${indentation}`, "gm"), "")
),
])
)
: concat([literalline, dedentToRoot(printMarkdown(text))]),
softline,
]);
}
break;
}
}
function printMarkdown(text) {
const doc = textToDoc(
text,
{ parser: "markdown", __inJsTemplate: true },
{ stripTrailingHardline: true }
);
return escapeTemplateCharacters(doc, true);
}
}
function getIndentation(str) {
const firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
}
function uncook(cookedValue) {
return cookedValue.replace(/([\\`]|\${)/g, "\\$1");
}
function escapeTemplateCharacters(doc, raw) {
return mapDoc(doc, (currentDoc) => {
if (!currentDoc.parts) {
return currentDoc;
}
const parts = currentDoc.parts.map((part) => {
if (typeof part === "string") {
return raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part);
}
return part;
});
return { ...currentDoc, parts };
});
}
function transformCssDoc(quasisDoc, path, print) {
const parentNode = path.getValue();
const isEmpty =
parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
if (isEmpty) {
return "``";
}
const expressionDocs = parentNode.expressions
? path.map(print, "expressions")
: [];
const newDoc = replacePlaceholders(quasisDoc, expressionDocs);
/* istanbul ignore if */
if (!newDoc) {
throw new Error("Couldn't insert all the expressions");
}
return concat(["`", indent(concat([hardline, newDoc])), softline, "`"]);
}
// Search all the placeholders in the quasisDoc tree
// and replace them with the expression docs one by one
// returns a new doc with all the placeholders replaced,
// or null if it couldn't replace any expression
function replacePlaceholders(quasisDoc, expressionDocs) {
if (!expressionDocs || !expressionDocs.length) {
return quasisDoc;
}
let replaceCounter = 0;
const newDoc = mapDoc(quasisDoc, (doc) => {
if (!doc || !doc.parts || !doc.parts.length) {
return doc;
}
let { parts } = doc;
const atIndex = parts.indexOf("@");
const placeholderIndex = atIndex + 1;
if (
atIndex > -1 &&
typeof parts[placeholderIndex] === "string" &&
parts[placeholderIndex].startsWith("prettier-placeholder")
) {
// If placeholder is split, join it
const at = parts[atIndex];
const placeholder = parts[placeholderIndex];
const rest = parts.slice(placeholderIndex + 1);
parts = parts
.slice(0, atIndex)
.concat([at + placeholder])
.concat(rest);
}
const replacedParts = [];
parts.forEach((part) => {
if (typeof part !== "string" || !part.includes("@prettier-placeholder")) {
replacedParts.push(part);
return;
}
// When we have multiple placeholders in one line, like:
// ${Child}${Child2}:not(:first-child)
part.split(/@prettier-placeholder-(\d+)-id/).forEach((component, idx) => {
// The placeholder is always at odd indices
if (idx % 2 === 0) {
replacedParts.push(replaceNewlinesWithLiterallines(component));
return;
}
// The component will always be a number at odd index
replacedParts.push("${", expressionDocs[component], "}");
replaceCounter++;
});
});
return { ...doc, parts: replacedParts };
});
return expressionDocs.length === replaceCounter ? newDoc : null;
}
function printGraphqlComments(lines) {
const parts = [];
let seenComment = false;
lines
.map((textLine) => textLine.trim())
.forEach((textLine, i, array) => {
// Lines are either whitespace only, or a comment (with potential whitespace
// around it). Drop whitespace-only lines.
if (textLine === "") {
return;
}
if (array[i - 1] === "" && seenComment) {
// If a non-first comment is preceded by a blank (whitespace only) line,
// add in a blank line.
parts.push(concat([hardline, textLine]));
} else {
parts.push(textLine);
}
seenComment = true;
});
// If `lines` was whitespace only, return `null`.
return parts.length === 0 ? null : join(hardline, parts);
}
/**
* Template literal in these contexts:
* <style jsx>{`div{color:red}`}</style>
* css``
* css.global``
* css.resolve``
*/
function isStyledJsx(path) {
const node = path.getValue();
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
return (
(parentParent &&
node.quasis &&
parent.type === "JSXExpressionContainer" &&
parentParent.type === "JSXElement" &&
parentParent.openingElement.name.name === "style" &&
parentParent.openingElement.attributes.some(
(attribute) => attribute.name.name === "jsx"
)) ||
(parent &&
parent.type === "TaggedTemplateExpression" &&
parent.tag.type === "Identifier" &&
parent.tag.name === "css") ||
(parent &&
parent.type === "TaggedTemplateExpression" &&
parent.tag.type === "MemberExpression" &&
parent.tag.object.name === "css" &&
(parent.tag.property.name === "global" ||
parent.tag.property.name === "resolve"))
);
}
/**
* Angular Components can have:
* - Inline HTML template
* - Inline CSS styles
*
* ...which are both within template literals somewhere
* inside of the Component decorator factory.
*
* E.g.
* @Component({
* template: `<div>...</div>`,
* styles: [`h1 { color: blue; }`]
* })
*/
function isAngularComponentStyles(path) {
return path.match(
(node) => node.type === "TemplateLiteral",
(node, name) => node.type === "ArrayExpression" && name === "elements",
(node, name) =>
(node.type === "Property" || node.type === "ObjectProperty") &&
node.key.type === "Identifier" &&
node.key.name === "styles" &&
name === "value",
...angularComponentObjectExpressionPredicates
);
}
function isAngularComponentTemplate(path) {
return path.match(
(node) => node.type === "TemplateLiteral",
(node, name) =>
(node.type === "Property" || node.type === "ObjectProperty") &&
node.key.type === "Identifier" &&
node.key.name === "template" &&
name === "value",
...angularComponentObjectExpressionPredicates
);
}
const angularComponentObjectExpressionPredicates = [
(node, name) => node.type === "ObjectExpression" && name === "properties",
(node, name) =>
node.type === "CallExpression" &&
node.callee.type === "Identifier" &&
node.callee.name === "Component" &&
name === "arguments",
(node, name) => node.type === "Decorator" && name === "expression",
];
/**
* styled-components template literals
*/
function isStyledComponents(path) {
const parent = path.getParentNode();
if (!parent || parent.type !== "TaggedTemplateExpression") {
return false;
}
const { tag } = parent;
switch (tag.type) {
case "MemberExpression":
return (
// styled.foo``
isStyledIdentifier(tag.object) ||
// Component.extend``
isStyledExtend(tag)
);
case "CallExpression":
return (
// styled(Component)``
isStyledIdentifier(tag.callee) ||
(tag.callee.type === "MemberExpression" &&
((tag.callee.object.type === "MemberExpression" &&
// styled.foo.attrs({})``
(isStyledIdentifier(tag.callee.object.object) ||
// Component.extend.attrs({})``
isStyledExtend(tag.callee.object))) ||
// styled(Component).attrs({})``
(tag.callee.object.type === "CallExpression" &&
isStyledIdentifier(tag.callee.object.callee))))
);
case "Identifier":
// css``
return tag.name === "css";
default:
return false;
}
}
/**
* JSX element with CSS prop
*/
function isCssProp(path) {
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
return (
parentParent &&
parent.type === "JSXExpressionContainer" &&
parentParent.type === "JSXAttribute" &&
parentParent.name.type === "JSXIdentifier" &&
parentParent.name.name === "css"
);
}
function isStyledIdentifier(node) {
return node.type === "Identifier" && node.name === "styled";
}
function isStyledExtend(node) {
return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
}
/*
* react-relay and graphql-tag
* graphql`...`
* graphql.experimental`...`
* gql`...`
* GraphQL comment block
*
* This intentionally excludes Relay Classic tags, as Prettier does not
* support Relay Classic formatting.
*/
function isGraphQL(path) {
const node = path.getValue();
const parent = path.getParentNode();
return (
hasLanguageComment(node, "GraphQL") ||
(parent &&
((parent.type === "TaggedTemplateExpression" &&
((parent.tag.type === "MemberExpression" &&
parent.tag.object.name === "graphql" &&
parent.tag.property.name === "experimental") ||
(parent.tag.type === "Identifier" &&
(parent.tag.name === "gql" || parent.tag.name === "graphql")))) ||
(parent.type === "CallExpression" &&
parent.callee.type === "Identifier" &&
parent.callee.name === "graphql")))
);
}
function hasLanguageComment(node, languageName) {
// This checks for a leading comment that is exactly `/* GraphQL */`
// In order to be in line with other implementations of this comment tag
// we will not trim the comment value and we will expect exactly one space on
// either side of the GraphQL string
// Also see ./clean.js
return hasLeadingComment(
node,
(comment) =>
isBlockComment(comment) && comment.value === ` ${languageName} `
);
}
/**
* - html`...`
* - HTML comment block
*/
function isHtml(path) {
return (
hasLanguageComment(path.getValue(), "HTML") ||
path.match(
(node) => node.type === "TemplateLiteral",
(node, name) =>
node.type === "TaggedTemplateExpression" &&
node.tag.type === "Identifier" &&
node.tag.name === "html" &&
name === "quasi"
)
);
}
// The counter is needed to distinguish nested embeds.
let htmlTemplateLiteralCounter = 0;
function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) {
const node = path.getValue();
const counter = htmlTemplateLiteralCounter;
htmlTemplateLiteralCounter = (htmlTemplateLiteralCounter + 1) >>> 0;
const composePlaceholder = (index) =>
`PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`;
const text = node.quasis
.map((quasi, index, quasis) =>
index === quasis.length - 1
? quasi.value.cooked
: quasi.value.cooked + composePlaceholder(index)
)
.join("");
const expressionDocs = path.map(print, "expressions");
if (expressionDocs.length === 0 && text.trim().length === 0) {
return "``";
}
const placeholderRegex = new RegExp(composePlaceholder("(\\d+)"), "g");
let topLevelCount = 0;
const contentDoc = mapDoc(
textToDoc(
text,
{
parser,
__onHtmlRoot(root) {
topLevelCount = root.children.length;
},
},
{ stripTrailingHardline: true }
),
(doc) => {
if (typeof doc !== "string") {
return doc;
}
const parts = [];
const components = doc.split(placeholderRegex);
for (let i = 0; i < components.length; i++) {
let component = components[i];
if (i % 2 === 0) {
if (component) {
component = uncook(component);
if (options.embeddedInHtml) {
component = component.replace(/<\/(script)\b/gi, "<\\/$1");
}
parts.push(component);
}
continue;
}
const placeholderIndex = +component;
parts.push(
concat(["${", group(expressionDocs[placeholderIndex]), "}"])
);
}
return concat(parts);
}
);
const leadingWhitespace = /^\s/.test(text) ? " " : "";
const trailingWhitespace = /\s$/.test(text) ? " " : "";
const linebreak =
options.htmlWhitespaceSensitivity === "ignore"
? hardline
: leadingWhitespace && trailingWhitespace
? line
: null;
if (linebreak) {
return group(
concat([
"`",
indent(concat([linebreak, group(contentDoc)])),
linebreak,
"`",
])
);
}
return group(
concat([
"`",
leadingWhitespace,
topLevelCount > 1 ? indent(group(contentDoc)) : group(contentDoc),
trailingWhitespace,
"`",
])
);
}
module.exports = embed;