跪拜 Guibai
← Back to the summary

Color Locked in Three Token Layers: Alioth's Multi-Brand Theme System

15 Brand Color Sets + Dual Mode: Locking Colors into Three Token Layers

Alioth Technical Notes · No. 24 · Frontend Design System / Theme Repository: https://github.com/aide-family/moon | Live demo: https://web.alioth.asia/

Introduction

Supporting multi-brand color schemes most easily goes wrong not in "not being able to match a good-looking color", but in two structural accidents: half the interface changes and half doesn't, and after switching brands, the text on buttons becomes hard to read. The first is a token-layering problem; the second is using the same color value as three different purposes. Alioth's web front end has 15 sets of brand × light/dark, relying on three token layers plus two verification scripts. This post explains the structure.

1. Three Layers: Brand, Semantic, Component

L0 Brand layer   src/styles/theme/tokens.brand.css    15 sets :root[data-brand], each with an 11-level color ramp + role colors
L1 Semantic layer src/styles/theme/semantic.{light,dark}.css   Brand roles → --primary family; neutral/status/chart/material
L2 Component layer src/index.css                        @theme inline mapping; components only consume semantic variables

The rule for components is only one: only read semantic variables (--background, --border, --primary), never directly reference brand color ramps (--sunset-500). This way, changing brand only modifies L0, and components stay untouched.

The L1 comment states the boundary very firmly:

/*
 * Rules:
 * - Only neutral colors / material literals are allowed here; any "colored" value must reference --brand-*,
 *   otherwise a brand switch will result in half the interface changing and half not.
 */

2. Brand Color Must Be Split into Three Responsibilities

This is the most critical decision in the whole system:

/* Brand color carries three different responsibilities; variables must be split:
 *     --primary       fill color (button background, selected background), paired with --primary-foreground
 *     --primary-ink   brand color used as "text/icon" (links, sidebar selection, text on soft backgrounds)
 *     --ring          focus ring, must be ≥3:1 against the page background
 * When the same --primary serves all three, high-luminance colors like lemon yellow will inevitably fail one end.
 */
--primary: var(--brand-fill);
--primary-foreground: var(--brand-fill-fg);
--primary-ink: var(--brand-ink);
--ring: var(--brand-ring);

Using lemon yellow as an example: as a button fill it's eye-catching (with dark ink text it contrasts at 12:1), but as body text on a white background it's only 1.5:1, completely unreadable. If there's only one --primary, you either sacrifice button recognizability (darken the yellow) or readability (use yellow for text).

So the same brand color derives multiple values in the generator: fill color, foreground on fill, ink color for text use, and focus ring. A color's semantics are determined by where it's used, not by its value - once this is clear, multi-brand becomes less likely to fall apart.

3. Status Colors Are Completely Decoupled from Brand

/* Status semantics: decoupled from brand; light mode uniformly uses -700 levels to guarantee 4.5:1 or more */
--success: #047857;   --warning: #a34a06;   --danger: #b42318;

Success/warning/danger don't follow the brand. The reason is stated plainly in the design document: orange, yellow, and emerald (brand colors) naturally collide with warning and success hues; the hue separation is insufficient, so the only fix is "slot exclusivity + secondary channel (icon/description)". If status colors also followed the brand, users would not be able to distinguish "this is a brand emphasis" from "this is an alert".

4. Switching Uses data-brand + class, Not media query

<html lang="zh-CN" class="light" data-brand="sunset">

The system mode handling happens only once in the boot script: it reads matchMedia("(prefers-color-scheme: dark)"), resolves it to a concrete light/dark, and writes it to the class. After that, the entire application only recognizes the class.

5. First-Frame Flash Prevention: Inline Script + Hardcoded Brand Table

The essence of theme flash is "styles arrive first, data arrives later". The only solution is to put the script that reads localStorage into <head>, before the stylesheets:

<script>
  // First-frame flash prevention: must execute synchronously before stylesheets and React, so it must be inline.
  // The brand id list is deliberately hardcoded here once — the boot script cannot import modules,
  // otherwise it would add another request and lose the "first-frame" meaning. scripts/check-theme-boot.mjs verifies it matches BRAND_IDS.
  const brands = ["sunset", "cornflower", "jade", ...]
  const brand = brands.includes(stored) ? stored : "sunset"
  root.classList.toggle("dark", dark)
  root.dataset.brand = brand
  root.style.backgroundColor = dark ? "#0b1120" : "#f8fafc"  // placeholder background, cleared after mount
</script>

This code has two "inelegant but necessary" aspects: the brand id list is duplicated (can't import), and the placeholder background is a hardcoded color value (at that point CSS variables aren't defined yet). Duplication requires a guard—check-theme-boot.mjs specifically checks that it matches the generated BRAND_IDS. This is a typical "accept duplication, but use a script to catch drift" approach.

6. Color Values Are Generated, Not Hand-Written

tokens.brand.css and brand-palette.generated.ts are generated artifacts ("do not hand-edit"). The generator gen-brand-tokens.mjs derives 11-level color ramps in OKLCH space with fixed steps and has built-in WCAG assertions - if any brand × mode combination fails contrast, generation fails directly (exit code non-zero).

CI has corresponding two scripts:

"tokens:gen":   "node scripts/gen-brand-tokens.mjs --write && node scripts/sync-theme-preview.mjs",
"tokens:check": "node scripts/gen-brand-tokens.mjs --check && node scripts/check-theme-boot.mjs && node scripts/sync-theme-preview.mjs --check"

--check doesn't write files; it only compares "the current generation result" with "the artifact in the repo". If someone hand-edits a color value, CI goes red immediately. Generated artifacts + verification mode is much more reliable than a "no hand-editing" convention.

7. UI Convention Guard: Only Blocks New Violations, Ignores Legacy

const LITERAL = /#[0-9a-fA-F]{3,8}\b|\brgba?\(|\bhsla?\(/
const PALETTE = /(?:bg|text|border|ring|from|to|via)-(?:slate|gray|...|rose)-\d{2,3}/

check-ui-conventions.mjs scans all tsx/ts under src (skipping components/ui/) and forbids three things: hardcoded color values, Tailwind palette classes (like emerald-700), and native textarea/select.

How about legacy? Use a baseline file:

const fresh = problems.filter((problem) => !baseline.has(key(problem)))
if (fresh.length === 0) { console.log("ui conventions ok(baseline... legacy not counted)"); return }

Only blocks new violations. This is the key to making technical debt manageable: if you demanded everything green from the start, the team would turn off the check; if you only block new ones, existing debt can be scheduled separately, and new code doesn't keep making it worse.

8. Unresolved Parts (Honest List)

The design document explicitly lists technical debt, copied here:

  1. 169 Tailwind palette classes across 25 files (emerald-700, amber-500/10). They all have dark: variants, so brand switching won't mix colors, but they bypass the semantic layer.
  2. 181 #1677ff instances in 14 unDraw illustrations. <img>-referenced SVGs can't read CSS variables, so after a brand switch the illustrations remain blue—most obvious on login, 403/404/502/503 pages.
  3. Cross-device preference sync is missing: /v1/self/* has no preference endpoint, only localStorage.

Item 2 is the most underestimated: many people think "tokenization" can solve every color problem, but colors inside images are another pipeline—they need build-time replacement or conversion to inline SVGs.

9. How to Verify

cd web
npm run tokens:check     # whether artifacts are stale + whether boot script brand table is consistent
npm run check            # typecheck + lint + i18n + ui conventions
npm run dev              # open the appearance menu and switch through 15 brands × light/dark

Manually inspect three spots: whether button text is clear, links/selected states are readable, and focus rings are visible (use Tab to walk through). The design document records measured results: 15 brands × 2 modes × 12 semantic groups = 360 contrast pairs all pass, with a minimum of 4.55:1 - this number is far more meaningful than "looks fine".

Conclusion

The difficulty of multi-brand theming isn't picking colors; it's locking colors into the correct layers: the brand layer holds only ramps and role colors, the semantic layer only does mapping, components only read semantic variables; the same brand color derives fill/ink/focus ring by purpose; status colors are decoupled from brand; generated artifacts are guarded by --check, and conventions are guarded by a "only new violations" baseline. This structure won't make colors prettier, but it turns "switching a brand palette" from a site-wide investigation into changing one generator input.


Next: e2e full-chain regression - how to fix after one run produces 20 defects.