-
Notifications
You must be signed in to change notification settings - Fork 6
/
parse.ts
148 lines (130 loc) · 4.76 KB
/
parse.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
import {Parser, Root, Document, ProcessOptions, Input} from 'postcss';
import postcssParse from 'postcss/lib/parse';
import {parse as babelParse} from '@babel/parser';
import {default as traverse, NodePath} from '@babel/traverse';
import {TaggedTemplateExpression} from '@babel/types';
import {createPlaceholder} from './util.js';
import {locationCorrectionWalker} from './locationCorrection.js';
/**
* Parses CSS from within tagged template literals in a JavaScript document
* @param {string} source Source code to parse
* @param {*=} opts Options to pass to PostCSS' parser when parsing
* @return {Root|Document}
*/
export const parse: Parser<Root | Document> = (
source: string | {toString(): string},
opts?: Pick<ProcessOptions, 'map' | 'from'>
): Root | Document => {
const doc = new Document();
const sourceAsString = source.toString();
const ast = babelParse(sourceAsString, {
sourceType: 'unambiguous',
plugins: ['typescript', ['decorators', {decoratorsBeforeExport: true}]],
ranges: true
});
const extractedStyles = new Set<TaggedTemplateExpression>();
traverse(ast, {
TaggedTemplateExpression: (
path: NodePath<TaggedTemplateExpression>
): void => {
if (path.node.tag.type === 'Identifier' && path.node.tag.name === 'css') {
extractedStyles.add(path.node);
}
}
});
let currentOffset = 0;
for (const node of extractedStyles) {
if (!node.quasi.range) {
continue;
}
const startIndex = node.quasi.range[0] + 1;
const expressionStrings: string[] = [];
let styleText = '';
for (let i = 0; i < node.quasi.quasis.length; i++) {
const template = node.quasi.quasis[i];
const expr = node.quasi.expressions[i];
const nextTemplate = node.quasi.quasis[i + 1];
if (template) {
styleText += template.value.raw;
if (expr && nextTemplate && nextTemplate.range && template.range) {
const exprText = sourceAsString.slice(
template.range[1],
nextTemplate.range[0]
);
styleText += createPlaceholder(i);
expressionStrings.push(exprText);
}
}
}
const baseIndentation = (node.quasi.loc?.end.column ?? 1) - 1;
const sourceLines = styleText.split('\n');
const baseIndentations = new Map<number, number>();
const indentationPattern = new RegExp(`^[ \\t]{${baseIndentation}}`);
const emptyLinePattern = /^[ \\t\r]*$/;
const deindentedLines: string[] = [];
const prefixOffsets = {lines: 0, offset: 0};
if (sourceLines[0] !== undefined && emptyLinePattern.test(sourceLines[0])) {
prefixOffsets.lines = 1;
prefixOffsets.offset = sourceLines[0].length + 1;
sourceLines.shift();
}
for (let i = 0; i < sourceLines.length; i++) {
const sourceLine = sourceLines[i];
if (sourceLine !== undefined) {
if (indentationPattern.test(sourceLine)) {
deindentedLines.push(sourceLine.replace(indentationPattern, ''));
baseIndentations.set(i + 1, baseIndentation);
// Roots don't have an end line, so we can't look this up so easily
// later on. Having a special '-1' key helps here.
if (i === sourceLines.length - 1) {
baseIndentations.set(-1, baseIndentation);
}
} else {
deindentedLines.push(sourceLine);
}
}
}
const deindentedStyleText = deindentedLines.join('\n');
const root = postcssParse(deindentedStyleText, {
...opts,
map: false
}) as Root;
root.raws['litPrefixOffsets'] = prefixOffsets;
root.raws['litTemplateExpressions'] = expressionStrings;
root.raws['litBaseIndentations'] = baseIndentations;
// TODO (43081j): remove this if stylelint/stylelint#5767 ever gets fixed,
// or they drop the indentation rule. Their indentation rule depends on
// `beforeStart` existing as they unsafely try to call `endsWith` on it.
if (!root.raws['beforeStart']) {
root.raws['beforeStart'] = '';
}
root.raws.codeBefore = sourceAsString.slice(
currentOffset,
startIndex + prefixOffsets.offset
);
root.parent = doc;
// TODO (43081j): stylelint relies on this existing, really unsure why.
// it could just access root.parent to get the document...
(root as Root & {document: Document}).document = doc;
const walker = locationCorrectionWalker(node);
walker(root);
root.walk(walker);
doc.nodes.push(root);
currentOffset = node.quasi.range[1] - 1;
}
if (doc.nodes.length > 0) {
const last = doc.nodes[doc.nodes.length - 1];
if (last) {
last.raws.codeAfter = sourceAsString.slice(currentOffset);
}
}
doc.source = {
input: new Input(sourceAsString, opts),
start: {
line: 1,
column: 1,
offset: 0
}
};
return doc;
};