Skip to content

Commit

Permalink
Initial resolve theme refs exploration
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronccasanova committed Sep 22, 2023
1 parent 3bafbea commit 01b63b4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 9 deletions.
24 changes: 15 additions & 9 deletions polaris-tokens/scripts/toValues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,11 @@ export async function toValues() {
await fs.promises.writeFile(
path.join(outputDir, 'index.ts'),
[
"import {resolveThemeRefs} from '../src/themes/utils';",
`export * from '../src/index';`,
Object.entries(themeDefault).map(createExport),
createExport(['tokens', themeDefault]),
createExport([
'themes',
Object.fromEntries(
Object.entries(metaThemes).map(([themeName, metaTheme]) => [
themeName,
extractMetaThemeValues(metaTheme),
]),
),
]),
createExportThemes(),
]
.flat()
.join('\n'),
Expand All @@ -39,3 +32,16 @@ export async function toValues() {
function createExport(entry: [string | number, any]) {
return `export const ${entry[0]} = ${JSON.stringify(entry[1])} as const;`;
}

function createExportThemes() {
const themes = Object.entries(metaThemes)
.map(([themeName, metaTheme]) => {
const theme = extractMetaThemeValues(metaTheme);
const themeJSON = JSON.stringify(theme, null, 2);

return `'${themeName}': resolveThemeRefs(${themeJSON})`;
})
.join(',\n');

return `export const themes = {\n${themes}\n} as const;`;
}
30 changes: 30 additions & 0 deletions polaris-tokens/src/themes/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type {
MetaThemePartialShape,
MetaTokenGroupShape,
ThemeName,
Theme,
} from './types';
import {themeNameLightUplift} from './constants';
import {metaThemeBase} from './base';
Expand Down Expand Up @@ -54,3 +55,32 @@ export function extractMetaThemeValues<T extends MetaThemeShape>(metaTheme: T) {
),
) as ExtractMetaThemeValues<T>;
}

/**
* Private utility to resolve references within the theme object by:
* 1. Traversing each token group.
* 2. Identifying token values starting with `var(--p-`.
* 3. Replacing these values with a getter function that returns the resolved value.
* 4. Returning the mutated theme object.
*/
export function resolveThemeRefs<T extends Theme>(theme: T): T {
Object.keys(theme).forEach((tokenGroupName) => {
const tokenGroupRef = theme[tokenGroupName as keyof Theme];

Object.entries(tokenGroupRef).forEach(([tokenName, tokenValue]) => {
if (tokenValue.startsWith('var(--p-')) {
const tokenNameRef = tokenValue.slice(8, -1);
const tokenGroupNameRef = tokenNameRef.split('-')[0];

Object.defineProperty(tokenGroupRef, tokenName, {
get() {
return (theme as any)[tokenGroupNameRef][tokenNameRef] as string;
},
enumerable: true,
});
}
});
});

return theme;
}

0 comments on commit 01b63b4

Please sign in to comment.