design-lint.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. #!/usr/bin/env node
  2. // design-lint: checks that the colors, font families and (optionally) spacing in an HTML design file come
  3. // from a design-system file. Node standard library only; reads files, writes nothing.
  4. //
  5. // node design-lint.mjs <page.html> [<design-system.md|.json>] [--spacing] [--json]
  6. //
  7. // Exit codes: 0 no violations, 1 violations, 2 usage or read error.
  8. import { readFileSync } from 'node:fs';
  9. import { realpath } from 'node:fs/promises';
  10. import { fileURLToPath } from 'node:url';
  11. import {
  12. GENERIC_FAMILIES, colorDistance, colorKey, cssDeclarations, familiesFromFontShorthand, findColors,
  13. htmlStyleSources, inlineDeclarations, lengthPx, lineAt, normalizeFamily, parseColor, parseDesignSystem,
  14. rgbKey, splitFamilies,
  15. } from './design-tokens.mjs';
  16. const SPACING_PROPERTIES = /^(margin|padding|gap|row-gap|column-gap)(-(top|right|bottom|left|block|inline)(-(start|end))?)?$/;
  17. function decodeEntities(text) {
  18. return text.replace(/&quot;/g, '"').replace(/&#0*39;|&apos;/g, "'").replace(/&amp;/g, '&');
  19. }
  20. /** Every declaration in the page, with absolute offsets so each finding has a line number. */
  21. export function pageDeclarations(html) {
  22. const { sheets, attributes, presentational } = htmlStyleSources(html);
  23. const declarations = [];
  24. for (const sheet of sheets) {
  25. for (const decl of cssDeclarations(sheet.css)) declarations.push({ ...decl, offset: sheet.offset + decl.offset, where: 'style' });
  26. }
  27. for (const attribute of attributes) {
  28. // Entities never span lines, so decoding first keeps line numbers exact.
  29. for (const decl of inlineDeclarations(decodeEntities(attribute.body), attribute.offset)) declarations.push({ ...decl, where: 'inline' });
  30. }
  31. for (const attribute of presentational) declarations.push({ ...attribute, where: 'attribute' });
  32. return declarations;
  33. }
  34. function nearestColor(color, tokens) {
  35. let best = null;
  36. for (const token of tokens) {
  37. const distance = colorDistance(color, token.color);
  38. if (!best || distance < best.distance) best = { token, distance };
  39. }
  40. return best && `${best.token.token} (${best.token.value})`;
  41. }
  42. function nearestLength(px, tokens) {
  43. let best = null;
  44. for (const token of tokens) {
  45. const distance = Math.abs(px - token.px);
  46. if (!best || distance < best.distance) best = { token, distance };
  47. }
  48. return best && `${best.token.token} (${best.token.value})`;
  49. }
  50. /**
  51. * Lints one page against an optional design system (as returned by parseDesignSystem).
  52. * Returns { violations, warnings, notes, stats }.
  53. */
  54. // 字体栈常放在任意名字的自定义属性里(--font-sans、--app-font-sans、--heading-font),页面再 var() 引用;
  55. // 名字带 font 的都按字体栈查,字号、字重这类同名族属性除外;值也得像字体栈(不是颜色、数字、关键字或 font 简写)。
  56. const FONT_METRIC_PROPERTY = /size|weight|style|stretch|feature|variation|smooth|kerning|synthesis|optical|height|leading|spacing|scale/;
  57. const NON_FAMILY_VALUE = /^(?:#|rgba?\(|hsla?\(|oklch\(|oklab\(|lab\(|lch\(|color\(|calc\(|[-+.\d])/i;
  58. const NON_FAMILY_KEYWORD = new Set(['swap', 'block', 'fallback', 'optional', 'auto', 'normal', 'bold', 'bolder', 'lighter', 'italic', 'oblique', 'inherit', 'initial', 'unset', 'revert', 'none', 'transparent', 'currentcolor']);
  59. function isFontStackProperty(property, value) {
  60. if (!property.startsWith('--') || !property.includes('font') || FONT_METRIC_PROPERTY.test(property)) return false;
  61. const first = value.trim().split(',')[0].trim();
  62. if (NON_FAMILY_VALUE.test(first)) return false;
  63. // 不带引号的首项里出现关键字(swap、normal 900 …这类 font 简写)就不是字体栈
  64. if (!/^["']/.test(first) && first.split(/\s+/).some((word) => NON_FAMILY_KEYWORD.has(word.toLowerCase()))) return false;
  65. return true;
  66. }
  67. export function lintDesign(html, system, options = {}) {
  68. const declarations = pageDeclarations(html);
  69. const violations = [];
  70. const warnings = [];
  71. const notes = [];
  72. const usedColors = new Set();
  73. const usedFamilies = new Set();
  74. const colorTokens = (system?.colors ?? [])
  75. .map((entry) => ({ ...entry, color: parseColor(entry.value) }))
  76. .filter((entry) => entry.color);
  77. const allowedColors = new Set(colorTokens.map((entry) => colorKey(entry.color)));
  78. const allowedRgb = new Set(colorTokens.map((entry) => rgbKey(entry.color)));
  79. const fontStacks = (system?.fonts ?? []).map((entry) => ({ ...entry, families: splitFamilies(entry.value).map(normalizeFamily) }));
  80. const allowedFamilies = new Set(fontStacks.flatMap((entry) => entry.families));
  81. const spacingTokens = (system?.spacing ?? [])
  82. .map((entry) => ({ ...entry, px: lengthPx(entry.value) }))
  83. .filter((entry) => entry.px !== null);
  84. const allowedSpacing = new Set(spacingTokens.map((entry) => entry.px));
  85. const checkColors = colorTokens.length > 0;
  86. const checkFonts = fontStacks.length > 0;
  87. const checkSpacing = Boolean(options.spacing) && spacingTokens.length > 0;
  88. if (!system) notes.push('No design system given: ran generic checks only (palette size, font families, literal colors outside custom properties). Pass a design-system file to check tokens.');
  89. else {
  90. if (!checkColors) notes.push('The design system lists no colors: color tokens not checked.');
  91. if (!checkFonts) notes.push('The design system lists no fonts: font families not checked.');
  92. if (options.spacing && spacingTokens.length === 0) notes.push('The design system lists no spacing in px/rem: spacing not checked.');
  93. }
  94. for (const decl of declarations) {
  95. const line = lineAt(html, decl.offset);
  96. const isCustomProperty = decl.property.startsWith('--');
  97. for (const found of findColors(decl.value)) {
  98. const key = colorKey(found.color);
  99. usedColors.add(key);
  100. if (checkColors) {
  101. if (allowedColors.has(key) || allowedRgb.has(rgbKey(found.color))) continue;
  102. violations.push({ kind: 'color', line, property: decl.property, value: found.text, suggestion: nearestColor(found.color, colorTokens) });
  103. } else if (!isCustomProperty && decl.where !== 'attribute') {
  104. warnings.push({ kind: 'color', line, property: decl.property, value: found.text, suggestion: 'define it once as a CSS custom property and use var()' });
  105. }
  106. }
  107. let families = null;
  108. if (decl.property === 'font-family' || isFontStackProperty(decl.property, decl.value)) families = /var\(/.test(decl.value) ? null : decl.value;
  109. else if (decl.property === 'font') families = familiesFromFontShorthand(decl.value);
  110. if (families) {
  111. const primary = splitFamilies(families).map(normalizeFamily).find((family) => !GENERIC_FAMILIES.has(family));
  112. if (primary) {
  113. usedFamilies.add(primary);
  114. if (checkFonts && !allowedFamilies.has(primary)) {
  115. const suggestion = fontStacks[0] ? `${fontStacks[0].token} (${fontStacks[0].value})` : null;
  116. violations.push({ kind: 'font', line, property: decl.property, value: splitFamilies(families)[0], suggestion });
  117. }
  118. }
  119. }
  120. if (checkSpacing && SPACING_PROPERTIES.test(decl.property) && !/var\(|calc\(/.test(decl.value)) {
  121. for (const part of decl.value.split(/\s+/)) {
  122. const px = lengthPx(part);
  123. if (px === null || allowedSpacing.has(px)) continue;
  124. violations.push({ kind: 'spacing', line, property: decl.property, value: part, suggestion: nearestLength(px, spacingTokens) });
  125. }
  126. }
  127. }
  128. if (!system) {
  129. if (usedColors.size > 12) warnings.push({ kind: 'palette', line: 0, property: '', value: `${usedColors.size} distinct colors`, suggestion: 'consolidate into a smaller set of color roles' });
  130. if (usedFamilies.size > 3) warnings.push({ kind: 'fonts', line: 0, property: '', value: `${usedFamilies.size} primary font families`, suggestion: 'keep to a display and a body family (plus mono if needed)' });
  131. }
  132. return { violations, warnings, notes, stats: { declarations: declarations.length, colors: usedColors.size, families: usedFamilies.size } };
  133. }
  134. function formatFinding(file, finding, label) {
  135. const where = finding.line ? `${file}:${finding.line}` : file;
  136. const property = finding.property ? ` ${finding.property}:` : '';
  137. const hint = finding.suggestion ? ` -> ${label}: ${finding.suggestion}` : '';
  138. return `${where} [${finding.kind}]${property} ${finding.value}${hint}`;
  139. }
  140. async function main(argv) {
  141. const args = argv.filter((arg) => !arg.startsWith('--'));
  142. const flags = new Set(argv.filter((arg) => arg.startsWith('--')));
  143. if (args.length < 1 || args.length > 2 || flags.has('--help')) {
  144. console.error('Usage: node design-lint.mjs <page.html> [<design-system.md|.json>] [--spacing] [--json]');
  145. return 2;
  146. }
  147. const [pagePath, systemPath] = args;
  148. let html;
  149. try {
  150. html = readFileSync(pagePath, 'utf8');
  151. } catch (error) {
  152. console.error(`Cannot read ${pagePath}: ${error.message}`);
  153. return 2;
  154. }
  155. // Generic checks only when no system was given; an explicit path that cannot be read is a read error,
  156. // otherwise a typo would let token violations pass with exit 0.
  157. let system = null;
  158. if (systemPath) {
  159. let text;
  160. try {
  161. text = readFileSync(systemPath, 'utf8');
  162. } catch (error) {
  163. console.error(`Cannot read design system ${systemPath}: ${error.message}`);
  164. return 2;
  165. }
  166. try {
  167. system = parseDesignSystem(text, systemPath);
  168. } catch (error) {
  169. console.error(`Cannot parse ${systemPath}: ${error.message}`);
  170. return 2;
  171. }
  172. // A readable file with no tokens (empty, a README, no Colors/Fonts/Spacing/Radii section, JSON without those
  173. // keys) is not a design system; linting against it would check nothing and still exit 0.
  174. if (!['colors', 'fonts', 'spacing', 'radii'].some((section) => system[section].length > 0)) {
  175. console.error(`Not a design system: ${systemPath} has no tokens under Colors, Fonts, Spacing or Radii.`);
  176. return 2;
  177. }
  178. }
  179. const result = lintDesign(html, system, { spacing: flags.has('--spacing') });
  180. if (flags.has('--json')) {
  181. console.log(JSON.stringify({ file: pagePath, system: systemPath ?? null, ...result }, null, 2));
  182. } else {
  183. for (const note of result.notes) console.log(`note: ${note}`);
  184. for (const finding of result.violations) console.log(formatFinding(pagePath, finding, 'nearest token'));
  185. for (const finding of result.warnings) console.log(`warning: ${formatFinding(pagePath, finding, 'fix')}`);
  186. console.log(`${result.violations.length} violation(s), ${result.warnings.length} warning(s); ${result.stats.colors} distinct colors, ${result.stats.families} font families.`);
  187. }
  188. return result.violations.length > 0 ? 1 : 0;
  189. }
  190. const entry = process.argv[1] === undefined ? undefined : await realpath(process.argv[1]).catch(() => undefined);
  191. if (entry !== undefined && entry === (await realpath(fileURLToPath(import.meta.url)))) process.exitCode = await main(process.argv.slice(2));