-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreateCSSStyleSheet.ts
More file actions
75 lines (69 loc) · 2.4 KB
/
createCSSStyleSheet.ts
File metadata and controls
75 lines (69 loc) · 2.4 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
const NEW_SHEET_ID = "react-native-stylesheet-layered";
const layerBoundaryRegex = /\[stylesheet-group="[^01]"]/;
let proxy: CSSStyleSheet | null = null;
export default function createCSSStyleSheet(
id: string,
rootNode?: any,
textContent?: string,
): CSSStyleSheet | null {
return (proxy ??= buildRNWProxy(textContent));
}
function buildRNWProxy(initialTextContent?: string) {
if (typeof window === "undefined") {
return null;
}
const flattenedSheet = new CSSStyleSheet();
if (initialTextContent) {
flattenedSheet.replaceSync(initialTextContent);
}
let layeredSheet = (document.getElementById(NEW_SHEET_ID) as HTMLStyleElement)
?.sheet;
if (!layeredSheet) {
const styleElem = document.createElement("style");
styleElem.id = NEW_SHEET_ID;
document.head.prepend(styleElem);
layeredSheet = styleElem.sheet;
}
if (!layeredSheet) return flattenedSheet;
// ensure that the first rule in the layered sheet is a layer
if (!(layeredSheet.cssRules[0] instanceof CSSLayerBlockRule)) {
layeredSheet.insertRule("@layer rnw {}", 0);
}
// Traverse the layered sheet to build the flattened sheet
flattenRules(layeredSheet.cssRules, flattenedSheet);
return new Proxy(flattenedSheet, {
get(target, prop) {
if (prop === "insertRule") {
return function insertRule(text: string, index: number) {
flattenedSheet.insertRule(text, index);
// find the index of the groups
const cutoffIndex = [...flattenedSheet.cssRules].findIndex((rule) =>
layerBoundaryRegex.exec(rule.cssText),
);
if (cutoffIndex === -1 || index <= cutoffIndex) {
// insert into the layer
const layerRule = layeredSheet.cssRules[0] as CSSLayerBlockRule;
layerRule.insertRule(text, layerRule.cssRules.length);
} else {
// insert into the sheet normally
layeredSheet.insertRule(text, layeredSheet.cssRules.length);
}
};
}
const value = (target as any)[prop];
return typeof value === "function" ? value.bind(target) : value;
},
});
}
function flattenRules(
rules: CSSRuleList | CSSRule[],
targetSheet: CSSStyleSheet,
) {
for (const rule of rules) {
if (rule instanceof CSSLayerBlockRule) {
flattenRules(rule.cssRules, targetSheet);
} else {
targetSheet.insertRule(rule.cssText, targetSheet.cssRules.length);
}
}
}