Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: theme builder AlertExample #740

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/storybook/config/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const config: StorybookConfig = {
'../../voorbeeld-design-tokens/documentation/**/*.stories.{ts,tsx}',
'../../../proprietary/*/documentation/{readme,color,design-tokens,typography}.mdx',
'../../../proprietary/*/documentation/*.stories.ts',
'../src/theme-builder/**/*.stories.{ts,tsx}',
],
framework: {
name: '@storybook/react-vite',
Expand Down
5 changes: 5 additions & 0 deletions packages/storybook/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@amsterdam/design-system-css": "0.11.0",
"@amsterdam/design-system-react": "0.11.0",
"@amsterdam/design-system-tokens": "0.11.0",
"@bundled-es-modules/memfs": "4.9.4",
"@gemeente-denhaag/design-tokens-components": "0.2.3-alpha.403",
"@gemeente-rotterdam/design-tokens": "1.0.0-alpha.34",
"@nl-design-system-unstable/amsterdam-design-tokens": "workspace:*",
Expand Down Expand Up @@ -80,17 +81,21 @@
"@storybook/blocks": "8.2.7",
"@storybook/react": "8.2.7",
"@storybook/react-vite": "8.2.7",
"@types/lodash": "4.17.9",
"@types/react": "18.3.3",
"@utrecht/component-library-react": "5.0.0",
"@utrecht/components": "6.2.0",
"@utrecht/design-tokens": "1.1.0",
"@utrecht/icon": "1.1.0",
"@utrecht/web-component-library-stencil": "1.4.0",
"clsx": "2.1.1",
"lodash": "4.17.21",
"npm-run-all": "4.1.5",
"react": "18.3.1",
"react-dom": "18.3.1",
"rimraf": "6.0.1",
"storybook": "8.2.7",
"style-dictionary": "4.0.1",
"vite": "5.3.5"
}
}
3 changes: 3 additions & 0 deletions packages/storybook/src/theme-builder/ThemeBuilder.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.theme-builder__example {
transition: all 1000ms ease-in-out;
}
173 changes: 173 additions & 0 deletions packages/storybook/src/theme-builder/ThemeBuilder.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import StyleDictionary from 'style-dictionary';
import memfs from '@bundled-es-modules/memfs';
import type { PropsWithChildren, ReactNode } from 'react';
import { useState, useEffect } from 'react';
import { ThemeBuilderStepObject } from './steps';
import { DesignTokenTree } from '@nl-design-system-unstable/theme-toolkit/dist/design-tokens';
import { treeToArray } from '@nl-design-system-unstable/theme-toolkit/dist/ExampleTokensCSS';
import './ThemeBuilder.css';
import './property.css';

const styleDictionaryConversion = async (
tokens,
selector,
filterFn = undefined,
): Promise<{ css: string; json: object }> => {
const { Volume } = memfs;
const vol = new Volume();
const sd = new StyleDictionary(
{
hooks: {
filters: {
'my-filter': filterFn,
},
},
tokens,
platforms: {
css: {
transforms: ['name/kebab'],
transformGroup: 'css',
files: [
{
destination: 'variables.css',
format: 'css/variables',
options: {
selector,
outputReferences: true,
},
filter: filterFn ? 'my-filter' : undefined,
},
],
},
json: {
transforms: ['name/kebab'],
transformGroup: 'css',
files: [
{
destination: 'variables.json',
format: 'json/flat',
filter: filterFn ? 'my-filter' : undefined,
},
],
},
},
},
{ volume: vol },
);

let css = '';
let json = {};
const id = Math.round(Math.random() * 1000);
console.time('Style Dictionary ' + id);
await sd.buildAllPlatforms();
console.timeEnd('Style Dictionary ' + id);

try {
css = vol.readFileSync('/variables.css').toString('utf-8');
json = JSON.parse(vol.readFileSync('/variables.json').toString('utf-8'));
} catch (e) {
console.error(e);
}

return { css, json };
};

export interface ThemeBuilderProps {
step: number;
steps: ThemeBuilderStepObject[];
theme: DesignTokenTree;
basis: DesignTokenTree;
example?: () => ReactNode;
allTokens?: boolean;
}

export const ThemeBuilder = ({
steps,
theme,
basis,
step,
example,
children,
allTokens,
}: PropsWithChildren<ThemeBuilderProps>) => {
const stepData = steps[step];
const Example = example || stepData?.example;
const Description = stepData?.description;

let relevantTokens = steps
.slice(0, step + 1)
.reduce((arr, step) => [...arr, ...step.tokens, ...(step.commonTokens || [])], []);

if (allTokens) {
relevantTokens = treeToArray(theme).map((token) => token.path.join('.'));
}

const relevantTokenSet = new Set(relevantTokens);

const [basisTokens] = useState(basis);
const [basisThemeCss, setBasisThemeCss] = useState('');
const [brandCss, setBrandCss] = useState('');
const [customThemeCss, setCustomThemeCss] = useState('');

useEffect(() => {
styleDictionaryConversion(basisTokens, '.basis-theme').then(({ css }) => {
setBasisThemeCss(css);
}, console.error);
}, [basisTokens]);

useEffect(() => {
styleDictionaryConversion(theme, '.brand-tokens', (token) => {
return (
['voorbeeld', 'groningen', 'rods'].includes(token.path[0]) ||
(token.path[0] === 'utrecht' && (token.path[1] === 'color' || token.path[1] === 'typography')) ||
(token.path[0] === 'denhaag' &&
(token.path[1] === 'color' || token.path[1] === 'typography' || token.path[1] === 'size'))
);
}).then(({ css }) => {
setBrandCss(css);
}, console.error);
}, [theme]);

useEffect(() => {
styleDictionaryConversion(theme, '.step-theme', (token) => {
return relevantTokenSet.has((token.path || []).join('.'));
}).then(({ css, json }) => {
console.log(json);
setCustomThemeCss(css);
}, console.error);
}, [step, theme]);

return (
<div className="theme-builder">
<div className="theme-builder__example basis-theme brand-tokens step-theme">{Example && <Example />}</div>
<h2>{stepData?.name || `Stap ${step}`}</h2>
{Description && <Description />}
<style dangerouslySetInnerHTML={{ __html: basisThemeCss }}></style>
<style dangerouslySetInnerHTML={{ __html: brandCss }}></style>
<style dangerouslySetInnerHTML={{ __html: customThemeCss }}></style>
<details>
<summary>{relevantTokens.length} tokens up until this step</summary>
<ul>
{relevantTokens.map((token, index) => (
<li key={index}>
<code>{token}</code>
</li>
))}
</ul>
</details>
<details>
<summary>Thema voor stap {step}</summary>
<pre>{customThemeCss}</pre>
</details>
<details>
<summary>Brand tokens</summary>
<pre>{brandCss}</pre>
</details>
<details>
<summary>Basis thema</summary>
<pre>{basisThemeCss}</pre>
</details>
{children}
</div>
);
};
Loading