-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathembed.ts
216 lines (184 loc) · 6.25 KB
/
embed.ts
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
import { Doc, doc, FastPath, ParserOptions } from 'prettier';
import { getText } from './lib/getText';
import { snippedTagContentAttribute } from './lib/snipTagContent';
import { PrintFn } from './print';
import {
getAttributeTextValue,
getLeadingComment,
isIgnoreDirective,
isNodeSupportedLanguage,
} from './print/node-helpers';
import { Node } from './print/nodes';
const {
builders: { concat, hardline, group, indent, literalline },
utils: { removeLines },
} = doc;
export function embed(
path: FastPath,
print: PrintFn,
textToDoc: (text: string, options: object) => Doc,
options: ParserOptions,
): Doc | null {
const node: Node = path.getNode();
if (node.isJS) {
try {
const embeddedOptions: any = {
parser: expressionParser,
};
if (node.forceSingleQuote) {
embeddedOptions.singleQuote = true;
}
const docs = textToDoc(forceIntoExpression(getText(node, options)), embeddedOptions);
return node.forceSingleLine ? removeLines(docs) : docs;
} catch (e) {
return getText(node, options);
}
}
const embedType = (tag: string, parser: 'typescript' | 'css', isTopLevel: boolean) =>
embedTag(
tag,
path,
(content) => formatBodyContent(content, parser, textToDoc, options),
print,
isTopLevel,
);
const embedScript = (isTopLevel: boolean) => embedType('script', 'typescript', isTopLevel);
const embedStyle = (isTopLevel: boolean) => embedType('style', 'css', isTopLevel);
switch (node.type) {
case 'Script':
return embedScript(true);
case 'Style':
return embedStyle(true);
case 'Element': {
if (node.name === 'script') {
return embedScript(false);
} else if (node.name === 'style') {
return embedStyle(false);
}
}
}
return null;
}
function forceIntoExpression(statement: string) {
// note the trailing newline: if the statement ends in a // comment,
// we can't add the closing bracket right afterwards
return `(${statement}\n)`;
}
function expressionParser(text: string, parsers: any, options: any) {
const ast = parsers.babel(text, parsers, options);
return { ...ast, program: ast.program.body[0].expression };
}
function skipBlank(docs: Doc[]): number {
for (let i = docs.length - 1; i >= 0; i--) {
const doc = docs[i];
if (typeof doc !== 'string') {
if (doc.type === 'break-parent') {
continue;
}
}
return i;
}
return -1;
}
function nukeLastLine(doc: Doc): Doc {
if (typeof doc === 'string') {
return doc;
}
switch (doc.type) {
case 'concat':
const end = skipBlank(doc.parts);
if (end > -1) {
return concat([
...doc.parts.slice(0, end),
nukeLastLine(doc.parts[end]),
...doc.parts.slice(end + 1),
]);
}
break;
case 'line':
return '';
}
return doc;
}
function preformattedBody(str: string): Doc {
const firstNewline = /^[\t\f\r ]*\n/;
const lastNewline = /\n[\t\f\r ]*$/;
// If we do not start with a new line prettier might try to break the opening tag
// to keep it together with the string. Use a literal line to skip indentation.
return concat([literalline, str.replace(firstNewline, '').replace(lastNewline, ''), hardline]);
}
function getSnippedContent(node: Node) {
const encodedContent = getAttributeTextValue(snippedTagContentAttribute, node);
if (encodedContent) {
return Buffer.from(encodedContent, 'base64').toString('utf-8');
} else {
return '';
}
}
function formatBodyContent(
content: string,
parser: 'typescript' | 'css',
textToDoc: (text: string, options: object) => Doc,
options: ParserOptions,
) {
const indentContent = options.svelteIndentScriptAndStyle;
try {
const indentIfDesired = (doc: Doc) => (indentContent ? indent(doc) : doc);
return concat([
indentIfDesired(concat([hardline, nukeLastLine(textToDoc(content, { parser }))])),
hardline,
]);
} catch (error) {
if (process.env.PRETTIER_DEBUG) {
throw error;
}
// We will wind up here if there is a syntax error in the embedded code. If we throw an error,
// prettier will try to print the node with the printer. That will fail with a hard-to-interpret
// error message (e.g. "Unsupported node type", referring to `<script>`).
// Therefore, fall back on just returning the unformatted text.
console.error(error);
return preformattedBody(content);
}
}
function embedTag(
tag: string,
path: FastPath,
formatBodyContent: (content: string) => Doc,
print: PrintFn,
isTopLevel: boolean,
) {
const node: Node = path.getNode();
const content = getSnippedContent(node);
const previousComment = getLeadingComment(path);
const body: Doc =
isNodeSupportedLanguage(node) && !isIgnoreDirective(previousComment)
? content.trim() !== ''
? formatBodyContent(content)
: content === ''
? ''
: hardline
: preformattedBody(content);
const attributes = concat(
path.map(
(childPath) =>
childPath.getNode().name !== snippedTagContentAttribute
? childPath.call(print)
: '',
'attributes',
),
);
let result: Doc = group(
concat(['<', tag, indent(group(attributes)), '>', body, '</', tag, '>']),
);
if (isTopLevel) {
// top level embedded nodes have been moved from their normal position in the
// node tree. if there is a comment referring to it, it must be recreated at
// the new position.
if (previousComment) {
result = concat(['<!--', previousComment.data, '-->', hardline, result, hardline]);
} else {
result = concat([result, hardline]);
}
}
return result;
}