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 28, 2024
1 parent 2a50875 commit 32b9909
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 2 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,6 @@
},
"resolutions": {
"jackspeak": "2.1.1"
}
},
"packageManager": "[email protected]+sha512.140036830124618d624a2187b50d04289d5a087f326c9edfc0ccd733d76c4f52c3a313d4fc148794a2a9d81553016004e6742e8cf850670268a7387fc220c903"
}
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 32b9909

Please sign in to comment.