示例工程 15-tailwind-css-and-design-tokens

15-tailwind-css-and-design-tokens/app/src/App.tsx

tsx · 11 KB

import { useCallback, useEffect, useState } from "react";
import type { ThemeSource, ThemeState } from "../shared/ipc";
import type { TabId } from "./lib/api";

const tabs: Array<{ id: TabId; label: string }> = [
  { id: "tokens", label: "设计 token" },
  { id: "dark", label: "暗色" },
  { id: "csp", label: "CSP 与体积" },
];

const tokens = [
  { name: "--color-primary", value: "#2563eb", swatch: "bg-primary" },
  { name: "--color-primary-soft", value: "#dbeafe", swatch: "bg-primary-soft" },
  { name: "--color-surface", value: "#ffffff", swatch: "bg-surface" },
  { name: "--color-panel", value: "#f8fafc", swatch: "bg-panel" },
  { name: "--color-border", value: "#e2e8f0", swatch: "bg-border" },
  { name: "--color-text", value: "#0f172a", swatch: "bg-text" },
  { name: "--color-muted", value: "#64748b", swatch: "bg-muted" },
  { name: "--radius-card", value: "8px", swatch: "bg-primary-soft" },
];

const cspRows = [
  {
    env: "开发(Vite dev server)",
    style: "style-src 'self' 'unsafe-inline'",
    reason: "样式通过 <style> 注入",
  },
  {
    env: "生产(构建产物)",
    style: "style-src 'self'",
    reason: "CSS 抽成独立文件",
  },
  { env: "脚本", style: "script-src 'self'", reason: "不需要 unsafe-eval" },
  { env: "HMR 连接", style: "connect-src 'self' ws:", reason: "仅开发态需要" },
];

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function applyThemeClass(dark: boolean): void {
  document.documentElement.classList.toggle("dark", dark);
}

export default function App() {
  const [tab, setTab] = useState<TabId>("tokens");
  const [theme, setTheme] = useState<ThemeState>({
    source: "system",
    dark: false,
  });

  const apply = useCallback((next: ThemeState) => {
    setTheme(next);
    applyThemeClass(next.dark);
  }, []);

  const setThemeSource = useCallback(
    async (source: ThemeSource) => {
      const next = await window.api.theme.set(source);
      apply(next);
    },
    [apply],
  );

  useEffect(() => {
    void window.api.theme.get().then(apply);
    return window.api.theme.onChange(apply);
  }, [apply]);

  useEffect(() => {
    window.__setTab = (next) => setTab(next);
    window.__setTheme = async (source) => {
      await setThemeSource(source);
    };
    window.__snapshot = () => ({
      tab,
      source: theme.source,
      dark: theme.dark,
    });
    window.__smoke = async () => {
      await setThemeSource("dark");
      await sleep(150);
      const darkApplied = document.documentElement.classList.contains("dark");
      await setThemeSource("light");
      await sleep(150);
      const lightApplied = !document.documentElement.classList.contains("dark");
      const button = document.querySelector<HTMLElement>(
        '[data-testid="primary-button"]',
      );
      const primary = button
        ? getComputedStyle(button).backgroundColor
        : "missing";
      return {
        darkApplied,
        lightApplied,
        primary,
        tokens: document.querySelectorAll("[data-token]").length,
        source: (await window.api.theme.get()).source,
      };
    };
  }, [setThemeSource, tab, theme.source, theme.dark]);

  return (
    <div className="min-h-screen bg-surface px-8 py-7 text-text">
      <header className="flex items-end justify-between gap-6 border-b border-border pb-4">
        <div>
          <h1 className="text-2xl font-semibold" data-testid="app-title">
            Tailwind 设计 token
          </h1>
          <p className="mt-1 text-sm text-muted">
            @theme · 暗色变体 · CSP · 体积预算
          </p>
        </div>
        <nav className="flex gap-1">
          {tabs.map((item) => (
            <button
              key={item.id}
              className={`rounded-md border px-3 py-1.5 text-sm ${
                tab === item.id
                  ? "border-border bg-panel font-semibold text-primary"
                  : "border-transparent text-muted hover:bg-panel"
              }`}
              data-testid={`tab-${item.id}`}
              onClick={() => setTab(item.id)}
            >
              {item.label}
            </button>
          ))}
        </nav>
      </header>

      <div className="mt-4 flex items-center gap-2 text-sm">
        <span className="text-muted">主题:</span>
        {(["system", "light", "dark"] as ThemeSource[]).map((source) => (
          <button
            key={source}
            className={`rounded-md border px-2.5 py-1 ${
              theme.source === source
                ? "border-primary text-primary"
                : "border-border text-muted"
            }`}
            data-testid={`theme-${source}`}
            onClick={() => void setThemeSource(source)}
          >
            {source}
          </button>
        ))}
        <span className="ml-2 text-muted" data-testid="dark-state">
          dark: {String(theme.dark)}
        </span>
      </div>

      <main className="mt-6">
        {tab === "tokens" && (
          <section>
            <h2 className="text-lg font-semibold">token 是三层的中间层</h2>
            <p className="mt-1 max-w-3xl text-sm text-muted">
              token → 工具类 → 组件。组件只写 <code>bg-primary</code>、
              <code>rounded-card</code>,不写死颜色与圆角。
            </p>
            <div className="mt-4 grid grid-cols-4 gap-3">
              {tokens.map((token) => (
                <div
                  key={token.name}
                  className="rounded-card border border-border bg-panel p-3"
                  data-token
                >
                  <div
                    className={`h-8 rounded-md border border-border ${token.swatch}`}
                  />
                  <div className="mt-2 font-mono text-xs text-muted">
                    {token.name}
                  </div>
                  <div className="font-mono text-xs">{token.value}</div>
                </div>
              ))}
            </div>
            <div className="mt-5 grid grid-cols-2 gap-4">
              <div className="rounded-card border border-border bg-panel p-5">
                <div className="text-xs uppercase tracking-wide text-muted">
                  Card / panel
                </div>
                <p className="mt-2 text-sm">
                  背景、边框、正文与弱化文字都来自 token;改主题只改变量。
                </p>
                <button
                  className="mt-4 rounded-card bg-primary px-4 py-2 text-sm font-medium text-white"
                  data-testid="primary-button"
                >
                  主操作按钮
                </button>
              </div>
              <div className="rounded-card border border-border bg-surface p-5">
                <div className="text-xs uppercase tracking-wide text-muted">
                  Surface / muted
                </div>
                <p className="mt-2 text-sm text-muted">
                  次级文字用 <code>text-muted</code>,不要临时调透明度。
                </p>
                <div className="mt-4 flex gap-2">
                  <span className="rounded-full bg-primary-soft px-2 py-1 text-xs text-primary">
                    primary-soft
                  </span>
                  <span className="rounded-full border border-border px-2 py-1 text-xs text-muted">
                    border
                  </span>
                </div>
              </div>
            </div>
          </section>
        )}

        {tab === "dark" && (
          <section>
            <h2 className="text-lg font-semibold">暗色只覆盖变量</h2>
            <p className="mt-1 max-w-3xl text-sm text-muted">
              <code>.dark</code> 覆盖 <code>--color-*</code>,组件类不变;
              <code>dark:</code> 变体用于少量结构性差异。
            </p>
            <div className="mt-4 grid grid-cols-2 gap-4">
              <div className="rounded-card border border-border bg-surface p-5">
                <div className="text-sm font-medium">当前主题预览</div>
                <p className="mt-2 text-sm text-muted">
                  系统、浅色、深色由主进程的 <code>nativeTheme</code> 决定。
                </p>
                <button className="mt-4 rounded-card bg-primary px-4 py-2 text-sm text-white">
                  主按钮
                </button>
              </div>
              <div className="rounded-card border border-border bg-panel p-5">
                <div className="text-sm font-medium">记住三件事</div>
                <ul className="mt-2 list-disc pl-5 text-sm text-muted">
                  <li>暗色不新增第二套 CSS 文件</li>
                  <li>不使用内联 style 切换颜色</li>
                  <li>不持久化用户的临时预览</li>
                </ul>
              </div>
            </div>
          </section>
        )}

        {tab === "csp" && (
          <section>
            <h2 className="text-lg font-semibold">CSP 与体积预算</h2>
            <table className="mt-4 w-full border-collapse text-sm">
              <thead>
                <tr className="bg-panel text-left text-xs text-muted">
                  <th className="border border-border px-3 py-2">环境</th>
                  <th className="border border-border px-3 py-2">指令</th>
                  <th className="border border-border px-3 py-2">原因</th>
                </tr>
              </thead>
              <tbody>
                {cspRows.map((row) => (
                  <tr key={row.env}>
                    <td className="border border-border px-3 py-2">
                      {row.env}
                    </td>
                    <td className="border border-border px-3 py-2 font-mono text-xs">
                      {row.style}
                    </td>
                    <td className="border border-border px-3 py-2 text-muted">
                      {row.reason}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="mt-4 grid grid-cols-3 gap-3">
              <div className="rounded-card border border-border bg-panel p-4">
                <div className="text-xs text-muted">生产 CSS(gzip)</div>
                <div className="mt-1 font-mono text-xl" data-testid="css-gzip">
                  1.8 KB
                </div>
              </div>
              <div className="rounded-card border border-border bg-panel p-4">
                <div className="text-xs text-muted">手写 CSS(gzip)</div>
                <div className="mt-1 font-mono text-xl">0.3 KB</div>
              </div>
              <div className="rounded-card border border-border bg-panel p-4">
                <div className="text-xs text-muted">内联 style</div>
                <div className="mt-1 font-mono text-xl">生产 0</div>
              </div>
            </div>
            <p className="mt-3 text-sm text-muted">
              数字由 <code>demo-03-csp-style</code> 的本地生产构建实测;升级
              Tailwind 或新增组件后要重测。
            </p>
          </section>
        )}
      </main>
    </div>
  );
}