-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathglobalStyle.ts
99 lines (81 loc) · 2.2 KB
/
globalStyle.ts
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
import postcss from 'postcss';
import { globalifySelector } from '../modules/globalifySelector';
import type * as pcss from 'postcss';
import type { Transformer, Options } from '../types';
const selectorPattern = /:global(?!\()/;
const globalifyRulePlugin = (root: pcss.Root) => {
root.walkRules(selectorPattern, (rule) => {
const modifiedSelectors = rule.selectors
.filter((selector) => selector !== ':global')
.map((selector) => {
const [beginning, ...rest] = selector.split(selectorPattern);
if (rest.length === 0) return beginning;
return [beginning, ...rest.map(globalifySelector)]
.map((str) => str.trim())
.join(' ')
.trim();
});
if (modifiedSelectors.length === 0) {
if (rule.parent?.type === 'atrule' && rule.selector === ':global') {
rule.replaceWith(...rule.nodes);
} else {
rule.remove();
}
return;
}
rule.replaceWith(
rule.clone({
selectors: modifiedSelectors,
}),
);
});
};
const globalAttrPlugin = (root: pcss.Root) => {
root.walkAtRules(/keyframes$/, (atrule) => {
if (!atrule.params.startsWith('-global-')) {
atrule.replaceWith(
atrule.clone({
params: `-global-${atrule.params}`,
}),
);
}
});
root.walkRules((rule) => {
// we use endsWith for checking @keyframes and prefixed @-{prefix}-keyframes
if ((rule?.parent as pcss.AtRule)?.name?.endsWith('keyframes')) {
return;
}
rule.replaceWith(
rule.clone({
selectors: rule.selectors.map(globalifySelector),
}),
);
});
};
const transformer: Transformer<Options.GlobalStyle> = async ({
content,
filename,
options,
map,
attributes,
}) => {
const plugins = [
globalifyRulePlugin,
attributes?.global && globalAttrPlugin,
].filter(Boolean);
const { css, map: newMap } = await postcss(plugins).process(content, {
from: filename,
to: filename,
map: options?.sourceMap ? { prev: map } : false,
});
if (attributes?.global) {
const { global, ...rest } = attributes;
attributes = rest;
}
return {
code: css,
map: newMap,
attributes,
};
};
export { transformer };