包文件→ .shtukbase/packages/design-lenses/lib/style-data.ts
lib/style-data.ts
197 行, 10.9 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // The pure core of the style specimen's data (build contract, section 6): DTCG token trees in, the object
- // window.SB_STYLE out. No IO here: lib/project.ts reads the project and calls these functions.
- //
- // A token path maps to a CSS name as design-tokens maps it: `card-foreground` → `--card-foreground`,
- // `sb.hue.1` → `--sb-hue-1`. A reference `{a.b}` is resolved; the dark tree overrides the light one.
- export type StyleToken = { name: string; group: string; type: string; light: string; dark: string; description: string };
- export type StyleSection = { title: string; page: string };
- export type StyleRef = { id: string; title: string; css: string[] };
- export type StyleData = {
- version: 1;
- id: string;
- title: string;
- tokens: StyleToken[];
- sections: StyleSection[];
- // Additions beyond section 6 of the contract (read only by the design lenses): the style's CSS files from the
- // root, its pictures (mark, icons) and every style installed in the project, for the style switch.
- css: string[];
- assets: string[];
- styles: StyleRef[];
- problems: string[];
- };
- type Leaf = { path: string; value: unknown; type: string; description: string };
- const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
- const REF = /^\{([^{}]+)\}$/;
- /** Every token of a DTCG tree with the type it inherits from its groups, in the order of the file. */
- export function leaves(tree: unknown): Leaf[] {
- const out: Leaf[] = [];
- const walk = (node: unknown, path: string[], type: string) => {
- if (!isObj(node)) return;
- if ('$value' in node) {
- out.push({ path: path.join('.'), value: node.$value, type: typeof node.$type === 'string' ? node.$type : type,
- description: typeof node.$description === 'string' ? node.$description : '' });
- return;
- }
- const t = typeof node.$type === 'string' ? node.$type : type;
- for (const [k, v] of Object.entries(node)) if (!k.startsWith('$')) walk(v, [...path, k], t);
- };
- walk(tree, [], '');
- return out;
- }
- /** The CSS custom property of a token path. */
- export const cssName = (path: string) => '--' + path.split('.').join('-');
- const num = (v: unknown) => (typeof v === 'number' ? String(Math.round(v * 10000) / 10000) : String(v));
- /** One DTCG value as CSS text; `ref` resolves a reference path to its CSS text (or null when it is missing). */
- export function cssValue(value: unknown, type: string, ref: (path: string) => string | null): string {
- if (typeof value === 'string') {
- const m = REF.exec(value);
- if (m) return ref(m[1]) ?? value;
- return value;
- }
- if (typeof value === 'number') return num(value);
- if (Array.isArray(value)) {
- if (type === 'fontFamily') return value.map((f) => (typeof f === 'string' && /\s/.test(f) && !/^["']/.test(f) ? `"${f}"` : String(f))).join(', ');
- if (type === 'cubicBezier') return `cubic-bezier(${value.map(num).join(', ')})`;
- // A list of shadow layers, also when an override (a dark value) carries no $type: layers are joined by commas.
- if (type === 'shadow' || value.some((v) => v && typeof v === 'object' && 'offsetX' in v)) return value.map((s) => cssValue(s, 'shadow', ref)).join(', ');
- return value.map((v) => cssValue(v, '', ref)).join(' ');
- }
- if (!isObj(value)) return String(value ?? '');
- const sub = (v: unknown, t: string) => cssValue(v, t, ref);
- if (type === 'color' || 'colorSpace' in value) {
- if (typeof value.hex === 'string') return value.hex + (typeof value.alpha === 'number' && value.alpha < 1 ? Math.round(value.alpha * 255).toString(16).padStart(2, '0') : '');
- const c = Array.isArray(value.components) ? value.components.map(num).join(' ') : '';
- const a = typeof value.alpha === 'number' && value.alpha < 1 ? ` / ${num(value.alpha)}` : '';
- const sp = String(value.colorSpace ?? 'srgb');
- return ['hsl', 'hwb', 'lab', 'lch', 'oklab', 'oklch'].includes(sp) ? `${sp}(${c}${a})` : `color(${sp} ${c}${a})`;
- }
- if ('value' in value && 'unit' in value) return num(value.value) + String(value.unit);
- if (type === 'shadow' || 'offsetX' in value) {
- const parts = [value.inset === true ? 'inset' : '', sub(value.offsetX, 'dimension'), sub(value.offsetY, 'dimension'),
- sub(value.blur, 'dimension'), value.spread !== undefined ? sub(value.spread, 'dimension') : '', sub(value.color, 'color')];
- return parts.filter(Boolean).join(' ');
- }
- if (type === 'typography' || 'fontFamily' in value) {
- return [sub(value.fontWeight, 'fontWeight'), sub(value.fontSize, 'dimension') + (value.lineHeight !== undefined ? '/' + sub(value.lineHeight, 'number') : ''),
- sub(value.fontFamily, 'fontFamily')].filter(Boolean).join(' ');
- }
- if (type === 'border' || 'style' in value) return [sub(value.width, 'dimension'), sub(value.style, 'strokeStyle'), sub(value.color, 'color')].join(' ');
- if (type === 'transition' || 'timingFunction' in value) return [sub(value.duration, 'duration'), sub(value.timingFunction, 'cubicBezier'), sub(value.delay, 'duration')].join(' ');
- return JSON.stringify(value);
- }
- /** Resolves every token of a tree to CSS text. `base` (the light tree's leaves) answers references the tree lacks. */
- export function resolve(list: Leaf[], base: Leaf[] = [], problems: string[] = [], file = ''): Map<string, { leaf: Leaf; css: string }> {
- const byPath = new Map<string, Leaf>();
- for (const l of base) byPath.set(l.path, l);
- for (const l of list) byPath.set(l.path, l);
- const done = new Map<string, string>();
- const ref = (path: string, seen: Set<string>): string | null => {
- if (done.has(path)) return done.get(path) as string;
- const l = byPath.get(path);
- if (!l) { problems.push(`${file}: the reference {${path}} leads nowhere`); return null; }
- if (seen.has(path)) { problems.push(`${file}: a circular reference through {${path}}`); return null; }
- seen.add(path);
- const css = cssValue(l.value, l.type, (p) => ref(p, seen));
- seen.delete(path);
- done.set(path, css);
- return css;
- };
- const out = new Map<string, { leaf: Leaf; css: string }>();
- for (const l of list) out.set(l.path, { leaf: l, css: ref(l.path, new Set()) ?? String(l.value) });
- return out;
- }
- const SHADCN_BASE = new Set(['background', 'foreground', 'card', 'card-foreground', 'popover', 'popover-foreground', 'primary',
- 'primary-foreground', 'secondary', 'secondary-foreground', 'muted', 'muted-foreground', 'accent', 'accent-foreground',
- 'destructive', 'destructive-foreground', 'border', 'input', 'ring']);
- /** The specimen group of a token, from its name and type: the order of GROUPS is the order on the page. */
- export const GROUPS = ['Colors', 'Charts', 'Sidebar', 'Hues', 'Type', 'Spacing', 'Radii', 'Shadows', 'Glows and edges', 'Motion', 'Other'];
- export function groupOf(name: string, type: string): string {
- const n = name.replace(/^--/, '');
- if (/^sb-(glow|edge)/.test(n)) return 'Glows and edges';
- if (/^sb-hue-/.test(n) || /^sb-(raspberry|tomato|tangerine|amber|grass|emerald|teal|sky|blue|indigo|violet|orchid)/.test(n)) return 'Hues';
- if (/^chart-/.test(n)) return 'Charts';
- if (/^sidebar/.test(n)) return 'Sidebar';
- if (SHADCN_BASE.has(n)) return 'Colors';
- if (/^(font|text|leading|tracking|line-height|letter)/.test(n) || ['fontFamily', 'fontWeight', 'typography'].includes(type)) return 'Type';
- if (/radius/.test(n)) return 'Radii';
- if (/shadow/.test(n) || type === 'shadow') return 'Shadows';
- if (/(ease|dur|duration|transition|motion)/.test(n) || ['duration', 'cubicBezier', 'transition'].includes(type)) return 'Motion';
- if (/^(space|spacing|gap|size)/.test(n)) return 'Spacing';
- if (type === 'color') return 'Colors';
- if (type === 'dimension') return 'Spacing';
- return 'Other';
- }
- /** A best guess at the DTCG type of a raw CSS value (for tokens read from tokens.css or typed only by their group). */
- export function guessType(name: string, css: string): string {
- const v = css.trim();
- if (/^(#[0-9a-f]{3,8}|(rgb|rgba|hsl|hsla|oklch|oklab|lab|lch|color)\(|color-mix\()/i.test(v)) return 'color';
- if (/shadow|glow|edge/.test(name)) return 'shadow';
- if (/^font-|^--font/.test(name)) return 'fontFamily';
- if (/^cubic-bezier|^ease|^linear/.test(v)) return 'cubicBezier';
- if (/^-?[\d.]+m?s$/.test(v)) return 'duration';
- if (/^-?[\d.]+(px|rem|em|%)$/.test(v)) return 'dimension';
- return '';
- }
- /** The tokens of the specimen from the light and the (optional) dark tree. */
- export function styleTokens(light: unknown, dark: unknown, problems: string[] = []): StyleToken[] {
- const L = leaves(light);
- const D = dark ? leaves(dark) : [];
- const lr = resolve(L, [], problems, 'tokens.json');
- // The dark tree overrides the light one: references in it resolve against the merged set.
- const merged = [...L.filter((l) => !D.some((d) => d.path === l.path)), ...D];
- const dr = resolve(merged, [], problems, 'tokens.dark.json');
- const out: StyleToken[] = [];
- const seen = new Set<string>();
- for (const l of [...L, ...D]) {
- if (seen.has(l.path)) continue;
- seen.add(l.path);
- const name = cssName(l.path);
- const lv = lr.get(l.path)?.css ?? dr.get(l.path)?.css ?? '';
- const dv = dr.get(l.path)?.css ?? lv;
- const type = l.type || guessType(name, lv);
- out.push({ name, group: groupOf(name, type), type, light: lv, dark: dv, description: l.description || (D.find((d) => d.path === l.path)?.description ?? '') });
- }
- return out;
- }
- /** The custom properties of a built tokens.css: the light block (`:root`) and the dark one (`.dark`, `[data-theme="dark"]`). */
- export function parseTokensCss(css: string): StyleToken[] {
- const text = css.replace(/\/\*[\s\S]*?\*\//g, '');
- const light = new Map<string, string>();
- const dark = new Map<string, string>();
- for (const m of text.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
- const sel = m[1].trim();
- const target = /\.dark|data-theme\s*=\s*["']?dark/.test(sel) ? dark : /:root|html/.test(sel) ? light : null;
- if (!target) continue;
- for (const d of m[2].matchAll(/(--[\w-]+)\s*:\s*([^;]+);?/g)) target.set(d[1], d[2].trim());
- }
- const names = [...new Set([...light.keys(), ...dark.keys()])];
- return names.map((name) => {
- const lv = light.get(name) ?? dark.get(name) ?? '';
- const type = guessType(name, lv);
- return { name, group: groupOf(name, type), type, light: lv, dark: dark.get(name) ?? lv, description: '' };
- });
- }
- /** Sorts tokens by the specimen's group order, keeping the file order inside a group. */
- export function sortTokens(tokens: StyleToken[]): StyleToken[] {
- const rank = (g: string) => (GROUPS.indexOf(g) < 0 ? GROUPS.length : GROUPS.indexOf(g));
- return tokens.map((t, i) => [t, i] as const).sort((a, b) => rank(a[0].group) - rank(b[0].group) || a[1] - b[1]).map(([t]) => t);
- }
- /** The text of lib/design/style.data.js: stable (no dates), so `check` can compare it byte for byte. */
- export function styleDataJs(data: StyleData): string {
- return '// Built by `shtuk run design-lenses build` from the chosen style (/design/design.md, field style). Do not edit.\n'
- + 'window.SB_STYLE = ' + JSON.stringify(data, null, 1) + ';\n';
- }