|
| 1 | +import path from 'path'; |
| 2 | +import { PostcssThemeConfig, PostcssStrictThemeConfig, Theme } from "../types"; |
| 3 | + |
| 4 | +/** Get the theme variable name from a string */ |
| 5 | +export const parseThemeKey = (value: string) => { |
| 6 | + const key = value.match(/@theme ([a-zA-Z-_0-9]+)/); |
| 7 | + return key ? key[1] : ''; |
| 8 | +} |
| 9 | + |
| 10 | +/** Replace a theme variable reference with a value */ |
| 11 | +export const replaceTheme = (value: string, replace: string) => { |
| 12 | + return value.replace(/@theme ([a-zA-Z-_0-9]+)/, replace); |
| 13 | +} |
| 14 | + |
| 15 | +/** Get the location of the theme file */ |
| 16 | +export function getThemeFilename(cssFile: string) { |
| 17 | + return path.join(path.dirname(cssFile), 'theme'); |
| 18 | +} |
| 19 | + |
| 20 | +/** Remove :theme-root usage from a selector */ |
| 21 | +export const replaceThemeRoot = (selector: string) => |
| 22 | + selector.replace(/:theme-root\((\S+)\)/g, '$1').replace(/:theme-root/g, ''); |
| 23 | + |
| 24 | +/** Make a SimpleTheme into a LightDarkTheme */ |
| 25 | +export const normalizeTheme = (config: PostcssThemeConfig | {}): PostcssStrictThemeConfig => { |
| 26 | + return Object.assign( |
| 27 | + {}, |
| 28 | + ...Object.entries(config).map(([theme, themeConfig]) => { |
| 29 | + if ('light' in themeConfig && 'dark' in themeConfig) { |
| 30 | + return { [theme]: themeConfig }; |
| 31 | + } |
| 32 | + |
| 33 | + return { [theme]: { light: themeConfig, dark: {} } }; |
| 34 | + }) |
| 35 | + ); |
| 36 | +}; |
| 37 | + |
| 38 | +/** Determine if a theme has dark mode enabled */ |
| 39 | +export const hasDarkMode = (theme: Theme) => |
| 40 | + Boolean( |
| 41 | + Object.keys(theme.dark).length > 0 && Object.keys(theme.light).length > 0 |
| 42 | + ); |
| 43 | + |
0 commit comments