-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathcompiler.ts
More file actions
331 lines (289 loc) · 10.2 KB
/
compiler.ts
File metadata and controls
331 lines (289 loc) · 10.2 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
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
/* eslint-disable */
import { inspect } from "node:util";
import { debug } from "debug";
import {
Features,
transform as lightningcss,
type ContainerRule,
type MediaQuery as CSSMediaQuery,
type CustomAtRules,
type MediaRule,
type Rule,
type Visitor,
} from "lightningcss";
import { maybeMutateReactNativeOptions, parsePropAtRule } from "./atRules";
import type { CompilerOptions, ContainerQuery } from "./compiler.types";
import { parseContainerCondition } from "./container-query";
import { parseDeclaration, round } from "./declarations";
import { extractKeyFrames } from "./keyframes";
import { parseMediaQuery } from "./media-query";
import { StylesheetBuilder } from "./stylesheet";
import { supportsConditionValid } from "./supports";
const defaultLogger = debug("react-native-css:compiler");
/**
* Converts a CSS file to a collection of style declarations that can be used with the StyleSheet API
*
* @param code - The CSS file contents
* @param options - Compiler options
* @returns A `ReactNativeCssStyleSheet` that can be passed to `StyleSheet.register` or used with a custom runtime
*/
export function compile(code: Buffer | string, options: CompilerOptions = {}) {
const { logger = defaultLogger } = options;
const isLoggerEnabled =
"enabled" in logger ? logger.enabled : Boolean(logger);
const features = Object.assign({}, options.features);
if (options.selectorPrefix && options.selectorPrefix.startsWith(".")) {
options.selectorPrefix = options.selectorPrefix.slice(1);
}
logger(`Features ${JSON.stringify(features)}`);
if (process.env.NODE_ENV !== "production") {
if (defaultLogger.enabled) {
defaultLogger(code.toString());
}
}
const builder = new StylesheetBuilder(options);
logger(`Lightningcss first pass`);
/**
* Use the lightningcss library to traverse the CSS AST and extract style declarations and animations
*
* devongovett on Aug 20, 2023
* > calc simplification happens during the initial parse phase, which is before custom visitors run. Currently there is not an additional simplification pass done after transforms, resulting in the output you see here.
* https://github.com/parcel-bundler/lightningcss/issues/554#issuecomment-1685143494
*
* Due to the above issue, we run lightningcss twice
*/
const { code: firstPass } = lightningcss({
code: typeof code === "string" ? new TextEncoder().encode(code) : code,
include: Features.DoublePositionGradients | Features.ColorFunction,
exclude: Features.VendorPrefixes,
visitor: {
Length(length) {
if (length.unit !== "rem" || options.inlineRem === false) {
return length;
}
return {
unit: "px",
value: round(length.value * (options.inlineRem ?? 14)),
};
},
},
filename: options.filename ?? "style.css",
projectRoot: options.projectRoot ?? process.cwd(),
});
if (isLoggerEnabled) {
const MAX_LOG_SIZE = 100 * 1024; // 100KB
if (firstPass.length <= MAX_LOG_SIZE) {
logger(firstPass.toString());
} else {
logger(
`firstPass buffer too large to log in full (${firstPass.length} bytes). Preview: ` +
firstPass.subarray(0, 1024).toString() +
"...",
);
}
}
logger(`Lightningcss second pass`);
const customAtRules: CustomAtRules = {
"react-native": {
body: "declaration-list",
},
};
const visitor: Visitor<typeof customAtRules> = {
Rule(rule) {
maybeMutateReactNativeOptions(rule, builder);
return rule;
},
StyleSheetExit(sheet) {
if (isLoggerEnabled) {
logger(`Found ${sheet.rules.length} rules to process`);
logger(
inspect(sheet.rules, { depth: null, colors: true, compact: false }),
);
}
for (const rule of sheet.rules) {
// Extract the style declarations and animations from the current rule
extractRule(rule, builder);
// We have processed this rule, so now delete it from the AST
}
logger(`Exiting lightningcss`);
return sheet;
},
};
lightningcss({
code: firstPass,
visitor,
filename: options.filename ?? "style.css",
projectRoot: options.projectRoot ?? process.cwd(),
});
return {
stylesheet: () => builder.getNativeStyleSheet(),
warnings: () => builder.getWarnings(),
};
}
/**
* Extracts style declarations and animations from a given CSS rule, based on its type.
*/
function extractRule(rule: Rule, builder: StylesheetBuilder) {
// Check the rule's type to determine which extraction function to call
switch (rule.type) {
case "keyframes": {
// If the rule is a keyframe animation, extract it with the `extractKeyFrames` function
extractKeyFrames(rule.value, builder);
break;
}
case "container": {
// If the rule is a container, extract it with the `extractedContainer` function
extractContainer(rule.value, builder);
break;
}
case "media": {
// If the rule is a media query, extract it with the `extractMedia` function
extractMedia(rule.value, builder);
break;
}
case "nested-declarations": {
const value = rule.value;
const declarationBlock = value.declarations;
if (declarationBlock) {
if (declarationBlock.declarations?.length) {
builder.newNestedRule();
for (const declaration of declarationBlock.declarations) {
parseDeclaration(declaration, builder);
}
builder.applyRuleToSelectors();
}
if (declarationBlock.importantDeclarations?.length) {
builder.newNestedRule({ important: true });
for (const declaration of declarationBlock.importantDeclarations) {
parseDeclaration(declaration, builder);
}
builder.applyRuleToSelectors();
}
}
break;
}
case "style": {
const value = rule.value;
const declarationBlock = value.declarations;
const mapping = parsePropAtRule(value.rules);
// If the rule is a style declaration, extract it with the `getExtractedStyle` function and store it in the `declarations` map
builder = builder.fork("style", value.selectors);
if (declarationBlock) {
if (declarationBlock.declarations) {
builder.newRule(mapping);
for (const declaration of declarationBlock.declarations) {
parseDeclaration(declaration, builder);
}
builder.applyRuleToSelectors();
}
if (declarationBlock.importantDeclarations) {
builder.newRule(mapping, { important: true });
for (const declaration of declarationBlock.importantDeclarations) {
parseDeclaration(declaration, builder);
}
builder.applyRuleToSelectors();
}
}
if (value.rules) {
for (const nestedRule of value.rules) {
extractRule(nestedRule, builder);
}
}
break;
}
case "layer-block":
for (const layerRule of rule.value.rules) {
extractRule(layerRule, builder);
}
break;
case "supports":
if (supportsConditionValid(rule.value.condition)) {
for (const layerRule of rule.value.rules) {
extractRule(layerRule, builder);
}
}
break;
case "custom":
case "font-face":
case "font-palette-values":
case "font-feature-values":
case "namespace":
case "layer-statement":
case "property":
case "view-transition":
case "ignored":
case "unknown":
case "import":
case "page":
case "counter-style":
case "moz-document":
case "nesting":
case "viewport":
case "custom-media":
case "scope":
case "starting-style":
break;
}
}
/**
* This function takes in a MediaRule object, an CompilerCollection object and a CssToReactNativeRuntimeOptions object,
* and returns an array of MediaQuery objects representing styles extracted from screen media queries.
*
* @param mediaRule - The MediaRule object containing the media query and its rules.
* @param collection - The CompilerCollection object to use when extracting styles.
* @param parseOptions - The CssToReactNativeRuntimeOptions object to use when parsing styles.
*
* @returns undefined if no screen media queries are found in the mediaRule, else it returns the extracted styles.
*/
function extractMedia(mediaRule: MediaRule, builder: StylesheetBuilder) {
builder = builder.fork("media");
// Initialize an empty array to store screen media queries
const media: CSSMediaQuery[] = [];
// Iterate over all media queries in the mediaRule
for (const mediaQuery of mediaRule.query.mediaQueries) {
if (
// If this is only a media query
(mediaQuery.mediaType === "print" && mediaQuery.qualifier !== "not") ||
// If this is a @media not print {}
// We can only do this if there are no conditions, as @media not print and (min-width: 100px) could be valid
(mediaQuery.mediaType !== "print" &&
mediaQuery.qualifier === "not" &&
mediaQuery.condition === null)
) {
continue;
}
media.push(mediaQuery);
}
if (media.length === 0) {
return;
}
for (const m of media) {
parseMediaQuery(m, builder);
}
// Iterate over all rules in the mediaRule and extract their styles using the updated CompilerCollection
for (const rule of mediaRule.rules) {
extractRule(rule, builder);
}
}
/**
* @param containerRule - The ContainerRule object containing the container query and its rules.
* @param collection - The CompilerCollection object to use when extracting styles.
* @param parseOptions - The CssToReactNativeRuntimeOptions object to use when parsing styles.
*/
function extractContainer(
containerRule: ContainerRule,
builder: StylesheetBuilder,
) {
builder = builder.fork("container");
// Iterate over all rules inside the containerRule and extract their styles using the updated CompilerCollection
const query: ContainerQuery = {
m: parseContainerCondition(containerRule.condition, builder),
};
if (containerRule.name) {
query.n = `c:${containerRule.name}`;
}
builder.addContainerQuery(query);
for (const rule of containerRule.rules) {
extractRule(rule, builder);
}
}