-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
preprocessor.ts
71 lines (61 loc) · 1.94 KB
/
preprocessor.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
import type { Element } from 'stylis';
import { serialize, compile, stringify, middleware } from 'stylis';
import rtlPlugin from 'stylis-plugin-rtl';
import { type PluginCustomOptions } from './cssFnValueToVariable';
function globalSelector(element: Element) {
switch (element.type) {
case 'rule':
element.props = (element.props as string[]).map((value) => {
if (value.match(/(:where|:is)\(/)) {
value = value.replace(/\.[^:]+(:where|:is)/, '$1');
return value;
}
return value;
});
break;
default:
break;
}
}
function getSerializer(includeRtl?: boolean) {
if (!includeRtl) {
return middleware([globalSelector, stringify]);
}
return middleware([globalSelector, rtlPlugin, stringify]);
}
const serializer = getSerializer();
const serializerRtl = getSerializer(true);
const stylis = (css: string, serializerParam = serializer) =>
serialize(compile(css), serializerParam);
const defaultGetDirSelector = (dir: 'ltr' | 'rtl') => `[dir=${dir}]`;
export function getGlobalSelector(asSelector: string) {
return `$$GLOBAL-${asSelector}`;
}
export function preprocessor(
selector: string,
cssText: string,
options?: PluginCustomOptions['css'],
) {
const {
defaultDirection = 'ltr',
generateForBothDir = false,
getDirSelector = defaultGetDirSelector,
} = options || {};
let css = '';
const isGlobal = selector.startsWith(getGlobalSelector(''));
if (!isGlobal && cssText.startsWith('@keyframes')) {
css += stylis(cssText.replace('@keyframes', `@keyframes ${selector}`));
return css;
}
css += stylis(!isGlobal ? `${selector}{${cssText}}` : cssText);
if (generateForBothDir) {
css += stylis(
`${getDirSelector(defaultDirection === 'ltr' ? 'rtl' : 'ltr')} ${!isGlobal ? `${selector}{${cssText}}` : cssText}`,
serializerRtl,
);
}
return css;
}
export function matchAdapterPath(path: string) {
return path.includes('zero-styled');
}