Skip to content

World's first open-source enterprise world model.

10.1 KB
Raw Blame
// 风格守卫:web/DESIGN.md 的五条规矩在这里变成检查。
//
// 扫 src/**/*.tsx,命中下面任何一条就红。`style-guard.baseline.json` 里列的是
// 还没迁移的页面——它们暂时豁免;每迁一页就从名单里删一行,名单空了这个
// 文件就删。**新文件永远不豁免**:名单只能缩短,不能加长。
//
// `src/ui/` 是组件本身,允许写原生元素、hover、transition——那正是它的活;
// 但颜色与字号的规矩对它一样管。
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const SRC = path.join(ROOT, "src");
const BASELINE = path.join(ROOT, "style-guard.baseline.json");

const PALETTE =
  "neutral|zinc|gray|slate|stone|rose|amber|red|green|blue|sky|emerald|violet|indigo|purple|pink|orange|yellow|cyan|teal|lime";

// `text-*` 允许的词从 styles.css 里读:五档字号(--text-*)与颜色令牌(--color-*)。
// 令牌加一个这里自动认得;不用再改守卫。剩下的是 Tailwind 里不是字号也不是颜色的
// text- 工具(对齐、换行、省略)和几个颜色关键字
const STYLES = fs.readFileSync(path.join(SRC, "styles.css"), "utf8");
const TOKENS = [
  ...new Set([
    ...[...STYLES.matchAll(/--text-([a-z]+)(?![a-z-])/g)].map((m) => m[1]),
    ...[...STYLES.matchAll(/--color-([a-z0-9-]+)/g)].map((m) => m[1]),
  ]),
];
const TEXT_UTILITIES =
  "left|center|right|justify|start|end|ellipsis|clip|wrap|nowrap|balance|pretty|white|black|transparent|current|inherit";
/* `white` / `black` 留在这张表里,为的是让 `unknown-text` 放过它们——
   它们归下面 `raw-white` 一条管,两条都报会把同一个错说两遍 */
const KNOWN_TEXT = [...TOKENS, ...TEXT_UTILITIES.split("|")]
  .sort((a, b) => b.length - a.length)
  .join("|");

/** 每条规矩:正则 + 一句话说明 + 是否也管组件目录 */
const RULES = [
  {
    id: "type-scale",
    re: /\btext-(xs|sm|base|lg|\d*xl|\[[0-9.]+(px|rem)\])\b/g,
    why: "字号只用五档:text-fine / small / body / title / display(规矩 1)",
    ui: true,
  },
  {
    id: "unknown-text",
    // 不在五档字号、颜色令牌、对齐/换行工具之内的 text-<词>:多半是编出来的
    // (text-caption、text-muted),没有定义,渲染成继承的字号或颜色,而且看不出来。
    // Tailwind 的默认字号另有上面那条报;模型名 text-embedding-* 不是类
    re: new RegExp(
      `\\btext-(?!(?:${KNOWN_TEXT}|xs|sm|base|lg|\\d*xl)(?![a-z0-9-])|embedding|\\[)[a-z][a-z0-9-]*\\b`,
      "g",
    ),
    why: "text-* 只能是五档字号、颜色令牌,或对齐/换行工具;别的没有定义(规矩 1、4)",
    ui: true,
  },
  {
    id: "raw-palette",
    re: new RegExp(
      `\\b(text|bg|border|ring|outline|from|to|via|decoration|divide|placeholder)-(${PALETTE})-[0-9]+\\b`,
      "g",
    ),
    why: "颜色只用令牌:ink / ink-2 / line / surface / ok / warn / danger…(规矩 4)",
    ui: true,
  },
  {
    id: "raw-white",
    /* 白与黑都不是颜色令牌,**带不带透明度都一样**。从前这条只认 `text-white/10`
       那种带斜杠的写法,`text-white` 光秃秃地写就过了——`white` 还被算进下面
       `unknown-text` 的合法工具类里(它跟 text-left、text-nowrap 排在一起)。
       两道门都开着,于是顶栏的字标写死了白色:暗底上看不出来,翻成纸底之后
       它还是白的,等于隐形。名字要的是 `text-ink`,随主题走。
       真要"在深色块上永远是浅字"(主按钮、危险按钮里的字)另有令牌:
       `--u-on-accent` / `--u-on-danger`,它们在浅色那套里也是对的 */
    re: /\b(bg|border|text|ring|outline|divide|fill|stroke|placeholder|decoration|from|via|to)-(white|black)\b(\/\[?[0-9.]+\]?)?/g,
    why: "白与黑不是令牌:文字用 ink / ink-2,面用 surface / surface-2 / surface-3,线用 line;深色块上的字用 on-accent / on-danger(规矩 4)",
    ui: true,
  },
  {
    id: "token-by-hand",
    re: /\[var\(--u-[a-z0-9-]+\)\]/g,
    why: "令牌已经是 Tailwind 颜色:写 text-danger,不写 text-[var(--u-danger)](规矩 4)",
    ui: true,
  },
  {
    id: "radius",
    // rounded-none 不是一档,是"这一条要顶到边"(下拉里撑满的行),放行
    re: /\brounded(-(sm|md|lg|xl|2xl|3xl|\[[^\]]+\]))?(?=[\s"'`}])/g,
    why:
      "圆角按角色分四档:rounded-cell / control / panel / overlay;" +
      "rounded-full 只给真圆的(规矩 3)",
    ui: true,
  },
  {
    id: "spacing",
    // 12 及以上是版面(给浮层留位、页脚净空),不是节奏,放行
    re: /\b-?(p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap|gap-x|gap-y|space-x|space-y)-(0\.5|1\.5|2\.5|3\.5|5|7|9|10|11|\[[^\]]+\])\b/g,
    why: "间距六档:1 2 3 4 6 8;12 以上只给版面净空(规矩 2)",
    ui: false,
  },
  {
    id: "raw-control",
    // 隐藏的文件选择框不算控件(它没有样子),放行
    re: /<(button|textarea|select)\b|<input\b(?![^>]*type="file")/g,
    why: "控件从 ui/ 来:Button / IconButton / Input / Textarea / Dropdown / SearchSelect(规矩 5)",
    ui: false,
  },
  {
    id: "state-in-page",
    re: /\b(hover|focus|focus-visible|active|disabled):[a-z0-9\[\]()/.-]+|\btransition(-[a-z]+)?\b|\bduration-[0-9a-z()-]+/g,
    why: "hover / focus / disabled / 动效在组件里定一次,页面不写(规矩 5)",
    ui: false,
  },
  {
    id: "raw-colour",
    // 页面和组件里不出现色值本身:令牌在 styles.css 里定义一次,浅色/暗色各一套,
    // 写死一个 #ffffff 就是写死了「暗底」。两个例外文件是**令牌的读者**:
    // graphVisuals.ts 从 CSS 变量里把画布要的颜色读出来(canvas 不认 var()),
    // palette.ts 是实体类型的数据色(规矩 4:彩色只属于数据),暗浅两套都在那里。
    // `rgba(0,0,0,0)` 是透明,不是颜色,放行
    re: /#[0-9a-fA-F]{6}(?![0-9a-fA-F])|(?<![a-zA-Z_])rgba?\(/g,
    why: "颜色只用令牌(规矩 4);画布从 graphVisuals 的调色板读,数据色在 palette.ts",
    ui: true,
    skip: (rel) => /src\/(pages\/graphVisuals\.ts|palette\.ts)$/.test(rel) || /\.test\.tsx?$/.test(rel),
    allow: /rgba\(0,\s*0,\s*0,\s*0\)/g,
  },
  {
    id: "raw-shadow",
    /* Tailwind 自带的阴影是按浅色界面调的黑影,与 `--u-shadow` 不是一回事;
       暗底上它们几乎看不见,所以能一直混在页面里没人察觉。浮起只有两档:
       贴着画布的控件 `u-lift`,盖在页面上的浮层 `u-lift-strong`。
       `shadow-none` 是"把它取消掉",不是一档深浅,放行 */
    re: /\bshadow-(sm|md|lg|xl|2xl)\b/g,
    why: "浮起两档:u-lift(贴着画布的控件)/ u-lift-strong(浮层);深浅归 --u-shadow(规矩 4)",
    ui: true,
  },
  {
    id: "native-confirm",
    re: /\bwindow\.(confirm|alert)\(|(?<![.\w])(confirm|alert)\(/g,
    why: "确认走 DangerConfirm / Dialog,不用 window.confirm(规矩 5)",
    ui: false,
  },
];

/** shadcn CLI 生成的那一层不受检:它是**供应层**,按 Tailwind 原生刻度写
 *  (text-sm / rounded-md / bg-primary),与这套规矩不是一套词。改它要么去
 *  registry 改,要么重新 `shadcn add` 覆盖,手写规矩管不到也不该管。
 *  规矩仍然管页面:页面怎么用这些组件、有没有自己拼控件,那是这里的事。 */
const VENDOR = path.join("src", "components", "ui");

function walk(dir, out = []) {
  if (dir.includes(VENDOR)) return out;
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) walk(full, out);
    else if (entry.name.endsWith(".tsx") || entry.name.endsWith(".ts")) out.push(full);
  }
  return out;
}

const baseline = new Set(
  fs.existsSync(BASELINE) ? JSON.parse(fs.readFileSync(BASELINE, "utf8")) : [],
);
const files = walk(SRC).map((f) => path.relative(ROOT, f).replaceAll("\\", "/"));

let failures = 0;
const staleBaseline = [...baseline].filter((f) => !files.includes(f));
for (const rel of files) {
  if (baseline.has(rel)) continue;
  const inUi = rel.startsWith("src/ui/");
  let text = fs.readFileSync(path.join(ROOT, rel), "utf8");
  // 隐藏的文件选择框可以跨好几行,先整段抹掉(保留换行,行号不变)
  // 时间轴的 range 同理:它的皮在 styles.css 的 .scrubber-range 里
  text = text.replace(/<input\b[^>]*type="(file|range)"[^>]*>/g, (m) =>
    m.replace(/[^\n]/g, " "),
  );
  const lines = text.split("\n");
  // 块注释里的行也不算:/* … */ 跨行时逐行看不出自己在注释里,这里记个状态
  let inBlock = false;
  const commentFree = lines.map((line) => {
    let out = "";
    let i = 0;
    while (i < line.length) {
      if (inBlock) {
        const end = line.indexOf("*/", i);
        if (end < 0) return out;
        inBlock = false;
        i = end + 2;
      } else {
        const start = line.indexOf("/*", i);
        if (start < 0) {
          out += line.slice(i);
          break;
        }
        out += line.slice(i, start);
        inBlock = true;
        i = start + 2;
      }
    }
    return out;
  });
  for (const rule of RULES) {
    if (inUi && !rule.ui) continue;
    if (rule.skip && rule.skip(rel)) continue;
    commentFree.forEach((line, i) => {
      // 注释里提到旧写法不算(规矩要能在注释里被引用)
      let code = line.replace(/\/\/.*$/, "");
      if (rule.allow) code = code.replace(rule.allow, "");
      const hits = code.match(rule.re);
      if (!hits) return;
      failures += 1;
      console.log(`${rel}:${i + 1}  [${rule.id}] ${hits.join(" ")}\n    ${rule.why}`);
    });
  }
}

if (staleBaseline.length) {
  console.log(`baseline 里有已经不存在的文件,删掉它们:\n  ${staleBaseline.join("\n  ")}`);
  failures += 1;
}

if (failures) {
  console.log(`\n${failures} 处不合规矩。规矩在 web/DESIGN.md。`);
  process.exit(1);
}
console.log(`style guard: ${files.length - baseline.size} 个文件合规,${baseline.size} 个在迁移名单上。`);