@raketa-cloud/design-cli 0.0.0-stage → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -2
- package/build.mjs +113 -0
- package/catalog/css-native.mjs +87 -0
- package/catalog/status-colors.mjs +12 -0
- package/cli.mjs +41 -0
- package/config.mjs +39 -0
- package/init.mjs +31 -0
- package/package.json +37 -4
- package/preview-css.mjs +45 -0
- package/showcase/asset-grid.css +7 -0
- package/showcase/asset-grid.mjs +7 -0
- package/showcase/assets.mjs +44 -0
- package/showcase/presets/dark.css +15 -0
- package/showcase/presets/default.css +14 -0
- package/showcase/reload.js +7 -0
- package/showcase/serve.mjs +292 -0
- package/showcase/showcase.css +73 -0
- package/skills/design-system/SKILL.md +27 -0
- package/tokens/themes.mjs +39 -0
package/README.md
CHANGED
|
@@ -1,3 +1,51 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Design tooling
|
|
2
|
+
|
|
3
|
+
Shared Node 22+ tooling for local design systems. It serves the showcase and builds a standalone CSS file from design tokens and component CSS.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
Initialize a host project, then generate and preview its design system:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx @raketa-cloud/design-cli init
|
|
11
|
+
npx @raketa-cloud/design-cli generate
|
|
12
|
+
npx @raketa-cloud/design-cli serve
|
|
13
|
+
npx @raketa-cloud/design-cli new component my-pattern
|
|
14
|
+
npx @raketa-cloud/design-cli new layout my-pattern
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Alternatively, install it with `npm install --save-dev @raketa-cloud/design-cli` and run `npx design <command>`. Run `npx @raketa-cloud/design-cli --help` for usage. `serve` listens on `127.0.0.1:4174`; `PORT` changes the port. `SHOWCASE_PRESET` selects a built-in or design-local preset. New scaffold previews link `/__showcase/theme.css`, so existing component classes work when opened through the showcase. Scaffolded markup and docs remain placeholders, not finished designs.
|
|
18
|
+
`init` creates a starter `.design` directory, installs the design-system skill to `.agents/skills/design-system`, and links it from `.claude/skills/` and `.pi/skills/`. It refuses to overwrite any of those paths. Update `.design/config.json`, tokens, and `DESIGN.md` for your project, then add patterns and wire the generated CSS into your application. The initializer does not change application code or dependencies.
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
Pattern previews are hand-maintained `preview.html` files, optionally accompanied by `docs.md` and reusable `styles.css`. Generation does not produce or overwrite previews.
|
|
22
|
+
|
|
23
|
+
## Configuration and build
|
|
24
|
+
|
|
25
|
+
A design directory has `config.json`:
|
|
26
|
+
|
|
27
|
+
```json
|
|
28
|
+
{
|
|
29
|
+
"system": { "name": "Example", "id": "example" },
|
|
30
|
+
"build": { "output": "public/design" }
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`system.name` names the showcase; `system.id` is lowercase kebab-case and forms the output directory. `build.output` is relative to the project directory (or an absolute path). The build writes exactly `[build.output]/[system.id]/theme.css`. `DESIGN_DIR` selects the design directory (default `.design`), whose parent is the project directory. `DESIGN_CONFIG` selects another config path without changing those directories.
|
|
35
|
+
|
|
36
|
+
The builder reads `tokens/tokens.json`, detects normalized or CSS-native data, emits custom properties and appends CSS files recursively from `components/`. `preview.css` is excluded because it contains specimen-only presentation. For CSS-native sources, `tokens/palettes.json` supplies optional `:root`/`.dark` custom properties, and `tokens/components.json` supplies optional component aliases and dark overrides. Normalized sources include their token groups and themes in `tokens.json`. Token references become CSS variable references. Component CSS must be standalone: Tailwind `@apply`, `@theme`, `@source`, and CSS `@import` are rejected. Relative asset URLs remain the component author's responsibility. Preview HTML, scripts, host runtime assets and application builds are not generated or updated.
|
|
37
|
+
|
|
38
|
+
The showcase reads `system.name` from configuration. Its token renderer detects normalized data (`primitive.color` and `semantic.color`) or Raketa CSS-native data (`blocks`). The latter projection reads `tokens/components.json` and a transient Tailwind build for status colors; its typography specimens use Raketa's documented defaults. Unknown or ambiguous token formats are rejected. `DESIGN.md` remains a design reference; configuration supplies the showcase name.
|
|
39
|
+
|
|
40
|
+
`/__showcase/preview.css` uses the CLI's bundled Tailwind compiler, design tokens and component/layout previews, independent of the host framework. It includes the generated theme when present. If previews also depend on a Tailwind-compatible stylesheet, set `"preview": { "css": "raketa/index.css" }` in `config.json` (path relative to the project). This is preview-only and does not alter production CSS. The stylesheet and its imports must be compatible with the CLI's Tailwind version; host plugins must be resolvable by the host. Run `generate` before serving to include the theme. Missing output returns 404 at `/__showcase/theme.css`.
|
|
41
|
+
|
|
42
|
+
Configuration, preview HTML and `_theme_preview.html` are trusted local inputs; do not expose the server to untrusted networks. Apart from shared chrome under `/__showcase/` and `/showcase/asset-grid.css`, the server serves files only within the design directory, plus the configured output at `/__showcase/theme.css`. The server watches the output directory for reloads when it exists at startup; restart after changing the output location or creating a previously missing directory. Theme selection and application-specific behavior must still be added to scaffolds.
|
|
43
|
+
|
|
44
|
+
Run `npm test` here for tooling behavior. Consumers should separately validate integration and preview appearance; the build does not change their production wiring.
|
|
45
|
+
|
|
46
|
+
## Publishing
|
|
47
|
+
|
|
48
|
+
The package is public on npm even though this repository is private. In npm package settings, add a GitHub Actions trusted publisher for organization `studioraketa`, repository `design-system-tools`, workflow filename `publish.yml`, with direct `npm publish` allowed and no environment name. The workflow uses GitHub OIDC rather than an npm token; Node 24 supplies the required npm 11.5.1 or later. Complete the first publish within two days of creating the trusted publisher. Private repositories do not generate npm provenance.
|
|
49
|
+
|
|
50
|
+
Update the package version and lockfile, then publish a GitHub release tagged with the exact version (for example, `1.0.2`); the workflow checks the tag, runs tests, and publishes to npm. Prereleases are not published. After a successful trusted publish, revoke the old npm publishing token and remove the `NPM_TOKEN` GitHub secret.
|
|
2
51
|
|
|
3
|
-
This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
|
package/build.mjs
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join, relative } from 'node:path';
|
|
3
|
+
import { tokenSource, themePath } from './config.mjs';
|
|
4
|
+
|
|
5
|
+
const validName = /^--[a-z][a-z0-9-]*$/;
|
|
6
|
+
const safeValue = value => {
|
|
7
|
+
const s = String(value);
|
|
8
|
+
if (!s || /[;{}\r\n]/.test(s)) throw new Error('Invalid CSS token value');
|
|
9
|
+
return s;
|
|
10
|
+
};
|
|
11
|
+
function cssName(path, native) {
|
|
12
|
+
const kebab = value => value.replaceAll('.', '-').replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
|
|
13
|
+
if (native && path.startsWith('primitive.color.')) return '--color-' + kebab(path.slice('primitive.color.'.length));
|
|
14
|
+
if (path.startsWith('semantic.color.')) return '--color-' + kebab(path.slice('semantic.color.'.length));
|
|
15
|
+
return '--' + kebab(path);
|
|
16
|
+
}
|
|
17
|
+
function serialize(value, native) {
|
|
18
|
+
if (typeof value === 'string') {
|
|
19
|
+
const ref = value.match(/^\{([a-zA-Z0-9.-]+)\}$/);
|
|
20
|
+
return ref ? `var(${cssName(ref[1], native)})` : safeValue(value);
|
|
21
|
+
}
|
|
22
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
|
23
|
+
if (Array.isArray(value) && value.every(v => typeof v === 'string')) return value.map(v => /^[a-z-]+$/i.test(v) ? v : JSON.stringify(v)).join(', ');
|
|
24
|
+
if (value && typeof value === 'object' && typeof value.unit === 'string' && Number.isFinite(value.value)) return safeValue(value.value + value.unit);
|
|
25
|
+
if (value?.colorSpace === 'srgb' && Array.isArray(value.components) && value.components.length === 3 && value.components.every(n => Number.isFinite(n) && n >= 0 && n <= 1)) return '#' + value.components.map(n => Math.round(n * 255).toString(16).padStart(2, '0')).join('');
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
function flattenTokens(group, native, path = [], output = {}) {
|
|
29
|
+
if (!group || typeof group !== 'object' || Array.isArray(group)) throw new Error('Invalid token group: ' + path.join('.'));
|
|
30
|
+
if (Object.hasOwn(group, '$value')) {
|
|
31
|
+
const value = serialize(group.$value, native);
|
|
32
|
+
if (value !== null) {
|
|
33
|
+
const name = cssName(path.join('.'), native);
|
|
34
|
+
if (!validName.test(name) || Object.hasOwn(output, name)) throw new Error('Invalid or duplicate token name: ' + name);
|
|
35
|
+
output[name] = value;
|
|
36
|
+
} else if (group.$value && typeof group.$value === 'object' && !Array.isArray(group.$value)) {
|
|
37
|
+
for (const [key, child] of Object.entries(group.$value)) flattenTokens({ $value: child }, native, [...path, key], output);
|
|
38
|
+
} else throw new Error('Unsupported token value: ' + path.join('.'));
|
|
39
|
+
return output;
|
|
40
|
+
}
|
|
41
|
+
for (const [key, child] of Object.entries(group)) if (!key.startsWith('$')) flattenTokens(child, native, [...path, key], output);
|
|
42
|
+
return output;
|
|
43
|
+
}
|
|
44
|
+
function block(selector, declarations) {
|
|
45
|
+
for (const [key, value] of Object.entries(declarations)) { if (!validName.test(key)) throw new Error('Invalid CSS token name: ' + key); safeValue(value); }
|
|
46
|
+
return selector + ' {\n' + Object.entries(declarations).map(([key, value]) => ` ${key}: ${value};`).join('\n') + '\n}\n';
|
|
47
|
+
}
|
|
48
|
+
async function jsonIfPresent(path) {
|
|
49
|
+
try { return JSON.parse(await readFile(path, 'utf8')); }
|
|
50
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
51
|
+
}
|
|
52
|
+
async function tokenCSS(designDir) {
|
|
53
|
+
const { input, type } = await tokenSource(designDir);
|
|
54
|
+
const native = type === 'raketa-css';
|
|
55
|
+
let css = '';
|
|
56
|
+
if (native) {
|
|
57
|
+
const extra = await jsonIfPresent(join(designDir, 'tokens/palettes.json')) || {};
|
|
58
|
+
for (const selector of Object.keys(extra)) if (![':root', '.dark'].includes(selector)) throw new Error('Unsupported palette selector: ' + selector);
|
|
59
|
+
const root = { ...(extra[':root'] || {}) };
|
|
60
|
+
let dark = { ...(extra['.dark'] || {}) };
|
|
61
|
+
const themedAliases = {};
|
|
62
|
+
for (const entry of input.blocks) {
|
|
63
|
+
if (!['@theme inline', '@theme', ':root', '.dark'].includes(entry.selector)) throw new Error('Unsupported token selector: ' + entry.selector);
|
|
64
|
+
const dest = entry.selector === '.dark' ? dark : root;
|
|
65
|
+
for (const [name, token] of Object.entries(entry.tokens)) {
|
|
66
|
+
if (token.$type !== 'string' || typeof token.$value !== 'string') throw new Error('Invalid CSS-native token: ' + name);
|
|
67
|
+
dest[name] = safeValue(token.$value);
|
|
68
|
+
if (entry.selector === '@theme inline') themedAliases[name] = dest[name];
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
css += block(':root', root) + block('.dark', { ...themedAliases, ...dark });
|
|
72
|
+
const components = await jsonIfPresent(join(designDir, 'tokens/components.json'));
|
|
73
|
+
if (components?.components) {
|
|
74
|
+
const baseRoles = flattenTokens(components.components, true, ['components']);
|
|
75
|
+
const darkRoles = components.themes?.dark?.components ? flattenTokens(components.themes.dark.components, true, ['components']) : {};
|
|
76
|
+
css += block(':root', baseRoles) + block('.dark', { ...baseRoles, ...darkRoles });
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
const base = Object.fromEntries(Object.entries(input).filter(([key]) => !key.startsWith('$') && key !== 'themes'));
|
|
80
|
+
css += block(':root', flattenTokens(base, false));
|
|
81
|
+
const themed = flattenTokens({ semantic: input.semantic, components: input.components || {} }, false);
|
|
82
|
+
css += block('.theme-light', themed);
|
|
83
|
+
for (const [name, values] of Object.entries(input.themes || {})) {
|
|
84
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name)) throw new Error('Invalid theme name: ' + name);
|
|
85
|
+
css += block(name === 'dark' ? '.dark' : '.theme-' + name, { ...themed, ...flattenTokens(values, false) });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return css;
|
|
89
|
+
}
|
|
90
|
+
async function styles(directory) {
|
|
91
|
+
let entries;
|
|
92
|
+
try { entries = await readdir(directory, { withFileTypes: true }); }
|
|
93
|
+
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
94
|
+
return (await Promise.all(entries.map(entry => {
|
|
95
|
+
const path = join(directory, entry.name);
|
|
96
|
+
if (entry.isDirectory()) return styles(path);
|
|
97
|
+
return entry.isFile() && entry.name.endsWith('.css') && entry.name !== 'preview.css' ? [path] : [];
|
|
98
|
+
}))).flat().sort();
|
|
99
|
+
}
|
|
100
|
+
export async function build(context) {
|
|
101
|
+
const output = themePath(context);
|
|
102
|
+
const dir = dirname(output);
|
|
103
|
+
let css = '/* Generated by design-tooling; edit the design sources instead. */\n' + await tokenCSS(context.designDir);
|
|
104
|
+
for (const path of await styles(join(context.designDir, 'components'))) {
|
|
105
|
+
const content = await readFile(path, 'utf8');
|
|
106
|
+
if (/@(?:apply|import|theme|source)\b/.test(content)) throw new Error('Component styles must be standalone CSS: ' + relative(context.designDir, path));
|
|
107
|
+
css += `\n/* ${relative(context.designDir, path).split('\\').join('/')} */\n` + content.trim() + '\n';
|
|
108
|
+
}
|
|
109
|
+
const existing = await lstat(output).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
110
|
+
if (existing && !existing.isFile()) throw new Error('Build output must be a regular file');
|
|
111
|
+
await mkdir(dir, { recursive: true });
|
|
112
|
+
await writeFile(output, css);
|
|
113
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Read-only projection for CSS-native Raketa token packages.
|
|
2
|
+
export function showcaseData(input, status, componentTokens) {
|
|
3
|
+
if (!input.blocks) return input;
|
|
4
|
+
const declarations = selector => {
|
|
5
|
+
const block = input.blocks.find(block => block.selector === selector);
|
|
6
|
+
if (!block?.tokens) throw new Error('Missing runtime token block: ' + selector);
|
|
7
|
+
return Object.fromEntries(Object.entries(block.tokens).map(([name, token]) => [name, token.$value]));
|
|
8
|
+
};
|
|
9
|
+
const palette = declarations('@theme');
|
|
10
|
+
const light = declarations(':root');
|
|
11
|
+
const dark = { ...light, ...declarations('.dark') };
|
|
12
|
+
function channels(value, variables, seen = []) {
|
|
13
|
+
const reference = value.match(/^var\((--[\w-]+)\)$/)?.[1];
|
|
14
|
+
if (reference) {
|
|
15
|
+
if (seen.includes(reference) || !variables[reference]) throw new Error('Missing or circular CSS color: ' + reference);
|
|
16
|
+
return channels(variables[reference], variables, [...seen, reference]);
|
|
17
|
+
}
|
|
18
|
+
if (/^\d+ \d+ \d+$/.test(value)) return value.split(' ').map(Number);
|
|
19
|
+
if (/^#[0-9a-f]{6}$/i.test(value)) return [1, 3, 5].map(offset => parseInt(value.slice(offset, offset + 2), 16));
|
|
20
|
+
// Preserve the runtime color-mix expression in tokens.json; only its swatch
|
|
21
|
+
// needs a derived sRGB value for the upstream renderer's color contract.
|
|
22
|
+
const mix = value.match(/^color-mix\(in srgb, rgb\(var\((--[\w-]+)\)\) ([\d.]+)%, (white|#[0-9a-f]{6})\)$/i);
|
|
23
|
+
if (mix) {
|
|
24
|
+
const fraction = Number(mix[2]) / 100;
|
|
25
|
+
const foreground = channels(`var(${mix[1]})`, variables, seen);
|
|
26
|
+
const background = channels(mix[3] === 'white' ? '#ffffff' : mix[3], variables, seen);
|
|
27
|
+
return foreground.map((channel, index) => channel * fraction + background[index] * (1 - fraction));
|
|
28
|
+
}
|
|
29
|
+
throw new Error('Unsupported showcase color expression: ' + value);
|
|
30
|
+
}
|
|
31
|
+
const color = rgb => ({ $type: 'color', $value: { colorSpace: 'srgb', components: rgb.map(value => value / 255), hex: '#' + rgb.map(value => Math.round(value).toString(16).padStart(2, '0')).join('') } });
|
|
32
|
+
const primitive = { color: {} };
|
|
33
|
+
primitive.color.brand = Object.fromEntries(Object.entries(light).filter(([name]) => /^--brand-\d+$/.test(name)).map(([name, value]) => [name.slice(8), color(channels(value, light))]));
|
|
34
|
+
primitive.color.zinc = {};
|
|
35
|
+
for (const [name, value] of Object.entries(palette)) {
|
|
36
|
+
const shade = name.match(/^--color-zinc-(\d+)$/)?.[1];
|
|
37
|
+
if (shade) primitive.color.zinc[shade] = color(channels(value, light));
|
|
38
|
+
}
|
|
39
|
+
for (const family of ['red', 'green', 'orange', 'yellow']) {
|
|
40
|
+
primitive.color[family] = Object.fromEntries(Object.entries(status).filter(([name]) => name.startsWith(family + '-')).map(([name, token]) => [name.slice(family.length + 1), token]));
|
|
41
|
+
}
|
|
42
|
+
primitive.color.base = { white: color([255, 255, 255]), black: color([0, 0, 0]) };
|
|
43
|
+
const derived = { color: { canvas: { light: color(channels(light['--raketa-canvas'], light)), dark: color(channels(dark['--raketa-canvas'], dark)) } } };
|
|
44
|
+
const alias = path => ({ $type: 'color', $value: `{primitive.color.${path}}` });
|
|
45
|
+
function reference(value, variables) {
|
|
46
|
+
const brand = value.match(/^var\(--brand-(\d+)\)$/)?.[1];
|
|
47
|
+
if (brand) return alias('brand.' + brand);
|
|
48
|
+
const rgb = channels(value, variables);
|
|
49
|
+
for (const [family, shades] of Object.entries(primitive.color)) {
|
|
50
|
+
for (const [shade, token] of Object.entries(shades)) {
|
|
51
|
+
if (token.$value?.components?.every((channel, index) => Math.abs(channel * 255 - rgb[index]) < 0.00001)) return alias(family + '.' + shade);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
throw new Error('No primitive for showcase color: ' + value);
|
|
55
|
+
}
|
|
56
|
+
function semantic(variables, theme) {
|
|
57
|
+
const values = {
|
|
58
|
+
foreground: alias(theme === 'light' ? 'zinc.950' : 'zinc.100'),
|
|
59
|
+
background: { $type: 'color', $value: '{derived.color.canvas.' + theme + '}' },
|
|
60
|
+
border: alias(theme === 'light' ? 'zinc.200' : 'zinc.800')
|
|
61
|
+
};
|
|
62
|
+
for (const name of ['surface', 'accent', 'accent-subtle', 'accent-foreground', 'action', 'action-foreground']) values[name] = reference(variables['--raketa-' + name], variables);
|
|
63
|
+
return values;
|
|
64
|
+
}
|
|
65
|
+
const font = { $type: 'fontFamily', $value: ['system-ui', 'sans-serif'] };
|
|
66
|
+
// Round specimen ratios for legible metadata; production line heights are unchanged.
|
|
67
|
+
const type = (size, lineHeight, weight = 400) => ({ $type: 'typography', $value: { fontFamily: '{foundation.font.ui}', fontSize: { value: size, unit: 'px' }, lineHeight: Number(lineHeight.toFixed(2)), fontWeight: weight, letterSpacing: { value: 0, unit: 'em' } } });
|
|
68
|
+
const scale = { 'text-4xl': [36, 40 / 36], 'text-xl': [20, 28 / 20], 'text-sm': [14, 20 / 14], 'text-xs': [12, 16 / 12] };
|
|
69
|
+
const typography = {};
|
|
70
|
+
// Raketa's documented default typography specimens; host CSS is not a design input.
|
|
71
|
+
for (const [name, utility, weight] of [['title-page', 'text-4xl', 700], ['title-header', 'text-xl', 700], ['title-section', 'text-xl', 600], ['title-subsection', 'text-sm', 600]]) {
|
|
72
|
+
const [size, lineHeight] = scale[utility];
|
|
73
|
+
typography[name] = type(size, lineHeight, weight);
|
|
74
|
+
}
|
|
75
|
+
typography['body-1'] = type(14, 20 / 14);
|
|
76
|
+
typography['text-sm'] = type(14, 20 / 14);
|
|
77
|
+
typography['text-xs'] = type(12, 16 / 12);
|
|
78
|
+
const dimension = value => ({ $type: 'dimension', $value: { value, unit: 'px' } });
|
|
79
|
+
return {
|
|
80
|
+
primitive,
|
|
81
|
+
derived,
|
|
82
|
+
semantic: { color: semantic(light, 'light') },
|
|
83
|
+
components: componentTokens.components,
|
|
84
|
+
themes: { dark: { semantic: { color: semantic(dark, 'dark') }, components: componentTokens.themes.dark.components } },
|
|
85
|
+
foundation: { font: { ui: font }, typography, sidebar: { desktop: dimension(197), narrow: dimension(150), collapsed: dimension(44), breakpoint: dimension(701) } }
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// The preview compiler includes full palettes; authored overrides win.
|
|
2
|
+
export function statusColors(css) {
|
|
3
|
+
const declarations = new Map([...css.matchAll(/--color-((?:green|yellow|orange|red)-\d+):([^;}]+)/g)].map(match => [match[1], match[2].trim()]));
|
|
4
|
+
const families = ['red', 'green', 'orange', 'yellow'];
|
|
5
|
+
const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
|
|
6
|
+
return Object.fromEntries(families.flatMap(family => shades.map(shade => {
|
|
7
|
+
const name = `${family}-${shade}`;
|
|
8
|
+
const value = declarations.get(name);
|
|
9
|
+
if (!value) throw new Error('Missing status color in compiled preview CSS: ' + name);
|
|
10
|
+
return [name, { $type: 'color', $value: value }];
|
|
11
|
+
})));
|
|
12
|
+
}
|
package/cli.mjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { mkdir, realpath, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { resolve, sep } from 'node:path';
|
|
4
|
+
import { loadConfig } from './config.mjs';
|
|
5
|
+
import { build } from './build.mjs';
|
|
6
|
+
|
|
7
|
+
const [command, ...args] = process.argv.slice(2);
|
|
8
|
+
if (command === '--help' || command === '-h' || !command) {
|
|
9
|
+
console.log('Usage: design <init|generate|serve|new>\n\n init Set up a design system and agent skill\n generate Build the design system CSS\n serve Start the local showcase\n new <component|layout> <name> Scaffold a pattern');
|
|
10
|
+
} else if (command === '--version' || command === '-v') {
|
|
11
|
+
const { readFile } = await import('node:fs/promises');
|
|
12
|
+
console.log(JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8')).version);
|
|
13
|
+
} else if (command === 'init') {
|
|
14
|
+
if (args.length) throw new Error('Unexpected arguments');
|
|
15
|
+
const { init } = await import('./init.mjs');
|
|
16
|
+
await init();
|
|
17
|
+
} else if (command === 'new') {
|
|
18
|
+
const [kind, name, ...extra] = args;
|
|
19
|
+
if (!['component', 'layout'].includes(kind) || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name || '') || extra.length) throw new Error('Usage: design new <component|layout> <kebab-case-name>');
|
|
20
|
+
const root = await realpath(resolve(process.env.DESIGN_DIR || '.design'));
|
|
21
|
+
const folder = resolve(root, kind === 'component' ? 'components' : 'layouts');
|
|
22
|
+
await mkdir(folder, { recursive: true });
|
|
23
|
+
const parent = await realpath(folder);
|
|
24
|
+
if (!parent.startsWith(root + sep)) throw new Error('Pattern directories must stay inside the design folder');
|
|
25
|
+
const target = resolve(parent, name);
|
|
26
|
+
try { await mkdir(target); } catch (error) {
|
|
27
|
+
if (error.code === 'EEXIST') throw new Error(`Refusing to overwrite existing path: ${target}`);
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
await writeFile(resolve(target, 'preview.html'), `<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${name}</title><link rel="stylesheet" href="/__showcase/theme.css"></head><body><main><h1>${name}</h1><p>Replace this placeholder with the pattern.</p></main></body></html>\n`, { flag: 'wx' });
|
|
32
|
+
await writeFile(resolve(target, 'docs.md'), `# ${name}\n\n## Purpose\nDescribe when to use this ${kind}.\n\n## Properties and states\nDocument content, defaults, variants and states.\n\n## Contract\nDocument accessibility, responsive behavior and integration.\n\n## Verification\nRecord verification and known gaps.\n`, { flag: 'wx' });
|
|
33
|
+
} catch (error) { await rm(target, { recursive: true, force: true }); throw error; }
|
|
34
|
+
console.log(`Created ${kind}: ${target}`);
|
|
35
|
+
} else if (command === 'generate') {
|
|
36
|
+
if (args.length) throw new Error('Unexpected arguments');
|
|
37
|
+
await build(await loadConfig());
|
|
38
|
+
} else if (command === 'serve') {
|
|
39
|
+
if (args.length) throw new Error('Unexpected arguments');
|
|
40
|
+
await import('./showcase/serve.mjs');
|
|
41
|
+
} else throw new Error('Usage: design <init|generate|serve|new>');
|
package/config.mjs
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { readFile, realpath } from 'node:fs/promises';
|
|
2
|
+
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import { showcaseData } from './catalog/css-native.mjs';
|
|
4
|
+
import { statusColors } from './catalog/status-colors.mjs';
|
|
5
|
+
import { previewCss } from './preview-css.mjs';
|
|
6
|
+
|
|
7
|
+
export async function loadConfig() {
|
|
8
|
+
const designDir = await realpath(resolve(process.env.DESIGN_DIR || '.design'));
|
|
9
|
+
const path = resolve(process.env.DESIGN_CONFIG || resolve(designDir, 'config.json'));
|
|
10
|
+
const config = JSON.parse(await readFile(path, 'utf8'));
|
|
11
|
+
if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error('Invalid design configuration');
|
|
12
|
+
return { config, designDir, projectDir: dirname(designDir) };
|
|
13
|
+
}
|
|
14
|
+
export function themePath({ config, projectDir }) {
|
|
15
|
+
const { system, build } = config;
|
|
16
|
+
if (!system || typeof system.name !== 'string' || !system.name.trim() || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(system.id || '')) throw new Error('system.name and kebab-case system.id are required');
|
|
17
|
+
if (!build || typeof build.output !== 'string' || !build.output.trim()) throw new Error('build.output is required');
|
|
18
|
+
return resolve(projectDir, build.output, system.id, 'theme.css');
|
|
19
|
+
}
|
|
20
|
+
export async function tokenSource(designDir) {
|
|
21
|
+
const input = JSON.parse(await readFile(resolve(designDir, 'tokens/tokens.json'), 'utf8'));
|
|
22
|
+
const cssNative = Array.isArray(input?.blocks);
|
|
23
|
+
const normalized = !!input?.primitive?.color && !!input?.semantic?.color;
|
|
24
|
+
if (cssNative === normalized) throw new Error('Unrecognized or ambiguous tokens/tokens.json format');
|
|
25
|
+
return { input, type: cssNative ? 'raketa-css' : 'tokens' };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function raketaInputs({ designDir }, input) {
|
|
29
|
+
const componentTokens = JSON.parse(await readFile(resolve(designDir, 'tokens/components.json'), 'utf8'));
|
|
30
|
+
return { input, componentTokens };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function catalog(context) {
|
|
34
|
+
const { input, type } = await tokenSource(context.designDir);
|
|
35
|
+
if (type === 'tokens') return input;
|
|
36
|
+
const { componentTokens } = await raketaInputs(context, input);
|
|
37
|
+
const status = statusColors(await previewCss(context));
|
|
38
|
+
return showcaseData(input, status, componentTokens);
|
|
39
|
+
}
|
package/init.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { lstat, mkdir, readFile, symlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
|
|
4
|
+
export async function init() {
|
|
5
|
+
const root = process.cwd();
|
|
6
|
+
const paths = ['.design', '.agents/skills/design-system', '.claude/skills/design-system', '.pi/skills/design-system'];
|
|
7
|
+
for (const path of paths) {
|
|
8
|
+
try {
|
|
9
|
+
await lstat(resolve(root, path));
|
|
10
|
+
throw new Error(`Refusing to overwrite existing path: ${path}`);
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if (error.code !== 'ENOENT') throw error;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
// Create the design directory exclusively; existing projects are never merged or overwritten.
|
|
16
|
+
await mkdir(resolve(root, '.design'));
|
|
17
|
+
for (const dir of ['tokens', 'components', 'layouts', 'rules', 'assets']) {
|
|
18
|
+
await mkdir(resolve(root, '.design', dir));
|
|
19
|
+
}
|
|
20
|
+
await writeFile(resolve(root, '.design/config.json'), JSON.stringify({ system: { name: 'My design system', id: 'my-design-system' }, build: { output: 'public/design' } }, null, 2) + '\n', { flag: 'wx' });
|
|
21
|
+
const tokens = { primitive: { color: { neutral: { white: { $type: 'color', $value: '#ffffff' }, black: { $type: 'color', $value: '#000000' } } } }, semantic: { color: { background: { $type: 'color', $value: '{primitive.color.neutral.white}' }, foreground: { $type: 'color', $value: '{primitive.color.neutral.black}' } } } };
|
|
22
|
+
await writeFile(resolve(root, '.design/tokens/tokens.json'), JSON.stringify(tokens, null, 2) + '\n', { flag: 'wx' });
|
|
23
|
+
await writeFile(resolve(root, '.design/DESIGN.md'), '# Design system\n\nReplace this starter with your design principles, conventions, and references.\n', { flag: 'wx' });
|
|
24
|
+
await mkdir(resolve(root, '.agents/skills/design-system'), { recursive: true });
|
|
25
|
+
await writeFile(resolve(root, '.agents/skills/design-system/SKILL.md'), await readFile(new URL('./skills/design-system/SKILL.md', import.meta.url)), { flag: 'wx' });
|
|
26
|
+
for (const agent of ['.claude', '.pi']) {
|
|
27
|
+
await mkdir(resolve(root, agent, 'skills'), { recursive: true });
|
|
28
|
+
await symlink('../../.agents/skills/design-system', resolve(root, agent, 'skills/design-system'), 'dir');
|
|
29
|
+
}
|
|
30
|
+
console.log('Initialized .design and installed the design-system skill.\n\nNext steps:\n 1. Update .design/config.json (system name, id, and output path).\n 2. Replace the starter tokens and document your system in .design/DESIGN.md and rules/.\n 3. Add patterns, run design generate and design serve, and wire the CSS into your app.');
|
|
31
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@raketa-cloud/design-cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.3",
|
|
4
|
+
"description": "CLI for building and previewing local design systems",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/studioraketa/design-system-tools.git"
|
|
8
|
+
},
|
|
9
|
+
"bin": {
|
|
10
|
+
"design": "cli.mjs"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"*.mjs",
|
|
14
|
+
"catalog/",
|
|
15
|
+
"showcase/",
|
|
16
|
+
"tokens/",
|
|
17
|
+
"skills/"
|
|
18
|
+
],
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"type": "module",
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=22"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
"./showcase/serve.mjs": "./showcase/serve.mjs",
|
|
28
|
+
"./showcase/assets.mjs": "./showcase/assets.mjs",
|
|
29
|
+
"./showcase/asset-grid.mjs": "./showcase/asset-grid.mjs",
|
|
30
|
+
"./cli.mjs": "./cli.mjs"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "node --test tests/*.test.mjs"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@tailwindcss/cli": "^4.3.5",
|
|
37
|
+
"tailwindcss": "^4.3.5"
|
|
38
|
+
}
|
|
39
|
+
}
|
package/preview-css.mjs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { readFile, access } from 'node:fs/promises';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import { themePath } from './config.mjs';
|
|
6
|
+
|
|
7
|
+
const require = createRequire(import.meta.url);
|
|
8
|
+
const cli = resolve(dirname(require.resolve('@tailwindcss/cli/package.json')), 'dist/index.mjs');
|
|
9
|
+
const tailwind = require.resolve('tailwindcss/index.css');
|
|
10
|
+
|
|
11
|
+
// Preview compilation is independent of the host application's toolchain.
|
|
12
|
+
export async function previewCss(context) {
|
|
13
|
+
const { projectDir, designDir, config } = context;
|
|
14
|
+
const tokens = JSON.parse(await readFile(resolve(designDir, 'tokens/tokens.json'), 'utf8'));
|
|
15
|
+
const extraCss = config?.preview?.css;
|
|
16
|
+
if (extraCss !== undefined && (typeof extraCss !== 'string' || !extraCss.trim())) throw new Error('preview.css must be a non-empty path');
|
|
17
|
+
const output = config ? themePath(context) : null;
|
|
18
|
+
let generated = false;
|
|
19
|
+
if (output) {
|
|
20
|
+
try { await access(output); generated = true; } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
21
|
+
}
|
|
22
|
+
const blocks = (tokens.blocks || []).filter(block => block.selector === '@theme' || block.selector === '@theme inline').map(block =>
|
|
23
|
+
`${block.selector} {\n${Object.entries(block.tokens).map(([name, token]) => ` ${name}: ${token.$value};`).join('\n')}\n}`
|
|
24
|
+
);
|
|
25
|
+
const input = [
|
|
26
|
+
`@import ${JSON.stringify(tailwind)} source(none);`,
|
|
27
|
+
...(generated ? [`@import ${JSON.stringify(output)};`] : []),
|
|
28
|
+
...(extraCss ? [`@import ${JSON.stringify(resolve(projectDir, extraCss))};`] : []),
|
|
29
|
+
...(typeof tokens.variant === 'string' ? [tokens.variant] : []),
|
|
30
|
+
...blocks,
|
|
31
|
+
`@source ${JSON.stringify(resolve(designDir, 'components'))};`,
|
|
32
|
+
`@source ${JSON.stringify(resolve(designDir, 'layouts'))};`,
|
|
33
|
+
'@source inline("bg-{red,green,orange,yellow}-{50,{100..900..100},950}");'
|
|
34
|
+
].join('\n');
|
|
35
|
+
return new Promise((resolvePromise, reject) => {
|
|
36
|
+
const child = spawn(process.execPath, [cli, '-i', '-'], { cwd: projectDir, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
37
|
+
let outputCss = '', errors = '';
|
|
38
|
+
child.stdout.setEncoding('utf8').on('data', chunk => { outputCss += chunk; });
|
|
39
|
+
child.stderr.setEncoding('utf8').on('data', chunk => { errors += chunk; });
|
|
40
|
+
child.on('error', reject);
|
|
41
|
+
child.stdin.on('error', error => { if (error.code !== 'EPIPE') reject(error); });
|
|
42
|
+
child.on('close', code => code === 0 ? resolvePromise(outputCss) : reject(new Error(`Preview CSS compilation failed (${code}): ${errors}`)));
|
|
43
|
+
child.stdin.end(input);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
.asset-more { margin-top: 20px; }
|
|
2
|
+
.asset-more > summary { width: fit-content; cursor: pointer; font-weight: 600; padding: 8px 0; }
|
|
3
|
+
.asset-more > summary:focus-visible { outline: 2px solid currentColor; outline-offset: 4px; }
|
|
4
|
+
.asset-more > summary .asset-more-hide { display: none; }
|
|
5
|
+
.asset-more[open] > summary .asset-more-show { display: none; }
|
|
6
|
+
.asset-more[open] > summary .asset-more-hide { display: inline; }
|
|
7
|
+
.asset-more > .asset-grid { margin-top: 16px; }
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Keep the reference grid; disclose large asset folders after the first ten.
|
|
2
|
+
export function assetGrid(cards) {
|
|
3
|
+
if (!cards.length) return '<p class="empty">No assets in this category.</p>';
|
|
4
|
+
const grid = items => '<div class="asset-grid">' + items.join('') + '</div>';
|
|
5
|
+
if (cards.length <= 10) return grid(cards);
|
|
6
|
+
return grid(cards.slice(0, 10)) + '<details class="asset-more"><summary><span class="asset-more-show">Show more (' + (cards.length - 10) + ')</span><span class="asset-more-hide">Hide</span></summary>' + grid(cards.slice(10)) + '</details>';
|
|
7
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { readdir, realpath } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
// Asset categories contain asset folders; each asset folder has exactly one file
|
|
6
|
+
// plus optional docs.md. Symlinks and nested folders are not asset files.
|
|
7
|
+
export async function scanAssets(root) {
|
|
8
|
+
let entries;
|
|
9
|
+
try { entries = await readdir(join(root, 'assets'), { withFileTypes: true }); }
|
|
10
|
+
catch (error) { if (error.code === 'ENOENT') return { categories: [], errors: [] }; throw error; }
|
|
11
|
+
const categoryFolders = entries.filter(entry => entry.isDirectory()).sort((a, b) => a.name.localeCompare(b.name));
|
|
12
|
+
const errors = [];
|
|
13
|
+
const categories = await Promise.all(categoryFolders.map(async category => {
|
|
14
|
+
const path = join('assets', category.name);
|
|
15
|
+
const members = await readdir(join(root, path), { withFileTypes: true });
|
|
16
|
+
const docs = members.some(entry => entry.name === 'docs.md' && entry.isFile());
|
|
17
|
+
const invalid = members.filter(entry => !(entry.name === 'docs.md' && entry.isFile()) && !entry.isDirectory()).map(entry => ({ name: entry.name, message: 'Place each asset in its own folder.' }));
|
|
18
|
+
const folders = members.filter(entry => entry.isDirectory()).sort((a, b) => a.name.localeCompare(b.name));
|
|
19
|
+
const assets = await Promise.all(folders.map(async folder => {
|
|
20
|
+
const itemPath = join(path, folder.name);
|
|
21
|
+
const contents = await readdir(join(root, itemPath), { withFileTypes: true });
|
|
22
|
+
const hasDocs = contents.some(entry => entry.name === 'docs.md' && entry.isFile());
|
|
23
|
+
const candidates = contents.filter(entry => entry.name !== 'docs.md' || !entry.isFile());
|
|
24
|
+
const valid = candidates.length === 1 && candidates[0].isFile();
|
|
25
|
+
return { name: folder.name, path: itemPath, docs: hasDocs, file: valid ? candidates[0].name : null, error: valid ? null : 'This folder must contain exactly one asset file and optional docs.md.' };
|
|
26
|
+
}));
|
|
27
|
+
return { name: category.name, path, docs, invalid, assets };
|
|
28
|
+
}));
|
|
29
|
+
for (const category of categories) {
|
|
30
|
+
for (const invalid of category.invalid) errors.push(join(category.path, invalid.name) + ': ' + invalid.message);
|
|
31
|
+
for (const asset of category.assets) if (asset.error) errors.push(asset.path + ': ' + asset.error);
|
|
32
|
+
}
|
|
33
|
+
return { categories, errors };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
37
|
+
if (!process.argv.includes('--check')) throw new Error('Usage: node assets.mjs --check');
|
|
38
|
+
const root = await realpath(resolve(process.env.DESIGN_DIR || join(dirname(fileURLToPath(import.meta.url)), '..')));
|
|
39
|
+
const { errors } = await scanAssets(root);
|
|
40
|
+
if (errors.length) {
|
|
41
|
+
console.error('Invalid asset structure:\n' + errors.map(error => '- ' + error).join('\n'));
|
|
42
|
+
process.exitCode = 1;
|
|
43
|
+
} else console.log('Asset structure is valid.');
|
|
44
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
:root {
|
|
2
|
+
color-scheme: dark;
|
|
3
|
+
--ui-background: #121212;
|
|
4
|
+
--ui-surface: #242424;
|
|
5
|
+
--ui-foreground: #f2f2f2;
|
|
6
|
+
--ui-muted: #c7c7c7;
|
|
7
|
+
--ui-border: #606060;
|
|
8
|
+
--ui-accent: #e5e5e5;
|
|
9
|
+
--ui-header-background: #080808;
|
|
10
|
+
--ui-header-foreground: #fafafa;
|
|
11
|
+
--ui-header-muted: #bdbdbd;
|
|
12
|
+
--ui-group-background: #303030;
|
|
13
|
+
--ui-dark-preview: #080808;
|
|
14
|
+
--ui-font: system-ui, sans-serif;
|
|
15
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
:root {
|
|
2
|
+
color-scheme: light;
|
|
3
|
+
--ui-background: #f7f7f7;
|
|
4
|
+
--ui-surface: #ffffff;
|
|
5
|
+
--ui-foreground: #171717;
|
|
6
|
+
--ui-muted: #525252;
|
|
7
|
+
--ui-border: #d4d4d4;
|
|
8
|
+
--ui-accent: #262626;
|
|
9
|
+
--ui-header-background: #ffffff;
|
|
10
|
+
--ui-header-foreground: #000000;
|
|
11
|
+
--ui-group-background: #eeeeee;
|
|
12
|
+
--ui-dark-preview: #171717;
|
|
13
|
+
--ui-font: system-ui, sans-serif;
|
|
14
|
+
}
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { watch } from 'node:fs';
|
|
3
|
+
import { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';
|
|
4
|
+
import { dirname, extname, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { resolveThemeDetails, cssName } from '../tokens/themes.mjs';
|
|
7
|
+
import { scanAssets } from './assets.mjs';
|
|
8
|
+
import { assetGrid } from './asset-grid.mjs';
|
|
9
|
+
import { loadConfig, catalog, themePath } from '../config.mjs';
|
|
10
|
+
import { previewCss } from '../preview-css.mjs';
|
|
11
|
+
const toolDir = dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
const context = await loadConfig();
|
|
13
|
+
const root = context.designDir;
|
|
14
|
+
const preset = process.env.SHOWCASE_PRESET || 'default';
|
|
15
|
+
if (!/^[a-z][a-z0-9-]*$/.test(preset)) throw new Error('Invalid SHOWCASE_PRESET');
|
|
16
|
+
async function findPreset() {
|
|
17
|
+
for (const directory of [join(root, 'showcase-presets'), join(toolDir, 'presets')]) {
|
|
18
|
+
try {
|
|
19
|
+
const presetRoot = await realpath(directory);
|
|
20
|
+
if (directory === join(root, 'showcase-presets') && !presetRoot.startsWith(root + sep)) throw new Error('Project presets must stay inside the design folder');
|
|
21
|
+
const path = await realpath(join(presetRoot, preset + '.css'));
|
|
22
|
+
if (!path.startsWith(presetRoot + sep)) throw new Error('Preset must stay inside its presets directory');
|
|
23
|
+
return path;
|
|
24
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
25
|
+
}
|
|
26
|
+
throw new Error('Unknown showcase preset: ' + preset);
|
|
27
|
+
}
|
|
28
|
+
await findPreset();
|
|
29
|
+
const port = Number(process.env.PORT || 4174);
|
|
30
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('PORT must be between 1 and 65535');
|
|
31
|
+
const escape = value => String(value).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
32
|
+
const urlFor = path => '/' + path.split(sep).map(encodeURIComponent).join('/');
|
|
33
|
+
async function designName() {
|
|
34
|
+
const name = (await loadConfig()).config.system?.name;
|
|
35
|
+
if (typeof name !== 'string' || !name.trim()) throw new Error('system.name is required');
|
|
36
|
+
return name.trim();
|
|
37
|
+
}
|
|
38
|
+
async function optionalFontsLink() {
|
|
39
|
+
try {
|
|
40
|
+
return (await stat(join(root, 'showcase-fonts.css'))).isFile() ? '<link rel="stylesheet" href="/showcase-fonts.css">' : '';
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error.code === 'ENOENT') return '';
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function files(folder) {
|
|
48
|
+
const start = join(root, folder);
|
|
49
|
+
async function walk(dir) {
|
|
50
|
+
let entries;
|
|
51
|
+
try { entries = await readdir(dir, { withFileTypes: true }); }
|
|
52
|
+
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
53
|
+
const nested = await Promise.all(entries.map(async entry => {
|
|
54
|
+
const path = join(dir, entry.name);
|
|
55
|
+
if (entry.isDirectory()) return walk(path);
|
|
56
|
+
return entry.isFile() ? [relative(root, path)] : [];
|
|
57
|
+
}));
|
|
58
|
+
return nested.flat();
|
|
59
|
+
}
|
|
60
|
+
return (await walk(start)).sort((a, b) => a.localeCompare(b));
|
|
61
|
+
}
|
|
62
|
+
function tokensIn(group, path = []) {
|
|
63
|
+
if (!group || typeof group !== 'object') return [];
|
|
64
|
+
if (Object.hasOwn(group, '$value')) return [{ path: path.join('.'), token: group }];
|
|
65
|
+
return Object.entries(group).filter(([key]) => !key.startsWith('$')).flatMap(([key, value]) => tokensIn(value, [...path, key]));
|
|
66
|
+
}
|
|
67
|
+
function resolveValue(data, token, seen = []) {
|
|
68
|
+
const value = token?.$value;
|
|
69
|
+
if (typeof value === 'string' && /^\{[^{}]+\}$/.test(value)) {
|
|
70
|
+
const path = value.slice(1, -1);
|
|
71
|
+
if (seen.includes(path)) return '[circular reference]';
|
|
72
|
+
const target = path.split('.').reduce((obj, part) => obj?.[part], data);
|
|
73
|
+
return target ? resolveValue(data, target, [...seen, path]) : '[missing reference]';
|
|
74
|
+
}
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
function format(value) {
|
|
78
|
+
if (value == null) return '—';
|
|
79
|
+
if (typeof value !== 'object') return String(value);
|
|
80
|
+
if (Array.isArray(value)) return value.join(', ');
|
|
81
|
+
if (value.colorSpace === 'srgb' && /^#[0-9a-f]{6}$/i.test(value.hex || '')) return value.hex;
|
|
82
|
+
if (value.colorSpace === 'srgb' && Array.isArray(value.components) && value.components.length === 3 && value.components.every(n => Number.isFinite(n) && n >= 0 && n <= 1)) return 'rgb(' + value.components.map(n => Math.round(n * 255)).join(' ') + ')';
|
|
83
|
+
if ('value' in value && 'unit' in value) return value.value + value.unit;
|
|
84
|
+
return JSON.stringify(value);
|
|
85
|
+
}
|
|
86
|
+
function isColor(value) {
|
|
87
|
+
return /^#[0-9a-f]{6}$/i.test(value || '') || /^rgb\(\d+ \d+ \d+\)$/.test(value || '') || /^oklch\((?:\d*\.)?\d+%? (?:\d*\.)?\d+ (?:\d*\.)?\d+\)$/.test(value || '');
|
|
88
|
+
}
|
|
89
|
+
function colorChip(value) {
|
|
90
|
+
return isColor(value) ? '<span class="color-chip" style="background:' + escape(value) + '" role="img" aria-label="Color ' + escape(value) + '" title="' + escape(value) + '"></span>' : '';
|
|
91
|
+
}
|
|
92
|
+
function primitiveReference(detail) {
|
|
93
|
+
if (!detail) return '—';
|
|
94
|
+
const reference = detail.primitive.replace(/^primitive\.color\./, '');
|
|
95
|
+
return '<span class="matrix-value">' + colorChip(detail.value) + '<code title="' + escape('{' + detail.primitive + '}') + '">' + escape(reference) + '</code></span>';
|
|
96
|
+
}
|
|
97
|
+
function primitivePalette(data) {
|
|
98
|
+
const groups = Object.entries(data.primitive?.color || {}).filter(([key]) => !key.startsWith('$'));
|
|
99
|
+
if (!groups.length) return '<p class="empty">No primitive colors defined.</p>';
|
|
100
|
+
return groups.map(([name, group]) => {
|
|
101
|
+
const shades = tokensIn(group).sort((a, b) => a.path.localeCompare(b.path, undefined, { numeric: true }));
|
|
102
|
+
const cells = shades.map(({ path, token }) => {
|
|
103
|
+
const value = format(resolveValue(data, token));
|
|
104
|
+
const style = isColor(value) ? ' style="background:' + escape(value) + '"' : '';
|
|
105
|
+
return '<div class="palette-shade"><div class="palette-swatch"' + style + '></div><strong>' + escape(path || name) + '</strong><code>' + escape(value) + '</code></div>';
|
|
106
|
+
});
|
|
107
|
+
return '<div class="palette-group"><h4>' + escape(name) + '</h4><div class="palette-scroll"><div class="palette-row">' + cells.join('') + '</div></div></div>';
|
|
108
|
+
}).join('');
|
|
109
|
+
}
|
|
110
|
+
function themeMatrix(themeSets) {
|
|
111
|
+
const allKeys = [...new Set(themeSets.flatMap(([, colors]) => Object.keys(colors)))];
|
|
112
|
+
const groups = new Map();
|
|
113
|
+
for (const key of allKeys) {
|
|
114
|
+
const parts = key.split('.');
|
|
115
|
+
const label = key.startsWith('semantic.color.') ? 'Global' : parts.slice(0, 2).join('.');
|
|
116
|
+
if (!groups.has(label)) groups.set(label, []);
|
|
117
|
+
groups.get(label).push(key);
|
|
118
|
+
}
|
|
119
|
+
const head = themeSets.map(([name]) => '<th scope="col">' + escape(name === 'light' ? 'Default' : name) + '</th>').join('');
|
|
120
|
+
const rows = [...groups].flatMap(([title, keys]) => ['<tr class="matrix-group"><th colspan="' + (themeSets.length + 1) + '">' + escape(title) + '</th></tr>', ...keys.map(key => '<tr><th scope="row">' + escape(key) + '</th>' + themeSets.map(([, colors]) => {
|
|
121
|
+
return '<td>' + primitiveReference(colors[key]) + '</td>';
|
|
122
|
+
}).join('') + '</tr>')]);
|
|
123
|
+
return '<div class="table-wrap"><table class="theme-matrix"><thead><tr><th scope="col">Token</th>' + head + '</tr></thead><tbody>' + rows.join('') + '</tbody></table></div>';
|
|
124
|
+
}
|
|
125
|
+
async function exampleIndex(folder) {
|
|
126
|
+
const examples = (await files(folder)).filter(path => /(?:^|\/)preview\.html$/i.test(path));
|
|
127
|
+
if (!examples.length) return '<p class="empty">No ' + escape(folder) + ' yet.</p>';
|
|
128
|
+
const items = await Promise.all(examples.map(async path => {
|
|
129
|
+
const companion = join(dirname(path), 'docs.md');
|
|
130
|
+
const markdown = await readFile(join(root, companion), 'utf8').catch(error => { if (error.code === 'ENOENT') return ''; throw error; });
|
|
131
|
+
const name = dirname(path).split(sep).pop().replace(/[-_]/g, ' ');
|
|
132
|
+
const title = markdown.match(/^#\s+(.+)$/m)?.[1] || name;
|
|
133
|
+
return '<li><a class="example-title" href="' + urlFor(path) + '">' + escape(title) + '</a><span class="links"><a href="' + urlFor(path) + '">Preview ↗</a>' + (markdown ? '<a href="' + urlFor(companion) + '">Docs ↗</a>' : '') + '</span></li>';
|
|
134
|
+
}));
|
|
135
|
+
return '<ul class="example-list">' + items.join('') + '</ul>';
|
|
136
|
+
}
|
|
137
|
+
async function assetIndex() {
|
|
138
|
+
const { categories } = await scanAssets(root);
|
|
139
|
+
if (!categories.length) return '<p class="empty">No asset categories included.</p>';
|
|
140
|
+
return categories.map(category => {
|
|
141
|
+
const title = category.name.replace(/[-_]/g, ' ');
|
|
142
|
+
const warnings = category.invalid.map(entry => '<p class="asset-warning">' + escape(entry.name) + ': ' + escape(entry.message) + '</p>').join('');
|
|
143
|
+
const cards = category.assets.map(asset => {
|
|
144
|
+
const label = asset.name.replace(/[-_]/g, ' ');
|
|
145
|
+
if (asset.error) return '<p class="asset-warning">' + escape(label) + ': ' + escape(asset.error) + '</p>';
|
|
146
|
+
const file = asset.file;
|
|
147
|
+
const href = urlFor(join(asset.path, file));
|
|
148
|
+
const image = /\.(svg|png|jpe?g|webp|gif|bmp|avif|ico)$/i.test(file);
|
|
149
|
+
const preview = image
|
|
150
|
+
? '<div class="asset-preview"><img src="' + href + '" alt=""></div>'
|
|
151
|
+
: '<div class="asset-preview asset-file"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="asset-download-icon" aria-hidden="true" focusable="false"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" /></svg></div>';
|
|
152
|
+
const description = escape(label + ' (' + file + ')');
|
|
153
|
+
const action = image
|
|
154
|
+
? '<a href="' + href + '" target="_blank" rel="noopener noreferrer" aria-label="Open ' + description + ' in a new tab">Open ↗</a>'
|
|
155
|
+
: '<a href="' + href + '" download aria-label="Download ' + description + '">Download</a>';
|
|
156
|
+
return '<article class="asset">' + preview + '<div class="asset-details"><strong>' + escape(label) + '</strong><span class="asset-filename">' + escape(file) + '</span><div class="asset-actions">' + action + (asset.docs ? '<a href="' + urlFor(join(asset.path, 'docs.md')) + '" aria-label="Read usage rules for ' + description + '">Docs</a>' : '') + '</div></div></article>';
|
|
157
|
+
});
|
|
158
|
+
const docsLink = category.docs ? '<p class="asset-category-docs"><a href="' + urlFor(join(category.path, 'docs.md')) + '">Usage rules</a></p>' : '';
|
|
159
|
+
return '<section class="asset-category"><h3>' + escape(title) + '</h3>' + docsLink + warnings + assetGrid(cards) + '</section>';
|
|
160
|
+
}).join('');
|
|
161
|
+
}
|
|
162
|
+
function otherTable(data) {
|
|
163
|
+
const rows = Object.entries(data.foundation || {}).filter(([name]) => !name.startsWith('$') && !['font', 'typography'].includes(name)).flatMap(([name, group]) => tokensIn(group, [name]));
|
|
164
|
+
if (!rows.length) return '<p class="empty">No other tokens defined.</p>';
|
|
165
|
+
return '<div class="table-wrap"><table class="other-table"><thead><tr><th scope="col">Key</th><th scope="col">Value</th></tr></thead><tbody>' + rows.map(({path, token}) => '<tr><th scope="row"><code>' + escape(path) + '</code></th><td><code>' + escape(format(resolveValue(data, token))) + '</code></td></tr>').join('') + '</tbody></table></div>';
|
|
166
|
+
}
|
|
167
|
+
function typographyStyle(data, token) {
|
|
168
|
+
const value = token?.$value || {};
|
|
169
|
+
let family = value.fontFamily;
|
|
170
|
+
if (typeof family === 'string' && /^\{[^{}]+\}$/.test(family)) {
|
|
171
|
+
const target = family.slice(1, -1).split('.').reduce((obj, part) => obj?.[part], data);
|
|
172
|
+
family = target ? resolveValue(data, target) : [];
|
|
173
|
+
}
|
|
174
|
+
if (!Array.isArray(family)) family = family ? [family] : [];
|
|
175
|
+
const safeFamily = family.filter(name => typeof name === 'string' && /^[a-z0-9 -]+$/i.test(name)).map(name => /^(serif|sans-serif|monospace|system-ui)$/i.test(name) ? name : "'" + name + "'").join(', ');
|
|
176
|
+
const size = value.fontSize;
|
|
177
|
+
const fontSize = size && Number.isFinite(size.value) && size.value > 0 && ['px', 'rem'].includes(size.unit) ? size.value + size.unit : 'inherit';
|
|
178
|
+
const weight = Number.isFinite(value.fontWeight) && value.fontWeight >= 1 && value.fontWeight <= 1000 ? value.fontWeight : 400;
|
|
179
|
+
const lineHeight = Number.isFinite(value.lineHeight) && value.lineHeight > 0 ? value.lineHeight : 1.5;
|
|
180
|
+
return { family, size, lineHeight, style: 'font-family:' + (safeFamily || 'sans-serif') + ';font-size:' + fontSize + ';font-weight:' + weight + ';line-height:' + lineHeight };
|
|
181
|
+
}
|
|
182
|
+
function typographyPreview(data) {
|
|
183
|
+
const entries = tokensIn(data.foundation?.typography);
|
|
184
|
+
if (!entries.length) return '<p class="empty">No typography tokens defined.</p>';
|
|
185
|
+
const samples = entries.map(({path, token}) => {
|
|
186
|
+
const { family, size, lineHeight, style } = typographyStyle(data, token);
|
|
187
|
+
const text = path.split('.').at(-1).startsWith('body-') ? 'The quick brown fox jumps over the lazy dog. A quiet moment can make room for new perspectives and a clearer sense of what matters. With thoughtful support, we can explore the challenges in front of us, understand our experiences and find a way forward at our own pace.' : 'The quick brown fox jumps over the lazy dog.';
|
|
188
|
+
return '<div class="type-row"><div class="type-meta"><strong>' + escape(path) + '</strong><span>' + escape(format(size)) + ' / ' + escape(lineHeight) + '</span><span>' + escape(family.join(', ')) + '</span></div><p class="type-sample" style="' + escape(style) + '">' + escape(text) + '</p></div>';
|
|
189
|
+
});
|
|
190
|
+
return '<div class="type-scale">' + samples.join('') + '</div>';
|
|
191
|
+
}
|
|
192
|
+
function themePreview(name, details, snippet) {
|
|
193
|
+
const entries = Object.entries(details).map(([path, detail]) => [cssName(path), detail.value]);
|
|
194
|
+
if (entries.some(([key, value]) => !/^--[a-zA-Z_][a-zA-Z0-9_-]*$/.test(key) || !isColor(value))) throw new Error('Theme contains an invalid CSS variable or color');
|
|
195
|
+
if (new Set(entries.map(([key]) => key)).size !== entries.length) throw new Error('Token paths collide as CSS variable names');
|
|
196
|
+
const vars = entries.map(([key, value]) => key + ':' + value).join(';');
|
|
197
|
+
return '<article class="theme-block"><h3>' + escape(name) + '</h3><div class="theme-preview" style="' + escape(vars) + '">' + snippet + '</div></article>';
|
|
198
|
+
}
|
|
199
|
+
async function showcase() {
|
|
200
|
+
const data = await catalog(await loadConfig());
|
|
201
|
+
const [components, layouts, assets, name, fontsLink, snippet] = await Promise.all([exampleIndex('components'), exampleIndex('layouts'), assetIndex(), designName(), optionalFontsLink(), readFile(join(root, '_theme_preview.html'), 'utf8').catch(error => { if (error.code === 'ENOENT') return null; throw error; })]);
|
|
202
|
+
const themeSets = Object.entries(resolveThemeDetails(data));
|
|
203
|
+
const themes = snippet === null ? '<p class="empty">Add _theme_preview.html to preview themes.</p>' : '<div class="theme-previews">' + themeSets.map(([name, details]) => themePreview(name === 'light' ? 'Default' : name, details, snippet)).join('') + '</div>';
|
|
204
|
+
const typography = typographyPreview(data);
|
|
205
|
+
const foundation = otherTable(data);
|
|
206
|
+
const title = name === 'Design system' ? name : name + ' design system';
|
|
207
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(title)}</title><link rel="stylesheet" href="/__showcase/preset.css"><link rel="stylesheet" href="/__showcase/showcase.css"><link rel="stylesheet" href="/showcase/asset-grid.css">${fontsLink}</head><body><header class="masthead"><div class="shell"><h1>${name === 'Design system' ? 'Design system' : escape(name) + '<br>design system'}</h1></div></header><nav class="showcase-nav" aria-label="Showcase sections"><div class="shell nav-links"><a href="#foundations">Type Scale</a><a href="#colors">Colors</a><a href="#semantic-colors">Semantic Colors</a><a href="#themes">Themes</a><a href="#other">Other</a><a href="#assets">Assets</a><a href="#components">Components</a><a href="#layouts">Layouts</a></div></nav><main class="shell"><section id="foundations"><div class="section-head"><h2>Type Scale</h2></div>${typography}</section><section id="colors"><div class="section-head"><h2>Colors</h2></div><h3>Primitive colors</h3>${primitivePalette(data)}<h3 id="semantic-colors">Semantic Colors</h3>${themeMatrix(themeSets)}</section><section id="themes"><div class="section-head"><h2>Themes</h2></div>${themes}</section><section id="other"><div class="section-head"><h2>Other</h2></div>${foundation}</section><section id="assets"><div class="section-head"><h2>Assets</h2></div>${assets}</section><section id="components"><div class="section-head"><h2>Components</h2></div>${components}</section><section id="layouts"><div class="section-head"><h2>Layouts</h2></div>${layouts}</section></main><footer><div class="shell">${escape(title)} <span>·</span> <a href="/DESIGN.md">Read DESIGN.md</a></div></footer></body></html>`;
|
|
208
|
+
}
|
|
209
|
+
const mime = { '.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.md': 'text/plain; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.bmp': 'image/bmp', '.avif': 'image/avif', '.ico': 'image/x-icon', '.pdf': 'application/pdf', '.otf': 'font/otf', '.ttf': 'font/ttf', '.woff': 'font/woff', '.woff2': 'font/woff2' };
|
|
210
|
+
const clients = new Set();
|
|
211
|
+
let reloadTimer;
|
|
212
|
+
function scheduleReload() {
|
|
213
|
+
clearTimeout(reloadTimer);
|
|
214
|
+
reloadTimer = setTimeout(() => { for (const client of clients) client.write('event: reload\ndata: changed\n\n'); }, 150);
|
|
215
|
+
}
|
|
216
|
+
for (const directory of [root, ...(!toolDir.startsWith(root + sep) && toolDir !== root ? [toolDir] : [])]) {
|
|
217
|
+
const watcher = watch(directory, { recursive: true }, scheduleReload);
|
|
218
|
+
watcher.on('error', error => console.error('Live reload watcher failed:', error));
|
|
219
|
+
}
|
|
220
|
+
// Watch the one configured output directory; theme generation occurs outside .design.
|
|
221
|
+
try {
|
|
222
|
+
const outputDir = dirname(themePath(context));
|
|
223
|
+
if (!outputDir.startsWith(root + sep) && outputDir !== root) {
|
|
224
|
+
const watcher = watch(outputDir, (event, name) => { if (!name || String(name) === 'theme.css') scheduleReload(); });
|
|
225
|
+
watcher.on('error', error => console.error('Theme watcher failed:', error));
|
|
226
|
+
}
|
|
227
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
228
|
+
const reloadScript = '<script src="/__showcase/reload.js" defer></script>';
|
|
229
|
+
function withReload(html) {
|
|
230
|
+
return /<\/body\s*>/i.test(html) ? html.replace(/<\/body\s*>/i, reloadScript + '</body>') : html + reloadScript;
|
|
231
|
+
}
|
|
232
|
+
createServer(async (req, res) => {
|
|
233
|
+
try {
|
|
234
|
+
if (!['GET', 'HEAD'].includes(req.method)) { res.writeHead(405, { Allow: 'GET, HEAD' }); return res.end(); }
|
|
235
|
+
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
|
|
236
|
+
if (pathname === '/__showcase/events') {
|
|
237
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' });
|
|
238
|
+
if (req.method === 'HEAD') return res.end();
|
|
239
|
+
res.write(': connected\n\n');
|
|
240
|
+
clients.add(res);
|
|
241
|
+
req.on('close', () => clients.delete(res));
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (pathname === '/__showcase/reload.js') {
|
|
245
|
+
const script = await readFile(join(toolDir, 'reload.js'));
|
|
246
|
+
res.writeHead(200, { 'Content-Type': mime['.js'], 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
247
|
+
return res.end(req.method === 'HEAD' ? undefined : script);
|
|
248
|
+
}
|
|
249
|
+
if (pathname === '/') {
|
|
250
|
+
const html = await showcase();
|
|
251
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
252
|
+
return res.end(req.method === 'HEAD' ? undefined : withReload(html));
|
|
253
|
+
}
|
|
254
|
+
if (pathname === '/__showcase/theme.css') {
|
|
255
|
+
const output = themePath(await loadConfig());
|
|
256
|
+
if (!(await lstat(output)).isFile()) { res.writeHead(404); return res.end('Not found'); }
|
|
257
|
+
const css = await readFile(output);
|
|
258
|
+
res.writeHead(200, { 'Content-Type': mime['.css'], 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
259
|
+
return res.end(req.method === 'HEAD' ? undefined : css);
|
|
260
|
+
}
|
|
261
|
+
if (pathname === '/__showcase/preview.css') {
|
|
262
|
+
const css = await previewCss(await loadConfig());
|
|
263
|
+
res.writeHead(200, { 'Content-Type': mime['.css'], 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
264
|
+
return res.end(req.method === 'HEAD' ? undefined : css);
|
|
265
|
+
}
|
|
266
|
+
if (pathname === '/showcase/asset-grid.css') {
|
|
267
|
+
const css = await readFile(join(toolDir, 'asset-grid.css'));
|
|
268
|
+
res.writeHead(200, { 'Content-Type': mime['.css'], 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
269
|
+
return res.end(req.method === 'HEAD' ? undefined : css);
|
|
270
|
+
}
|
|
271
|
+
if (pathname === '/__showcase/showcase.css' || pathname === '/__showcase/preset.css') {
|
|
272
|
+
const path = pathname.endsWith('/preset.css') ? await findPreset() : join(toolDir, 'showcase.css');
|
|
273
|
+
const css = await readFile(path);
|
|
274
|
+
res.writeHead(200, { 'Content-Type': 'text/css; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
275
|
+
return res.end(req.method === 'HEAD' ? undefined : css);
|
|
276
|
+
}
|
|
277
|
+
if (pathname.includes('\0')) { res.writeHead(400); return res.end('Bad request'); }
|
|
278
|
+
const candidate = resolve(root, '.' + pathname);
|
|
279
|
+
if (candidate !== root && !candidate.startsWith(root + sep)) { res.writeHead(403); return res.end('Forbidden'); }
|
|
280
|
+
const path = await realpath(candidate);
|
|
281
|
+
if (!path.startsWith(root + sep) || !(await stat(path)).isFile()) { res.writeHead(404); return res.end('Not found'); }
|
|
282
|
+
const data = await readFile(path);
|
|
283
|
+
const extension = extname(path).toLowerCase();
|
|
284
|
+
res.writeHead(200, { 'Content-Type': mime[extension] || 'application/octet-stream', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
285
|
+
res.end(req.method === 'HEAD' ? undefined : ['.html', '.htm'].includes(extension) ? withReload(data.toString('utf8')) : data);
|
|
286
|
+
} catch (error) {
|
|
287
|
+
const missing = error.code === 'ENOENT' || error.code === 'ENOTDIR';
|
|
288
|
+
res.writeHead(missing ? 404 : 500, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
289
|
+
res.end(missing ? 'Not found' : 'Could not generate the showcase; see the server log.');
|
|
290
|
+
if (!missing) console.error(error);
|
|
291
|
+
}
|
|
292
|
+
}).listen(port, '127.0.0.1', () => console.log('Design showcase: http://127.0.0.1:' + port));
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
* { box-sizing: border-box; }
|
|
2
|
+
html { scroll-behavior: smooth; scroll-padding-top: 4rem; }
|
|
3
|
+
body { margin: 0; background: var(--ui-background); color: var(--ui-foreground); font: 15px/1.55 var(--ui-font); }
|
|
4
|
+
.shell { width: min(1180px, 90%); margin: auto; }
|
|
5
|
+
a { color: inherit; text-underline-offset: 4px; }
|
|
6
|
+
a:focus-visible, button:focus-visible { outline: 3px solid var(--ui-accent); outline-offset: 3px; }
|
|
7
|
+
.masthead { background: var(--ui-header-background); color: var(--ui-header-foreground); padding: 80px 0 48px; }
|
|
8
|
+
.masthead h1 { font-size: clamp(40px, 6vw, 72px); font-weight: 650; letter-spacing: -.04em; line-height: 1.1; margin: 0; overflow-wrap: anywhere; }
|
|
9
|
+
.showcase-nav { position: sticky; top: 0; z-index: 10; background: var(--ui-header-background); color: var(--ui-header-foreground); border-bottom: 1px solid var(--ui-border); }
|
|
10
|
+
.nav-links { display: flex; align-items: center; gap: 28px; overflow-x: auto; white-space: nowrap; }
|
|
11
|
+
.nav-links a { flex: none; padding: 18px 0; text-decoration: none; font-size: 13px; font-weight: 600; }
|
|
12
|
+
.nav-links a:hover { text-decoration: underline; }
|
|
13
|
+
.nav-links a:focus-visible { outline-color: var(--ui-header-foreground); outline-offset: -3px; }
|
|
14
|
+
main > section { padding: 72px 0; border-bottom: 1px solid var(--ui-border); }
|
|
15
|
+
.section-head { margin-bottom: 36px; }
|
|
16
|
+
.section-head h2 { font-size: clamp(30px, 4vw, 42px); font-weight: 650; letter-spacing: -.03em; line-height: 1.2; margin: 0; }
|
|
17
|
+
h3 { font-size: 16px; margin: 35px 0 16px; }
|
|
18
|
+
.empty, .note { color: var(--ui-muted); }
|
|
19
|
+
.palette-group { margin: 24px 0 30px; }
|
|
20
|
+
.palette-group h4 { margin: 0 0 10px; font-size: 14px; text-transform: capitalize; }
|
|
21
|
+
.palette-scroll, .table-wrap { overflow-x: auto; }
|
|
22
|
+
.palette-scroll { padding-bottom: 6px; }
|
|
23
|
+
.palette-row { display: flex; gap: 5px; min-width: max-content; }
|
|
24
|
+
.palette-shade { width: 84px; min-width: 84px; }
|
|
25
|
+
.palette-swatch { height: 68px; border: 1px solid var(--ui-border); }
|
|
26
|
+
.palette-shade strong, .palette-shade code { display: block; font-size: 11px; }
|
|
27
|
+
.palette-shade strong { margin-top: 7px; }
|
|
28
|
+
.palette-shade code { color: var(--ui-muted); }
|
|
29
|
+
.color-chip { display: inline-block; width: 32px; height: 32px; border: 1px solid rgba(0, 0, 0, 0.1); border-radius: 50%; flex-shrink: 0; }
|
|
30
|
+
table { border-collapse: collapse; width: 100%; text-align: left; font-size: 13px; }
|
|
31
|
+
th, td { border-bottom: 1px solid var(--ui-border); padding: 12px; vertical-align: top; }
|
|
32
|
+
td code { white-space: normal; overflow-wrap: anywhere; }
|
|
33
|
+
.theme-matrix { min-width: 450px; }
|
|
34
|
+
.theme-matrix .matrix-group th { background: var(--ui-group-background); font-size: 12px; }
|
|
35
|
+
.matrix-value { display: flex; align-items: center; gap: 8px; }
|
|
36
|
+
.theme-previews { display: grid; grid-template-columns: 1fr; gap: 28px; }
|
|
37
|
+
.theme-block > h3 { margin: 0 0 12px; text-transform: capitalize; }
|
|
38
|
+
.other-table th code { font-weight: 400; }
|
|
39
|
+
.type-row { display: grid; grid-template-columns: 200px 1fr; gap: 30px; padding: 28px 0; border-top: 1px solid var(--ui-border); }
|
|
40
|
+
.type-meta { display: flex; flex-direction: column; color: var(--ui-muted); font-size: 12px; overflow-wrap: anywhere; }
|
|
41
|
+
.type-meta strong { color: var(--ui-foreground); font-size: 13px; }
|
|
42
|
+
.type-sample { margin: 0; max-width: 70ch; overflow-wrap: anywhere; }
|
|
43
|
+
.asset-category { margin-top: 40px; }
|
|
44
|
+
.asset-category h3 { margin: 0 0 8px; text-transform: capitalize; }
|
|
45
|
+
.asset-category-docs { margin: 0 0 16px; font-size: 13px; }
|
|
46
|
+
.asset-category-docs a, .asset-actions a { color: var(--ui-accent); }
|
|
47
|
+
.asset-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 220px), 1fr)); gap: 16px; }
|
|
48
|
+
.asset { min-width: 0; background: var(--ui-surface); border: 1px solid var(--ui-border); }
|
|
49
|
+
.asset-preview { height: 180px; background: #767676; color: #000; display: flex; align-items: center; justify-content: center; padding: 20px; }
|
|
50
|
+
.asset-preview.asset-file { background: #e5e5e5; }
|
|
51
|
+
.asset-preview img { max-width: 100%; max-height: 100%; object-fit: contain; }
|
|
52
|
+
.asset-download-icon { width: 24px; height: 24px; }
|
|
53
|
+
.asset-details { display: flex; flex-direction: column; gap: 4px; padding: 15px; overflow-wrap: anywhere; }
|
|
54
|
+
.asset-details strong { text-transform: capitalize; }
|
|
55
|
+
.asset-filename { color: var(--ui-muted); font-size: 12px; }
|
|
56
|
+
.asset-actions { display: flex; flex-wrap: wrap; gap: 10px 16px; margin-top: 10px; font-size: 12px; font-weight: 700; }
|
|
57
|
+
.asset-warning { color: var(--ui-foreground); background: var(--ui-group-background); padding: 12px; font-size: 13px; }
|
|
58
|
+
.example-list { list-style: none; padding: 0; margin: 0; border-top: 1px solid var(--ui-border); }
|
|
59
|
+
.example-list li { display: flex; align-items: center; justify-content: space-between; gap: 20px; border-bottom: 1px solid var(--ui-border); padding: 17px 0; }
|
|
60
|
+
.example-title { font-size: 16px; font-weight: 600; text-decoration: none; }
|
|
61
|
+
.example-title:hover { text-decoration: underline; }
|
|
62
|
+
.links { display: flex; flex-wrap: wrap; gap: 10px 20px; font-size: 12px; font-weight: 700; }
|
|
63
|
+
.links a { color: var(--ui-accent); }
|
|
64
|
+
footer { padding: 35px 0; color: var(--ui-muted); font-size: 12px; }
|
|
65
|
+
footer span { padding: 0 7px; }
|
|
66
|
+
@media (max-width: 700px) {
|
|
67
|
+
main > section { padding: 55px 0; }
|
|
68
|
+
.type-row { grid-template-columns: 1fr; gap: 12px; }
|
|
69
|
+
.example-list li { align-items: flex-start; flex-direction: column; gap: 8px; }
|
|
70
|
+
.palette-shade { width: 74px; min-width: 74px; }
|
|
71
|
+
.asset-grid { grid-template-columns: repeat(auto-fill, minmax(min(100%, 160px), 1fr)); }
|
|
72
|
+
}
|
|
73
|
+
@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: design-system
|
|
3
|
+
description: Use the project's .design system and its tooling when inspecting, designing, building, or changing interfaces, design tokens, components, layouts, or previews.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Design system workflow
|
|
7
|
+
|
|
8
|
+
Before designing or changing an interface, read `.design/DESIGN.md`, the relevant rules under `.design/rules/`, and the documentation and previews for the patterns involved. The design system is authoritative; flag conflicts with host conventions and ask. Accessibility takes precedence.
|
|
9
|
+
|
|
10
|
+
Use the project's tokens, assets and documented patterns. Preserve semantic structure, reading order, responsive behavior, keyboard access and visible focus. Report missing patterns or assets; do not invent imagery. Document new reusable patterns and known gaps, and ask when a necessary design decision is unresolved.
|
|
11
|
+
|
|
12
|
+
For design-system work, edit previews directly and keep them consistent with reusable styles and documentation. Follow the project's styling conventions.
|
|
13
|
+
|
|
14
|
+
## Tooling and validation
|
|
15
|
+
|
|
16
|
+
Requires Node 22+. Run these commands from the host project root:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npx @raketa-cloud/design-cli generate
|
|
20
|
+
npx @raketa-cloud/design-cli serve
|
|
21
|
+
npx @raketa-cloud/design-cli new component my-pattern
|
|
22
|
+
npx @raketa-cloud/design-cli new layout my-pattern
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Generate before serving the showcase at `http://127.0.0.1:4174`; set `PORT` to use another port. The CLI bundles the Tailwind compiler for previews and does not require Rails or a host Tailwind installation. If previews depend on additional Tailwind-compatible CSS, set `preview.css` in `.design/config.json` to its project-relative path; validate that the preview matches the host. The `new` commands scaffold placeholders without overwriting existing patterns. If the project has not been initialized, run `npx @raketa-cloud/design-cli init`; it refuses to overwrite existing design or skill paths.
|
|
26
|
+
|
|
27
|
+
Edit tokens and component CSS, not generated CSS. The build does not regenerate previews or wire the host application. After relevant changes, generate, run focused tests, and inspect previews at desktop and narrow widths and in supported themes. Validate production integration separately and report gaps or anything unverified.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Resolve theme overrides before following aliases, including component-to-global aliases.
|
|
2
|
+
export function flatten(group, prefix = '') {
|
|
3
|
+
if (!group || typeof group !== 'object' || Array.isArray(group)) throw new Error('Invalid token group: ' + prefix);
|
|
4
|
+
if (Object.hasOwn(group, '$value')) return { [prefix]: group };
|
|
5
|
+
return Object.assign({}, ...Object.entries(group).filter(([key]) => !key.startsWith('$')).map(([key, value]) => flatten(value, prefix ? prefix + '.' + key : key)));
|
|
6
|
+
}
|
|
7
|
+
export function resolveThemeDetails(data) {
|
|
8
|
+
const base = { ...flatten(data.semantic.color, 'semantic.color'), ...flatten(data.components || {}, 'components') };
|
|
9
|
+
const themeInputs = [['light', {}], ...Object.entries(data.themes || {})];
|
|
10
|
+
const result = {};
|
|
11
|
+
for (const [name, overrides] of themeInputs) {
|
|
12
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name) || (name === 'light' && overrides !== themeInputs[0][1])) throw new Error('Invalid theme name: ' + name);
|
|
13
|
+
for (const key of Object.keys(overrides)) if (!['semantic', 'components'].includes(key)) throw new Error('Unknown theme group: ' + key);
|
|
14
|
+
if (overrides.semantic && Object.keys(overrides.semantic).some(key => key !== 'color')) throw new Error('Unknown semantic theme group');
|
|
15
|
+
const changes = { ...(overrides.semantic?.color ? flatten(overrides.semantic.color, 'semantic.color') : {}), ...(overrides.components ? flatten(overrides.components, 'components') : {}) };
|
|
16
|
+
for (const key of Object.keys(changes)) if (!Object.hasOwn(base, key)) throw new Error('Unknown theme override: ' + key);
|
|
17
|
+
const effective = { ...base, ...changes };
|
|
18
|
+
function resolve(path, seen = []) {
|
|
19
|
+
if (seen.includes(path)) throw new Error('Circular token reference: ' + [...seen, path].join(' → '));
|
|
20
|
+
const token = effective[path] ?? path.split('.').reduce((value, key) => value?.[key], data);
|
|
21
|
+
if (!token || !Object.hasOwn(token, '$value')) throw new Error('Missing token: ' + path);
|
|
22
|
+
const value = token.$value;
|
|
23
|
+
if (typeof value === 'string' && /^\{[^{}]+\}$/.test(value)) return resolve(value.slice(1, -1), [...seen, path]);
|
|
24
|
+
if (!path.startsWith('primitive.color.') && !path.startsWith('derived.color.')) throw new Error('Color must resolve to a primitive or derived color token: ' + path);
|
|
25
|
+
if (token.$type === 'color' && typeof value === 'string' && (/^#[0-9a-f]{6}$/i.test(value) || /^oklch\((?:\d*\.)?\d+%? (?:\d*\.)?\d+ (?:\d*\.)?\d+\)$/.test(value))) return { value, primitive: path };
|
|
26
|
+
if (token.$type !== 'color' || value?.colorSpace !== 'srgb' || !Array.isArray(value.components) || value.components.length !== 3 || value.components.some(n => !Number.isFinite(n) || n < 0 || n > 1)) throw new Error('Expected sRGB color: ' + path);
|
|
27
|
+
return { value: '#' + value.components.map(n => Math.round(n * 255).toString(16).padStart(2, '0')).join(''), primitive: path };
|
|
28
|
+
}
|
|
29
|
+
result[name] = Object.fromEntries(Object.keys(base).map(path => [path, resolve(path)]));
|
|
30
|
+
}
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
export function resolveThemes(data) {
|
|
34
|
+
return Object.fromEntries(Object.entries(resolveThemeDetails(data)).map(([name, tokens]) => [name, Object.fromEntries(Object.entries(tokens).map(([path, detail]) => [path, detail.value]))]));
|
|
35
|
+
}
|
|
36
|
+
export function cssName(path) {
|
|
37
|
+
if (path.startsWith('semantic.color.')) return '--color-' + path.slice('semantic.color.'.length).replaceAll('.', '-');
|
|
38
|
+
return '--' + path.replaceAll('.', '-');
|
|
39
|
+
}
|