forked from brikou/CSS-in-JS-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvertCssForEmotion.ts
More file actions
73 lines (60 loc) · 2.39 KB
/
convertCssForEmotion.ts
File metadata and controls
73 lines (60 loc) · 2.39 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
import { convertScopedCssForEmotion } from "./convertScopedCssForEmotion";
import { convertScopeToModuleName } from "./convertScopeToModuleName";
import { getCssIndexedByScope } from "./getCssIndexedByScope";
import { getRequiredScopes } from "./getRequiredScopes";
export function convertCssForEmotion(css: string): string {
let cssForEmotion = "";
const cssIndexedByScope = getCssIndexedByScope(css);
if (cssIndexedByScope.has("root")) {
if (cssIndexedByScope.size > 1) {
cssForEmotion += 'import { css, injectGlobal } from "emotion";\n';
} else {
cssForEmotion += 'import { injectGlobal } from "emotion";\n';
}
} else if (cssIndexedByScope.size > 0) {
cssForEmotion += 'import { css } from "emotion";\n';
}
const knownScopes = new Set([...cssIndexedByScope.keys()]);
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: "base",
});
const sortedKnownScopes = [...knownScopes]
.sort((scopeA, scopeB) => {
if (scopeA === "root") {
return -1;
}
return collator.compare(scopeA, scopeB);
})
.reduce((previousSortedKnownScopes: Set<string>, knownScope: string) => {
getRequiredScopes(
cssIndexedByScope.get(knownScope) as string,
knownScope,
knownScopes,
).forEach((requiredScope) => {
if (previousSortedKnownScopes.has(requiredScope) === false) {
previousSortedKnownScopes.add(requiredScope);
}
});
if (previousSortedKnownScopes.has(knownScope) === false) {
previousSortedKnownScopes.add(knownScope);
}
return previousSortedKnownScopes;
}, new Set());
sortedKnownScopes.forEach((scope) => {
cssForEmotion += "\n";
const convertedScopedCssForEmotion = convertScopedCssForEmotion(
cssIndexedByScope.get(scope) as string,
scope,
knownScopes,
);
if (scope === "root") {
cssForEmotion += `injectGlobal\`${convertedScopedCssForEmotion}\`;\n`;
} else {
cssForEmotion += `export const ${convertScopeToModuleName(
scope,
)} = css\`${convertedScopedCssForEmotion}\`;\n`;
}
});
return cssForEmotion;
}