forked from brikou/CSS-in-JS-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetCssIndexedByScope.ts
More file actions
57 lines (46 loc) · 1.54 KB
/
getCssIndexedByScope.ts
File metadata and controls
57 lines (46 loc) · 1.54 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
import {parse} from "postcss";
import type {Node} from "postcss";
import Stringifier from "postcss/lib/stringifier";
import { getNodeScopes } from "./getNodeScopes";
import { getSelectorScope } from "./getSelectorScope";
export function getCssIndexedByScope(css: string): Map<string, string> {
const cssIndexedByScope = new Map();
const scopesStack = [new Set(["root"])];
function builder(
output: string,
node?: Node,
flag?: "start" | "end",
) {
if (flag === "start" && node) {
scopesStack.push(getNodeScopes(node));
}
if (flag === "end") {
output += "\n\n";
}
scopesStack[scopesStack.length - 1].forEach((scope) => {
if (cssIndexedByScope.has(scope) === false) {
cssIndexedByScope.set(scope, "");
}
if (
flag === "start" &&
node &&
node.type === "rule" &&
(node.parent.type !== "atrule" ||
/keyframes$/.test(node.parent.name) === false)
) {
output = `${(node.selectors || [])
.filter(
(selector) => getSelectorScope(selector) === scope,
)} {`;
}
cssIndexedByScope.set(scope, cssIndexedByScope.get(scope) + output);
});
if (flag === "end") {
scopesStack.pop();
}
}
(new Stringifier(builder)).stringify(
parse(css),
);
return cssIndexedByScope;
}