design-tokens.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // Shared by design-lint.mjs and import-design-system.mjs: color parsing and the design-system file format.
  2. // Node standard library only; nothing here touches the filesystem.
  3. // ---------------------------------------------------------------- colors
  4. const HEX = /#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![0-9a-z_-])/gi;
  5. const FUNC = /\b(?:rgba?|hsla?)\(\s*[^()]*\)/gi;
  6. function clamp(value, low, high) {
  7. return Math.min(high, Math.max(low, value));
  8. }
  9. function channel(text) {
  10. const value = text.trim();
  11. if (value.endsWith('%')) return clamp(Math.round((parseFloat(value) / 100) * 255), 0, 255);
  12. return clamp(Math.round(parseFloat(value)), 0, 255);
  13. }
  14. function alpha(text) {
  15. if (text === undefined) return 1;
  16. const value = text.trim();
  17. return clamp(value.endsWith('%') ? parseFloat(value) / 100 : parseFloat(value), 0, 1);
  18. }
  19. function hue(text) {
  20. const value = text.trim().toLowerCase();
  21. const number = parseFloat(value);
  22. if (value.endsWith('turn')) return number * 360;
  23. if (value.endsWith('rad')) return (number * 180) / Math.PI;
  24. if (value.endsWith('grad')) return number * 0.9;
  25. return number;
  26. }
  27. function hslToRgb(h, s, l) {
  28. const k = (n) => (n + h / 30) % 12;
  29. const a = s * Math.min(l, 1 - l);
  30. const f = (n) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
  31. return [f(0), f(8), f(4)].map((v) => Math.round(v * 255));
  32. }
  33. function splitArgs(inner) {
  34. // Accepts both "1, 2, 3, 0.5" and "1 2 3 / 50%".
  35. const [main, slash] = inner.split('/');
  36. const parts = main.split(/[\s,]+/).filter(Boolean);
  37. if (slash !== undefined) parts.push(slash.trim());
  38. return parts;
  39. }
  40. /** Parses one CSS color literal (hex, rgb[a], hsl[a]) into { r, g, b, a }, or null. */
  41. export function parseColor(text) {
  42. const value = text.trim().toLowerCase();
  43. if (value.startsWith('#')) {
  44. let hex = value.slice(1);
  45. if (!/^(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(hex)) return null;
  46. if (hex.length <= 4) hex = [...hex].map((c) => c + c).join('');
  47. const n = (i) => parseInt(hex.slice(i, i + 2), 16);
  48. return { r: n(0), g: n(2), b: n(4), a: hex.length === 8 ? Math.round((n(6) / 255) * 1000) / 1000 : 1 };
  49. }
  50. const match = value.match(/^(rgba?|hsla?)\((.*)\)$/);
  51. if (!match) return null;
  52. const args = splitArgs(match[2]);
  53. if (args.length < 3 || args.some((arg) => !/^[-+.\d]/.test(arg))) return null;
  54. if (match[1].startsWith('rgb')) return { r: channel(args[0]), g: channel(args[1]), b: channel(args[2]), a: alpha(args[3]) };
  55. const [r, g, b] = hslToRgb(((hue(args[0]) % 360) + 360) % 360, clamp(parseFloat(args[1]) / 100, 0, 1), clamp(parseFloat(args[2]) / 100, 0, 1));
  56. return { r, g, b, a: alpha(args[3]) };
  57. }
  58. /** Canonical lowercase hex: #rrggbb, or #rrggbbaa when not opaque. */
  59. export function colorKey(color) {
  60. const hex = [color.r, color.g, color.b].map((v) => v.toString(16).padStart(2, '0')).join('');
  61. return color.a >= 1 ? `#${hex}` : `#${hex}${Math.round(color.a * 255).toString(16).padStart(2, '0')}`;
  62. }
  63. export function rgbKey(color) {
  64. return colorKey({ ...color, a: 1 });
  65. }
  66. /** Every color literal in a CSS value, with its offset inside the value. */
  67. export function findColors(value) {
  68. const found = [];
  69. for (const pattern of [HEX, FUNC]) {
  70. for (const match of value.matchAll(pattern)) {
  71. const color = parseColor(match[0]);
  72. if (color) found.push({ text: match[0], index: match.index, color });
  73. }
  74. }
  75. return found.sort((x, y) => x.index - y.index);
  76. }
  77. /** Perceptual-ish RGB distance ("redmean"); good enough to rank a nearest token. */
  78. export function colorDistance(x, y) {
  79. const mean = (x.r + y.r) / 2;
  80. const dr = x.r - y.r;
  81. const dg = x.g - y.g;
  82. const db = x.b - y.b;
  83. return Math.sqrt((2 + mean / 256) * dr * dr + 4 * dg * dg + (2 + (255 - mean) / 256) * db * db);
  84. }
  85. // ---------------------------------------------------------------- CSS scanning
  86. /** Replaces comments with spaces so offsets (and therefore line numbers) stay valid. */
  87. export function blankComments(css) {
  88. return css.replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, ' '));
  89. }
  90. /**
  91. * Declarations of a stylesheet: { selector, property, value, offset } where offset points at the value.
  92. * Only innermost blocks hold declarations, so @media and other wrappers need no special casing.
  93. */
  94. export function cssDeclarations(css) {
  95. const text = blankComments(css);
  96. const out = [];
  97. for (const block of text.matchAll(/([^{}]*)\{([^{}]*)\}/g)) {
  98. const selector = block[1].trim().split(/[;\n]/).pop().trim();
  99. const bodyStart = block.index + block[0].indexOf('{') + 1;
  100. out.push(...inlineDeclarations(block[2], bodyStart).map((decl) => ({ selector, ...decl })));
  101. }
  102. return out;
  103. }
  104. /** Declarations of a style attribute body (no braces). */
  105. export function inlineDeclarations(body, baseOffset = 0) {
  106. const out = [];
  107. let cursor = 0;
  108. for (const piece of body.split(';')) {
  109. const colon = piece.indexOf(':');
  110. if (colon > 0) {
  111. const property = piece.slice(0, colon).trim().toLowerCase();
  112. const rawValue = piece.slice(colon + 1);
  113. const lead = rawValue.length - rawValue.trimStart().length;
  114. if (/^-{0,2}[a-z][\w-]*$/i.test(property)) {
  115. out.push({ property, value: rawValue.trim(), offset: baseOffset + cursor + colon + 1 + lead });
  116. }
  117. }
  118. cursor += piece.length + 1;
  119. }
  120. return out;
  121. }
  122. /** Style sheets and style attributes of an HTML document, with offsets into the document. */
  123. export function htmlStyleSources(html) {
  124. const sheets = [];
  125. for (const match of html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)) {
  126. sheets.push({ css: match[1], offset: match.index + match[0].indexOf('>') + 1 });
  127. }
  128. const attributes = [];
  129. for (const match of html.matchAll(/\sstyle\s*=\s*("([^"]*)"|'([^']*)')/gi)) {
  130. const body = match[2] ?? match[3] ?? '';
  131. attributes.push({ body, offset: match.index + match[0].indexOf(match[1]) + 1 });
  132. }
  133. const presentational = [];
  134. for (const match of html.matchAll(/\s(fill|stroke|color|stop-color|flood-color|bgcolor)\s*=\s*("([^"]*)"|'([^']*)')/gi)) {
  135. const value = match[3] ?? match[4] ?? '';
  136. presentational.push({ property: match[1].toLowerCase(), value, offset: match.index + match[0].indexOf(match[2]) + 1 });
  137. }
  138. return { sheets, attributes, presentational };
  139. }
  140. export function lineAt(text, offset) {
  141. let line = 1;
  142. for (let i = 0; i < offset && i < text.length; i += 1) if (text.charCodeAt(i) === 10) line += 1;
  143. return line;
  144. }
  145. // ---------------------------------------------------------------- fonts and lengths
  146. export const GENERIC_FAMILIES = new Set([
  147. 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif',
  148. 'ui-monospace', 'ui-rounded', 'emoji', 'math', 'fangsong', '-apple-system', 'blinkmacsystemfont',
  149. 'inherit', 'initial', 'unset', 'revert', 'revert-layer',
  150. ]);
  151. export function splitFamilies(value) {
  152. return value
  153. .split(',')
  154. .map((family) => family.trim().replace(/^['"]|['"]$/g, '').trim())
  155. .filter(Boolean);
  156. }
  157. export function normalizeFamily(family) {
  158. return family.replace(/^['"]|['"]$/g, '').trim().toLowerCase();
  159. }
  160. /** The family list inside a `font` shorthand, or null for keywords and var() values. */
  161. export function familiesFromFontShorthand(value) {
  162. if (/var\(/.test(value)) return null;
  163. const match = value.match(/(?:^|\s)[\d.]+(?:px|r?em|pt|%|vw|vh|ch|ex)?(?:\s*\/\s*[\w.%-]+)?\s+(.+)$/i);
  164. return match ? match[1] : null;
  165. }
  166. /** A plain length in px (rem/em counted at 16px), or null for 0, auto, %, calc, var and friends. */
  167. export function lengthPx(token) {
  168. const match = token.trim().toLowerCase().match(/^(-?[\d.]+)(px|rem|em)$/);
  169. if (!match) return null;
  170. const number = parseFloat(match[1]);
  171. if (number === 0) return null;
  172. return Math.abs(match[2] === 'px' ? number : number * 16);
  173. }
  174. // ---------------------------------------------------------------- design-system file
  175. export const SECTIONS = ['colors', 'fonts', 'spacing', 'radii'];
  176. const SECTION_ALIASES = {
  177. colors: /^(colou?rs?|palette)\b/i,
  178. fonts: /^(fonts?|typography|type|font families)\b/i,
  179. spacing: /^(spacing|space|spaces)\b/i,
  180. radii: /^(radii|radius|corner radii|border radius)\b/i,
  181. };
  182. function unquoteCell(cell) {
  183. return cell.trim().replace(/\\\|/g, '|').replace(/^`([\s\S]*)`$/, '$1').trim();
  184. }
  185. function tableCells(line) {
  186. const body = line.trim().replace(/^\|/, '').replace(/\|$/, '');
  187. return body.split(/(?<!\\)\|/).map(unquoteCell);
  188. }
  189. /**
  190. * Reads a design-system file. Markdown: `## Colors` / `## Fonts` / `## Spacing` / `## Radii` sections
  191. * holding `| token | value | use |` tables (or `- token: value` items). JSON: the same keys, each an object
  192. * of token -> value or a list of { token, value, use }.
  193. */
  194. export function parseDesignSystem(text, path = '') {
  195. const system = { name: '', colors: [], fonts: [], spacing: [], radii: [], usage: '' };
  196. const trimmed = text.trim();
  197. if (path.toLowerCase().endsWith('.json') || trimmed.startsWith('{')) {
  198. const data = JSON.parse(trimmed);
  199. system.name = typeof data.name === 'string' ? data.name : '';
  200. system.usage = typeof data.usage === 'string' ? data.usage : '';
  201. for (const section of SECTIONS) {
  202. const entries = data[section];
  203. if (Array.isArray(entries)) {
  204. for (const entry of entries) if (entry && entry.token && entry.value) system[section].push({ token: String(entry.token), value: String(entry.value), use: String(entry.use ?? '') });
  205. } else if (entries && typeof entries === 'object') {
  206. for (const [token, value] of Object.entries(entries)) system[section].push({ token, value: Array.isArray(value) ? value.join(', ') : String(value), use: '' });
  207. }
  208. }
  209. return system;
  210. }
  211. const front = trimmed.match(/^---\n([\s\S]*?)\n---/);
  212. if (front) system.name = front[1].match(/^name:\s*(.+)$/m)?.[1].trim().replace(/^['"]|['"]$/g, '') ?? '';
  213. let section = null;
  214. const usage = [];
  215. for (const line of text.split('\n')) {
  216. const heading = line.match(/^#{2,3}\s+(.+?)\s*$/);
  217. if (heading) {
  218. section = SECTIONS.find((name) => SECTION_ALIASES[name].test(heading[1])) ?? (/^usage\b/i.test(heading[1]) ? 'usage' : null);
  219. continue;
  220. }
  221. if (!system.name) system.name = line.match(/^#\s+(.+?)\s*$/)?.[1] ?? '';
  222. if (section === 'usage') {
  223. usage.push(line);
  224. continue;
  225. }
  226. if (!section) continue;
  227. if (/^\s*\|/.test(line)) {
  228. const cells = tableCells(line);
  229. if (cells.length < 2 || /^:?-{2,}:?$/.test(cells[0]) || /^token$/i.test(cells[0])) continue;
  230. if (cells[0] && cells[1]) system[section].push({ token: cells[0], value: cells[1], use: cells[2] ?? '' });
  231. continue;
  232. }
  233. const item = line.match(/^\s*[-*]\s+`?([^`:]+?)`?\s*:\s*`?([^`]+?)`?\s*(?:[—-]\s*(.*))?$/);
  234. if (item) system[section].push({ token: item[1].trim(), value: item[2].trim(), use: item[3]?.trim() ?? '' });
  235. }
  236. system.usage = usage.join('\n').trim();
  237. return system;
  238. }
  239. function cell(text) {
  240. return String(text).replace(/\|/g, '\\|').replace(/\n/g, ' ');
  241. }
  242. const TITLES = { colors: 'Colors', fonts: 'Fonts', spacing: 'Spacing', radii: 'Radii' };
  243. /** Writes the markdown form read by parseDesignSystem. */
  244. export function formatDesignSystem(system) {
  245. const lines = ['---', `name: ${system.name}`];
  246. if (system.sources?.length) {
  247. lines.push('sources:');
  248. for (const source of system.sources) lines.push(` - ${source}`);
  249. }
  250. lines.push('---', '', `# ${system.name}`, '');
  251. lines.push('Design-system file for the design skill. `design-lint.mjs` reads the four token tables; keep their layout. Edit values and the usage notes freely.', '');
  252. for (const section of SECTIONS) {
  253. lines.push(`## ${TITLES[section]}`, '');
  254. const entries = system[section] ?? [];
  255. if (entries.length === 0) {
  256. lines.push('None found in the sources. Add tokens here if the design should be bound to them.', '');
  257. continue;
  258. }
  259. lines.push('| Token | Value | Use |', '| --- | --- | --- |');
  260. for (const entry of entries) lines.push(`| \`${cell(entry.token)}\` | \`${cell(entry.value)}\` | ${cell(entry.use ?? '')} |`);
  261. lines.push('');
  262. }
  263. lines.push('## Usage', '', system.usage ?? '', '');
  264. return lines.join('\n');
  265. }