-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
92 lines (77 loc) · 3.01 KB
/
index.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
import { CustomThemeConfig } from 'tailwindcss/types/config';
type Options = {
prefix?: string;
};
const tailwindAliasesMap = [
{
functionIdent: 'speed',
tailwindKey: 'transitionDuration'
},
{
functionIdent: 'ease',
tailwindKey: 'transitionTimingFunction'
},
{
functionIdent: 'z',
tailwindKey: 'zIndex'
},
{
functionIdent: 'color',
tailwindKey: 'colors'
},
{
functionIdent: 'spacing',
tailwindKey: 'spacing'
}
];
const postcssTailwindShortcuts = (tailwindThemeConfig: Partial<CustomThemeConfig>, options: Options = {}) => {
return {
postcssPlugin: 'postcss-tailwind-shortcuts',
Root(root) {
root.walkDecls((decl) => {
// Create a concatenated regular expression pattern for all functionIdent values
const functionIdents = tailwindAliasesMap
.map((alias) => {
if (options?.prefix) {
return `${options?.prefix}-${alias.functionIdent}`;
}
return alias.functionIdent;
})
.join('|');
const regex = new RegExp(
`\\b(${functionIdents})\\s*\\(\\s*['"]?([^'")]+)?['"]?\\s*\\)`,
'g'
);
// Replace the function with the Tailwind value
decl.value = decl.value.replace(regex, (match, ident, value) => {
// Find the corresponding tailwind key and get the value
const alias = tailwindAliasesMap.find((alias) => {
if (options?.prefix) {
return `${options?.prefix}-${alias.functionIdent}` === ident;
}
return alias.functionIdent === ident;
});
if (alias) {
const tailwindKey = alias.tailwindKey;
const defaultValue = 'default'; // Default key value to use if no value is provided
// Determine the value to use
const keyValue = value || defaultValue;
// Access the value from the Tailwind config
const tailwindValue = tailwindThemeConfig.extend[tailwindKey]?.[keyValue];
// Log an error if no value is found
if (!tailwindValue) {
console.error(`No value found for ${tailwindKey}.${keyValue}`);
return match;
}
// Return the Tailwind value
return tailwindValue;
}
// Return the original value if no match is found
return match;
});
});
}
};
};
postcssTailwindShortcuts.postcss = true;
export default postcssTailwindShortcuts;