Skip to content

Commit

Permalink
export tetra tokens as CSS Variables
Browse files Browse the repository at this point in the history
  • Loading branch information
winkerVSbecks committed Jul 29, 2024
1 parent 2a50875 commit 730607b
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
26 changes: 26 additions & 0 deletions src/css-variables.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Meta, Source } from '@storybook/blocks';
import cssVariables from './css-variables';

<Meta title="Tokens/CSS Variables" />

# Token CSS Variables

The tokens are also available as CSS Variables. To use them:

```jsx
import cssVariables from '@chromatic-com/tetra/css-variables';
import { css, Global } from '@storybook/theming';

const tetraCSSVariables = css`
${cssVariables}
`;

const App = () => (
<>
<Global styles={tetraCSSVariables} />
{/* Other app components */}
</>
);
```

<Source code={cssVariables} />
48 changes: 48 additions & 0 deletions src/css-variables.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import {
color,
fontFamily,
fontWeight,
fontSize,
lineHeight,
breakpoint,
spacing,
} from './_tokens/tokens';

const prefix = 'tetra';

function jsonToCssVariables(tokenType: string, json: Record<string, any>) {
const keys = Object.keys(json);

const vars = keys.map((key) => {
const varValue = json[key];
const varName = `--${prefix}-${tokenType}-${key}`;

return ` ${varName}: ${varValue};`;
}, {});

return vars.join('\n');
}

function generateCSSVariables() {
const cssVariables = `:root {
${jsonToCssVariables('color', color)}
${jsonToCssVariables('fontFamily', fontFamily)}
${jsonToCssVariables('fontWeight', fontWeight)}
${jsonToCssVariables('fontSize', fontSize)}
${jsonToCssVariables('lineHeight', lineHeight)}
${jsonToCssVariables('breakpoint', breakpoint)}
${jsonToCssVariables('spacing', spacing)}
}`;

return cssVariables;
}

const cssVariables = generateCSSVariables();

export default cssVariables;
2 changes: 1 addition & 1 deletion tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { defineConfig } from 'tsup';

export default defineConfig({
entry: ['src/index.ts'],
entry: ['src/index.ts', 'src/css-variables.ts'],
treeshake: true,
sourcemap: true,
minify: true,
Expand Down

0 comments on commit 730607b

Please sign in to comment.