-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.ts
313 lines (282 loc) · 10.4 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import Color from 'color';
import plugin from 'tailwindcss/plugin';
import forEach from 'lodash.foreach';
import flatten from 'flat';
const SCHEME = Symbol('color-scheme');
const emptyConfig: TwcConfig = {};
type NestedColors = { [SCHEME]?: 'light' | 'dark' } & MaybeNested<string, string>;
type FlatColors = { [SCHEME]?: 'light' | 'dark' } & Record<string, string>;
type TwcObjectConfig<ThemeName extends string> = Record<ThemeName, NestedColors>;
type TwcFunctionConfig<ThemeName extends string> = (scheme: {
light: typeof light;
dark: typeof dark;
}) => TwcObjectConfig<ThemeName>;
type DefaultThemeObject<ThemeName = any> = {
light: NoInfer<ThemeName> | (string & {});
dark: NoInfer<ThemeName> | (string & {});
};
type ResolvedVariants = Array<{ name: string; definition: string[] }>;
type ResolvedUtilities = { [selector: string]: Record<string, any> };
type ResolvedColors = {
[colorName: string]: ({
opacityValue,
opacityVariable,
}: {
opacityValue: string;
opacityVariable: string;
}) => string;
};
type Resolved = {
variants: ResolvedVariants;
utilities: ResolvedUtilities;
colors: ResolvedColors;
};
export type TwcConfig<ThemeName extends string = string> =
| TwcObjectConfig<ThemeName>
| TwcFunctionConfig<ThemeName>;
export interface TwcOptions<ThemeName extends string = string> {
produceCssVariable?: (colorName: string) => string;
produceThemeClass?: (themeName: ThemeName) => string;
produceThemeVariant?: (themeName: ThemeName) => string;
defaultTheme?: NoInfer<ThemeName> | (string & {}) | DefaultThemeObject<ThemeName>;
strict?: boolean;
}
/**
* Resolves the variants, base and colors to inject in the plugin
* Library authors might use this function instead of the createThemes function
*/
export const resolveTwcConfig = <ThemeName extends string>(
config: TwcConfig<ThemeName> = emptyConfig,
{
produceCssVariable = defaultProduceCssVariable,
produceThemeClass = defaultProduceThemeClass,
produceThemeVariant = produceThemeClass,
defaultTheme,
strict = false,
}: TwcOptions<ThemeName> = {},
) => {
const resolved: Resolved = {
variants: [],
utilities: {},
colors: {},
};
const configObject = typeof config === 'function' ? config({ dark, light }) : config;
// @ts-ignore forEach types fail to assign themeName
forEach(configObject, (colors: NestedColors, themeName: ThemeName) => {
const themeClassName = produceThemeClass(themeName);
const themeVariant = produceThemeVariant(themeName);
const flatColors = flattenColors(colors);
// set the resolved.variants
resolved.variants.push({
name: themeVariant,
// tailwind will generate only the first matched definition
definition: [
generateVariantDefinitions(`.${themeClassName}`),
generateVariantDefinitions(`[data-theme='${themeName}']`),
generateRootVariantDefinitions(themeName, defaultTheme),
].flat(),
});
const cssSelector = `.${themeClassName},[data-theme="${themeName}"]`;
// set the color-scheme css property
resolved.utilities[cssSelector] = colors[SCHEME] ? { 'color-scheme': colors[SCHEME] } : {};
forEach(flatColors, (colorValue, colorName) => {
// this case was handled above
if ((colorName as any) === SCHEME) return;
const safeColorName = escapeChars(colorName, '/');
let [h, s, l, defaultAlphaValue]: HslaArray = [0, 0, 0, 1];
try {
[h, s, l, defaultAlphaValue] = toHslaArray(colorValue);
} catch (error: any) {
const message = `\r\nWarning - In theme "${themeName}" color "${colorName}". ${error.message}`;
if (strict) {
throw new Error(message);
}
return console.error(message);
}
const twcColorVariable = produceCssVariable(safeColorName);
const twcOpacityVariable = `${produceCssVariable(safeColorName)}-opacity`;
// add the css variables in "@layer utilities" for the hsl values
const hslValues = `${h} ${s}% ${l}%`;
resolved.utilities[cssSelector][twcColorVariable] = hslValues;
addRootUtilities(resolved.utilities, {
key: twcColorVariable,
value: hslValues,
defaultTheme,
themeName,
});
if (typeof defaultAlphaValue === 'number') {
// add the css variables in "@layer utilities" for the alpha
const alphaValue = defaultAlphaValue.toFixed(2);
resolved.utilities[cssSelector][twcOpacityVariable] = alphaValue;
addRootUtilities(resolved.utilities, {
key: twcOpacityVariable,
value: alphaValue,
defaultTheme,
themeName,
});
}
// set the dynamic color in tailwind config theme.colors
resolved.colors[colorName] = ({ opacityVariable, opacityValue }) => {
// if the opacity is set with a slash (e.g. bg-primary/90), use the provided value
if (!isNaN(+opacityValue)) {
return `hsl(var(${twcColorVariable}) / ${opacityValue})`;
}
// if no opacityValue was provided (=it is not parsable to a number),
// the twcOpacityVariable (opacity defined in the color definition rgb(0, 0, 0, 0.5))
// should have the priority over the tw class based opacity(e.g. "bg-opacity-90")
// This is how tailwind behaves as for v3.2.4
if (opacityVariable) {
return `hsl(var(${twcColorVariable}) / var(${twcOpacityVariable}, var(${opacityVariable})))`;
}
return `hsl(var(${twcColorVariable}) / var(${twcOpacityVariable}, 1))`;
};
});
});
return resolved;
};
export const createThemes = <ThemeName extends string>(
config: TwcConfig<ThemeName> = emptyConfig,
options: TwcOptions<ThemeName> = {},
) => {
const resolved = resolveTwcConfig(config, options);
return plugin(
({ addUtilities, addVariant }) => {
// add the css variables to "@layer utilities" because:
// - The Base layer does not provide intellisense
// - The Components layer might get overriden by tailwind default colors in case of name clash
addUtilities(resolved.utilities);
// add the theme as variant e.g. "theme-[name]:text-2xl"
resolved.variants.forEach(({ name, definition }) => addVariant(name, definition));
},
// extend the colors config
{
theme: {
extend: {
// @ts-ignore tailwind types are broken
colors: resolved.colors,
},
},
},
);
};
function escapeChars(str: string, ...chars: string[]) {
let result = str;
for (let char of chars) {
const regexp = new RegExp(char, 'g');
result = str.replace(regexp, '\\' + char);
}
return result;
}
function flattenColors(colors: NestedColors) {
const flatColorsWithDEFAULT: FlatColors = flatten(colors, {
safe: true,
delimiter: '-',
});
return Object.entries(flatColorsWithDEFAULT).reduce((acc, [key, value]) => {
acc[key.replace(/\-DEFAULT$/, '')] = value;
return acc;
}, {} as FlatColors);
}
function toHslaArray(colorValue?: string) {
return Color(colorValue).hsl().round(1).array() as HslaArray;
}
function defaultProduceCssVariable(themeName: string) {
return `--twc-${themeName}`;
}
function defaultProduceThemeClass(themeName: string) {
return themeName;
}
function dark(colors: NestedColors): { [SCHEME]: 'dark' } & MaybeNested<string, string> {
return {
...colors,
[SCHEME]: 'dark',
};
}
function light(colors: NestedColors): { [SCHEME]: 'light' } & MaybeNested<string, string> {
return {
...colors,
[SCHEME]: 'light',
};
}
function generateVariantDefinitions(selector: string) {
return [
`${selector}&`,
`:is(${selector} > &:not([data-theme]))`,
`:is(${selector} &:not(${selector} [data-theme]:not(${selector}) * ))`,
`:is(${selector}:not(:has([data-theme])) &:not([data-theme]))`,
];
}
function generateRootVariantDefinitions<ThemeName extends string>(
themeName: ThemeName,
defaultTheme: TwcOptions<ThemeName>['defaultTheme'],
) {
const baseDefinitions = [
`:root&`,
`:is(:root > &:not([data-theme]))`,
`:is(:root &:not([data-theme] *):not([data-theme]))`,
];
if (typeof defaultTheme === 'string' && themeName === defaultTheme) {
return baseDefinitions;
}
if (typeof defaultTheme === 'object' && themeName === defaultTheme.light) {
return baseDefinitions.map(
(definition) => `@media (prefers-color-scheme: light){${definition}}`,
);
}
if (typeof defaultTheme === 'object' && themeName === defaultTheme.dark) {
return baseDefinitions.map(
(definition) => `@media (prefers-color-scheme: dark){${definition}}`,
);
}
return [];
}
// hande the defaultTheme utils
function addRootUtilities<ThemeName extends string>(
utilities: ResolvedUtilities,
{
key,
value,
defaultTheme,
themeName,
}: {
key: string;
value: string;
defaultTheme: TwcOptions<ThemeName>['defaultTheme'];
themeName: ThemeName;
},
) {
if (!defaultTheme) return;
if (typeof defaultTheme === 'string') {
if (themeName === defaultTheme) {
// initialize
if (!utilities[':root']) {
utilities[':root'] = {};
}
// set
utilities[':root'][key] = value;
}
} else if (themeName === defaultTheme.light) {
// initialize
if (!utilities['@media (prefers-color-scheme: light)']) {
utilities['@media (prefers-color-scheme: light)'] = {
':root': {},
};
}
// set
utilities['@media (prefers-color-scheme: light)'][':root'][key] = value;
} else if (themeName === defaultTheme.dark) {
// initialize
if (!utilities['@media (prefers-color-scheme: dark)']) {
utilities['@media (prefers-color-scheme: dark)'] = {
':root': {},
};
}
// set
utilities['@media (prefers-color-scheme: dark)'][':root'][key] = value;
}
}
interface MaybeNested<K extends keyof any = string, V extends string = string> {
[key: string]: V | MaybeNested<K, V>;
}
type NoInfer<T> = [T][T extends any ? 0 : never];
type HslaArray = [number, number, number, number | undefined];