ShtukbaseStandard
包文件→ .shtukbase/packages/design-lenses/lib/style-data.ts

lib/style-data.ts

197 行, 10.9 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // The pure core of the style specimen's data (build contract, section 6): DTCG token trees in, the object
  2. // window.SB_STYLE out. No IO here: lib/project.ts reads the project and calls these functions.
  3. //
  4. // A token path maps to a CSS name as design-tokens maps it: `card-foreground` → `--card-foreground`,
  5. // `sb.hue.1` → `--sb-hue-1`. A reference `{a.b}` is resolved; the dark tree overrides the light one.
  6. export type StyleToken = { name: string; group: string; type: string; light: string; dark: string; description: string };
  7. export type StyleSection = { title: string; page: string };
  8. export type StyleRef = { id: string; title: string; css: string[] };
  9. export type StyleData = {
  10. version: 1;
  11. id: string;
  12. title: string;
  13. tokens: StyleToken[];
  14. sections: StyleSection[];
  15. // Additions beyond section 6 of the contract (read only by the design lenses): the style's CSS files from the
  16. // root, its pictures (mark, icons) and every style installed in the project, for the style switch.
  17. css: string[];
  18. assets: string[];
  19. styles: StyleRef[];
  20. problems: string[];
  21. };
  22. type Leaf = { path: string; value: unknown; type: string; description: string };
  23. const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
  24. const REF = /^\{([^{}]+)\}$/;
  25. /** Every token of a DTCG tree with the type it inherits from its groups, in the order of the file. */
  26. export function leaves(tree: unknown): Leaf[] {
  27. const out: Leaf[] = [];
  28. const walk = (node: unknown, path: string[], type: string) => {
  29. if (!isObj(node)) return;
  30. if ('$value' in node) {
  31. out.push({ path: path.join('.'), value: node.$value, type: typeof node.$type === 'string' ? node.$type : type,
  32. description: typeof node.$description === 'string' ? node.$description : '' });
  33. return;
  34. }
  35. const t = typeof node.$type === 'string' ? node.$type : type;
  36. for (const [k, v] of Object.entries(node)) if (!k.startsWith('$')) walk(v, [...path, k], t);
  37. };
  38. walk(tree, [], '');
  39. return out;
  40. }
  41. /** The CSS custom property of a token path. */
  42. export const cssName = (path: string) => '--' + path.split('.').join('-');
  43. const num = (v: unknown) => (typeof v === 'number' ? String(Math.round(v * 10000) / 10000) : String(v));
  44. /** One DTCG value as CSS text; `ref` resolves a reference path to its CSS text (or null when it is missing). */
  45. export function cssValue(value: unknown, type: string, ref: (path: string) => string | null): string {
  46. if (typeof value === 'string') {
  47. const m = REF.exec(value);
  48. if (m) return ref(m[1]) ?? value;
  49. return value;
  50. }
  51. if (typeof value === 'number') return num(value);
  52. if (Array.isArray(value)) {
  53. if (type === 'fontFamily') return value.map((f) => (typeof f === 'string' && /\s/.test(f) && !/^["']/.test(f) ? `"${f}"` : String(f))).join(', ');
  54. if (type === 'cubicBezier') return `cubic-bezier(${value.map(num).join(', ')})`;
  55. // A list of shadow layers, also when an override (a dark value) carries no $type: layers are joined by commas.
  56. if (type === 'shadow' || value.some((v) => v && typeof v === 'object' && 'offsetX' in v)) return value.map((s) => cssValue(s, 'shadow', ref)).join(', ');
  57. return value.map((v) => cssValue(v, '', ref)).join(' ');
  58. }
  59. if (!isObj(value)) return String(value ?? '');
  60. const sub = (v: unknown, t: string) => cssValue(v, t, ref);
  61. if (type === 'color' || 'colorSpace' in value) {
  62. 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') : '');
  63. const c = Array.isArray(value.components) ? value.components.map(num).join(' ') : '';
  64. const a = typeof value.alpha === 'number' && value.alpha < 1 ? ` / ${num(value.alpha)}` : '';
  65. const sp = String(value.colorSpace ?? 'srgb');
  66. return ['hsl', 'hwb', 'lab', 'lch', 'oklab', 'oklch'].includes(sp) ? `${sp}(${c}${a})` : `color(${sp} ${c}${a})`;
  67. }
  68. if ('value' in value && 'unit' in value) return num(value.value) + String(value.unit);
  69. if (type === 'shadow' || 'offsetX' in value) {
  70. const parts = [value.inset === true ? 'inset' : '', sub(value.offsetX, 'dimension'), sub(value.offsetY, 'dimension'),
  71. sub(value.blur, 'dimension'), value.spread !== undefined ? sub(value.spread, 'dimension') : '', sub(value.color, 'color')];
  72. return parts.filter(Boolean).join(' ');
  73. }
  74. if (type === 'typography' || 'fontFamily' in value) {
  75. return [sub(value.fontWeight, 'fontWeight'), sub(value.fontSize, 'dimension') + (value.lineHeight !== undefined ? '/' + sub(value.lineHeight, 'number') : ''),
  76. sub(value.fontFamily, 'fontFamily')].filter(Boolean).join(' ');
  77. }
  78. if (type === 'border' || 'style' in value) return [sub(value.width, 'dimension'), sub(value.style, 'strokeStyle'), sub(value.color, 'color')].join(' ');
  79. if (type === 'transition' || 'timingFunction' in value) return [sub(value.duration, 'duration'), sub(value.timingFunction, 'cubicBezier'), sub(value.delay, 'duration')].join(' ');
  80. return JSON.stringify(value);
  81. }
  82. /** Resolves every token of a tree to CSS text. `base` (the light tree's leaves) answers references the tree lacks. */
  83. export function resolve(list: Leaf[], base: Leaf[] = [], problems: string[] = [], file = ''): Map<string, { leaf: Leaf; css: string }> {
  84. const byPath = new Map<string, Leaf>();
  85. for (const l of base) byPath.set(l.path, l);
  86. for (const l of list) byPath.set(l.path, l);
  87. const done = new Map<string, string>();
  88. const ref = (path: string, seen: Set<string>): string | null => {
  89. if (done.has(path)) return done.get(path) as string;
  90. const l = byPath.get(path);
  91. if (!l) { problems.push(`${file}: the reference {${path}} leads nowhere`); return null; }
  92. if (seen.has(path)) { problems.push(`${file}: a circular reference through {${path}}`); return null; }
  93. seen.add(path);
  94. const css = cssValue(l.value, l.type, (p) => ref(p, seen));
  95. seen.delete(path);
  96. done.set(path, css);
  97. return css;
  98. };
  99. const out = new Map<string, { leaf: Leaf; css: string }>();
  100. for (const l of list) out.set(l.path, { leaf: l, css: ref(l.path, new Set()) ?? String(l.value) });
  101. return out;
  102. }
  103. const SHADCN_BASE = new Set(['background', 'foreground', 'card', 'card-foreground', 'popover', 'popover-foreground', 'primary',
  104. 'primary-foreground', 'secondary', 'secondary-foreground', 'muted', 'muted-foreground', 'accent', 'accent-foreground',
  105. 'destructive', 'destructive-foreground', 'border', 'input', 'ring']);
  106. /** The specimen group of a token, from its name and type: the order of GROUPS is the order on the page. */
  107. export const GROUPS = ['Colors', 'Charts', 'Sidebar', 'Hues', 'Type', 'Spacing', 'Radii', 'Shadows', 'Glows and edges', 'Motion', 'Other'];
  108. export function groupOf(name: string, type: string): string {
  109. const n = name.replace(/^--/, '');
  110. if (/^sb-(glow|edge)/.test(n)) return 'Glows and edges';
  111. if (/^sb-hue-/.test(n) || /^sb-(raspberry|tomato|tangerine|amber|grass|emerald|teal|sky|blue|indigo|violet|orchid)/.test(n)) return 'Hues';
  112. if (/^chart-/.test(n)) return 'Charts';
  113. if (/^sidebar/.test(n)) return 'Sidebar';
  114. if (SHADCN_BASE.has(n)) return 'Colors';
  115. if (/^(font|text|leading|tracking|line-height|letter)/.test(n) || ['fontFamily', 'fontWeight', 'typography'].includes(type)) return 'Type';
  116. if (/radius/.test(n)) return 'Radii';
  117. if (/shadow/.test(n) || type === 'shadow') return 'Shadows';
  118. if (/(ease|dur|duration|transition|motion)/.test(n) || ['duration', 'cubicBezier', 'transition'].includes(type)) return 'Motion';
  119. if (/^(space|spacing|gap|size)/.test(n)) return 'Spacing';
  120. if (type === 'color') return 'Colors';
  121. if (type === 'dimension') return 'Spacing';
  122. return 'Other';
  123. }
  124. /** A best guess at the DTCG type of a raw CSS value (for tokens read from tokens.css or typed only by their group). */
  125. export function guessType(name: string, css: string): string {
  126. const v = css.trim();
  127. if (/^(#[0-9a-f]{3,8}|(rgb|rgba|hsl|hsla|oklch|oklab|lab|lch|color)\(|color-mix\()/i.test(v)) return 'color';
  128. if (/shadow|glow|edge/.test(name)) return 'shadow';
  129. if (/^font-|^--font/.test(name)) return 'fontFamily';
  130. if (/^cubic-bezier|^ease|^linear/.test(v)) return 'cubicBezier';
  131. if (/^-?[\d.]+m?s$/.test(v)) return 'duration';
  132. if (/^-?[\d.]+(px|rem|em|%)$/.test(v)) return 'dimension';
  133. return '';
  134. }
  135. /** The tokens of the specimen from the light and the (optional) dark tree. */
  136. export function styleTokens(light: unknown, dark: unknown, problems: string[] = []): StyleToken[] {
  137. const L = leaves(light);
  138. const D = dark ? leaves(dark) : [];
  139. const lr = resolve(L, [], problems, 'tokens.json');
  140. // The dark tree overrides the light one: references in it resolve against the merged set.
  141. const merged = [...L.filter((l) => !D.some((d) => d.path === l.path)), ...D];
  142. const dr = resolve(merged, [], problems, 'tokens.dark.json');
  143. const out: StyleToken[] = [];
  144. const seen = new Set<string>();
  145. for (const l of [...L, ...D]) {
  146. if (seen.has(l.path)) continue;
  147. seen.add(l.path);
  148. const name = cssName(l.path);
  149. const lv = lr.get(l.path)?.css ?? dr.get(l.path)?.css ?? '';
  150. const dv = dr.get(l.path)?.css ?? lv;
  151. const type = l.type || guessType(name, lv);
  152. out.push({ name, group: groupOf(name, type), type, light: lv, dark: dv, description: l.description || (D.find((d) => d.path === l.path)?.description ?? '') });
  153. }
  154. return out;
  155. }
  156. /** The custom properties of a built tokens.css: the light block (`:root`) and the dark one (`.dark`, `[data-theme="dark"]`). */
  157. export function parseTokensCss(css: string): StyleToken[] {
  158. const text = css.replace(/\/\*[\s\S]*?\*\//g, '');
  159. const light = new Map<string, string>();
  160. const dark = new Map<string, string>();
  161. for (const m of text.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
  162. const sel = m[1].trim();
  163. const target = /\.dark|data-theme\s*=\s*["']?dark/.test(sel) ? dark : /:root|html/.test(sel) ? light : null;
  164. if (!target) continue;
  165. for (const d of m[2].matchAll(/(--[\w-]+)\s*:\s*([^;]+);?/g)) target.set(d[1], d[2].trim());
  166. }
  167. const names = [...new Set([...light.keys(), ...dark.keys()])];
  168. return names.map((name) => {
  169. const lv = light.get(name) ?? dark.get(name) ?? '';
  170. const type = guessType(name, lv);
  171. return { name, group: groupOf(name, type), type, light: lv, dark: dark.get(name) ?? lv, description: '' };
  172. });
  173. }
  174. /** Sorts tokens by the specimen's group order, keeping the file order inside a group. */
  175. export function sortTokens(tokens: StyleToken[]): StyleToken[] {
  176. const rank = (g: string) => (GROUPS.indexOf(g) < 0 ? GROUPS.length : GROUPS.indexOf(g));
  177. 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);
  178. }
  179. /** The text of lib/design/style.data.js: stable (no dates), so `check` can compare it byte for byte. */
  180. export function styleDataJs(data: StyleData): string {
  181. return '// Built by `shtuk run design-lenses build` from the chosen style (/design/design.md, field style). Do not edit.\n'
  182. + 'window.SB_STYLE = ' + JSON.stringify(data, null, 1) + ';\n';
  183. }