-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathparse-css.ts
More file actions
293 lines (268 loc) · 7.95 KB
/
parse-css.ts
File metadata and controls
293 lines (268 loc) · 7.95 KB
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
import { camelCase } from "change-case";
import * as csstree from "css-tree";
import { StyleValue, type StyleProperty } from "@webstudio-is/css-engine";
import { parseCssValue as parseCssValueLonghand } from "./parse-css-value";
import { expandShorthands } from "./shorthands";
export type ParsedStyleDecl = {
breakpoint?: string;
selector: string;
state?: string;
property: StyleProperty;
value: StyleValue;
};
/**
* Store prefixed properties without change
* and convert to camel case only unprefixed properties
* @todo stop converting to camel case and use hyphenated format
*/
const normalizePropertyName = (property: string) => {
// these are manually added with pascal case
// convert unprefixed used by webflow version into prefixed one
if (property === "-webkit-font-smoothing" || property === "font-smoothing") {
return "WebkitFontSmoothing";
}
if (property === "-moz-osx-font-smoothing") {
return "MozOsxFontSmoothing";
}
// webflow use unprefixed version
if (property === "tap-highlight-color") {
return "-webkit-tap-highlight-color";
}
if (property.startsWith("-")) {
return property;
}
return camelCase(property);
};
// @todo we don't parse correctly most of them if not all
const prefixedProperties = [
"-webkit-box-orient",
"-webkit-line-clamp",
"-webkit-font-smoothing",
"-moz-osx-font-smoothing",
"-webkit-tap-highlight-color",
"-webkit-overflow-scrolling",
];
const prefixes = ["webkit", "moz", "ms", "o"];
const prefixRegex = new RegExp(`^-(${prefixes.join("|")})-`);
const unprefixProperty = (property: string) => {
if (prefixedProperties.includes(property)) {
return property;
}
return property.replace(prefixRegex, "");
};
const parseCssValue = (
property: string,
value: string,
{ customProperties }: { customProperties: boolean }
): Map<StyleProperty, StyleValue> => {
const expanded = new Map(expandShorthands([[property, value]]));
const final = new Map();
for (const [property, value] of expanded) {
if (value === "") {
// Keep the browser behavior when property is defined with an empty value e.g. `color:;`
// It may override some existing value and effectively set it to "unset";
final.set(property, { type: "keyword", value: "unset" });
continue;
}
// @todo https://github.com/webstudio-is/webstudio/issues/3399
if (customProperties === false && value.startsWith("var(")) {
final.set(property, { type: "keyword", value: "unset" });
continue;
}
final.set(
property,
parseCssValueLonghand(
normalizePropertyName(property) as StyleProperty,
value
)
);
}
return final;
};
const cssTreeTryParse = (input: string) => {
try {
const ast = csstree.parse(input);
return ast;
} catch {
return;
}
};
type Selector = {
name: string;
state?: string;
};
type ParserOptions = {
customProperties?: boolean;
};
export const parseCss = (css: string, options: ParserOptions = {}) => {
const customProperties = options.customProperties ?? false;
const ast = cssTreeTryParse(css);
const styles = new Map<string, ParsedStyleDecl>();
if (ast === undefined) {
return [];
}
csstree.walk(ast, function (node) {
if (node.type !== "Declaration" || this.rule?.prelude.type === undefined) {
return;
}
if (this.atrule && this.atrule.name !== "media") {
return;
}
const supportedMediaFeatures = ["min-width", "max-width"];
const supportedUnits = ["px"];
let breakpoint: undefined | string;
let invalidBreakpoint = false;
if (this.atrule?.prelude?.type === "AtrulePrelude") {
csstree.walk(this.atrule.prelude, {
enter: (node, item, list) => {
if (node.type === "Identifier") {
if (
node.name === "screen" ||
node.name === "all" ||
node.name === "and"
) {
list.remove(item);
}
// prevent saving print styles
if (node.name === "print") {
invalidBreakpoint = true;
}
}
if (
node.type === "MediaFeature" &&
supportedMediaFeatures.includes(node.name) === false
) {
invalidBreakpoint = true;
}
if (
node.type === "Dimension" &&
supportedUnits.includes(node.unit) === false
) {
invalidBreakpoint = true;
}
},
leave: (node) => {
// complex media queries are not supported yet
if (node.type === "MediaQuery" && node.children.size > 1) {
invalidBreakpoint = true;
}
``;
},
});
const generated = csstree.generate(this.atrule.prelude);
if (generated) {
breakpoint = generated;
}
}
if (invalidBreakpoint || this.rule.prelude.type !== "SelectorList") {
return;
}
const selectors: Selector[] = [];
for (const node of this.rule.prelude.children) {
if (node.type !== "Selector") {
continue;
}
let selector: Selector | undefined = undefined;
for (const childNode of node.children) {
let name: string = "";
let state: string | undefined;
switch (childNode.type) {
case "TypeSelector":
name = childNode.name;
break;
case "ClassSelector":
name = `.${childNode.name}`;
break;
case "AttributeSelector":
name = csstree.generate(childNode);
break;
case "PseudoClassSelector": {
// First pseudo selector is not a state but an element selector, e.g. :root
if (selector) {
state = `:${childNode.name}`;
} else {
name = `:${childNode.name}`;
}
break;
}
case "PseudoElementSelector":
state = `::${childNode.name}`;
break;
case "Combinator":
// " " vs " > "
name =
childNode.name === " " ? childNode.name : ` ${childNode.name} `;
break;
}
if (selector) {
selector.name += name;
if (state) {
selector.state = state;
}
} else {
selector = { name, state };
}
}
if (selector) {
selectors.push(selector);
selector = undefined;
}
}
const stringValue = csstree.generate(node.value);
const parsedCss = parseCssValue(
unprefixProperty(node.property),
stringValue,
{ customProperties }
);
for (const { name: selector, state } of selectors) {
for (const [property, value] of parsedCss) {
const styleDecl: ParsedStyleDecl = {
selector,
property: normalizePropertyName(
unprefixProperty(property)
) as StyleProperty,
value,
};
if (breakpoint) {
styleDecl.breakpoint = breakpoint;
}
if (state) {
styleDecl.state = state;
}
// deduplicate styles within selector and state by using map
styles.set(`${breakpoint}:${selector}:${state}:${property}`, styleDecl);
}
}
});
return Array.from(styles.values());
};
type ParsedBreakpoint = {
minWidth?: number;
maxWidth?: number;
};
export const parseMediaQuery = (
mediaQuery: string
): undefined | ParsedBreakpoint => {
const ast = csstree.parse(mediaQuery, { context: "mediaQuery" });
let property: undefined | "minWidth" | "maxWidth";
let value: undefined | number;
csstree.walk(ast, (node) => {
if (node.type === "MediaFeature") {
if (node.name === "min-width") {
property = "minWidth";
}
if (node.name === "max-width") {
property = "maxWidth";
}
}
if (node.type === "Dimension" && node.unit === "px") {
value = Number(node.value);
}
});
if (property === undefined || value === undefined) {
return;
}
return {
[property]: value,
};
};