Skip to content

Commit

Permalink
Merge pull request #103 from chromaui/css-vars
Browse files Browse the repository at this point in the history
export tetra tokens as CSS Variables
  • Loading branch information
winkerVSbecks authored Jul 29, 2024
2 parents 2a50875 + 18d564f commit ce67d97
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
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} />
46 changes: 46 additions & 0 deletions src/css-variables.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
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;
}

export const cssVariables = generateCSSVariables();
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,5 @@ export { Stat } from './Stat';
export { SubNav } from './SubNav';
export { Testimonial } from './Testimonial';
export { Text } from './Text';

export { cssVariables } from './css-variables';

0 comments on commit ce67d97

Please sign in to comment.