示例工程 22-theming-and-native-appearance

22-theming-and-native-appearance/demo-01-theme-resolve/theme.ts

typescript · 1.5 KB

type ThemeSource = "system" | "light" | "dark";

const SOURCES: ThemeSource[] = ["system", "light", "dark"];

function isSource(value: unknown): value is ThemeSource {
  return typeof value === "string" && SOURCES.includes(value as ThemeSource);
}

function resolveTheme(source: ThemeSource, systemDark: boolean): boolean {
  if (source === "dark") return true;
  if (source === "light") return false;
  return systemDark;
}

function parseStored(raw: unknown): ThemeSource {
  if (typeof raw === "object" && raw !== null) {
    const source = (raw as { source?: unknown }).source;
    if (isSource(source)) return source;
  }
  return "system";
}

function nextSource(source: ThemeSource): ThemeSource {
  const index = SOURCES.indexOf(source);
  return SOURCES[(index + 1) % SOURCES.length] ?? "system";
}

const cases = [
  resolveTheme("system", true),
  resolveTheme("system", false),
  resolveTheme("dark", false),
  resolveTheme("light", true),
];

const parsed = [
  parseStored({ source: "dark" }),
  parseStored({ source: "blue" }),
  parseStored(null),
  parseStored("dark"),
];

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      cases[0] === true &&
      cases[1] === false &&
      cases[2] === true &&
      cases[3] === false &&
      parsed.join(",") === "dark,system,system,system" &&
      nextSource("system") === "light" &&
      nextSource("light") === "dark" &&
      nextSource("dark") === "system",
    cases,
    parsed,
    cycle: [nextSource("system"), nextSource("light"), nextSource("dark")],
  }),
);