Skip to content

Commit

Permalink
feat: alternative syntax for cssVarV2
Browse files Browse the repository at this point in the history
  • Loading branch information
pengx17 committed Dec 3, 2024
1 parent 6ca1acf commit bd050b0
Show file tree
Hide file tree
Showing 7 changed files with 1,395 additions and 46 deletions.
44 changes: 38 additions & 6 deletions packages/theme/src/v2/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { objectKeys } from '../utils/object-keys';
import { darkThemeV2, lightThemeV2 } from './variables';
import {
darkThemeV2,
lightThemeV2,
// only use for type inference
type nestedDarkTheme,
type nestedLightTheme,
} from './variables';

type NestedTheme = typeof nestedLightTheme | typeof nestedDarkTheme;

export { darkThemeV2, lightThemeV2 };
export type AffineThemeV2 = typeof lightThemeV2;
Expand All @@ -21,17 +29,41 @@ function createVariables(theme: AffineThemeV2) {
export const lightCssVariablesV2 = createVariables(lightThemeV2);
export const darkCssVariablesV2 = createVariables(darkThemeV2);

function _cssVarV2(key: AffineThemeKeyV2, fallback?: string) {
return `var(${themeToVar(key)}${fallback ? `, ${fallback}` : ''})`;
}

function createCssVarProxy(prefix: string = ''): any {
return new Proxy(_cssVarV2, {
get(_, prop) {
const newPrefix = prefix ? `${prefix}/${String(prop)}` : String(prop);

if (typeof lightThemeV2[newPrefix as AffineThemeKeyV2] !== 'string') {
return createCssVarProxy(newPrefix);
}

// found the value
return _cssVarV2(newPrefix as AffineThemeKeyV2);
},
apply(_, __, [fallback]) {
return _cssVarV2(prefix as AffineThemeKeyV2, fallback);
},
});
}

/**
* Get AFFiNE css variable name type safely (v2)
* @param key as copied from Figma design. __e.g. `text/primary`__
*
*
* ```ts
* import { cssVarV2 } from '@toeverything/theme/v2';
*
*
* cssVarV2('text/primary');
* cssVarV2('button/siderbarPrimary/background')
*
* // alternative syntax:
* cssVarV2.text.primary;
* cssVarV2.button.siderbarPrimary.background;
* ```
*/
export function cssVarV2(key: AffineThemeKeyV2, fallback?: string) {
return `var(${themeToVar(key)}${fallback ? `, ${fallback}` : ''})`;
}
export const cssVarV2 = createCssVarProxy() as typeof _cssVarV2 & NestedTheme;
Loading

0 comments on commit bd050b0

Please sign in to comment.