Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,6 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# internal
ROADMAP.md
23 changes: 23 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,27 @@ describe("toTypes", () => {
expect(toTypes()).toContain("light");
expect(toTypes()).toContain("dark");
});

it("returns empty string when themes is empty", () => {
const { toTypes: toTypesEmpty } = defineThemes({
prefix: "ui",
tokens: ["accent"] as const,
themes: {},
});
expect(toTypesEmpty()).toBe("");
});
});

describe("inject — edge cases", () => {
it("does nothing when document.head is null", () => {
const { inject } = defineThemes({
prefix: "edge",
tokens: ["accent"] as const,
themes: { light: ["#fff"] },
});
const original = document.head;
Object.defineProperty(document, "head", { value: null, configurable: true });
expect(() => inject()).not.toThrow();
Object.defineProperty(document, "head", { value: original, configurable: true });
});
});
10 changes: 6 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const defineThemes = ({
}: DefineThemesConfig) => {
const map: Record<string, CSSVarItem<typeof prefix, typeof tokens>> = {};

for (const t in themes) {
for (const t of Object.keys(themes)) {
const vars: Record<string, string> = {};
tokens.forEach((token, i) => {
vars[key(token, prefix)] = themes[t]?.[i] ?? "";
Expand All @@ -23,7 +23,7 @@ export const defineThemes = ({
const toCSS = () => {
let r = "",
first = true;
for (const t in map) {
for (const t of Object.keys(map)) {
if (first) {
r += `:root,\n`;
first = false;
Expand All @@ -38,7 +38,7 @@ export const defineThemes = ({
};

const inject = () => {
if (typeof document === "undefined") return;
if (typeof document === "undefined" || !document.head) return;
const id = `${VARTH}-${prefix}`;
const el =
document.getElementById(id) ??
Expand All @@ -51,11 +51,13 @@ export const defineThemes = ({
const themeNames = Object.keys(map);

const toTypes = () => {
if (themeNames.length === 0) return "";
const firstTheme = themeNames[0] as string;
const union = (names: string[]) =>
names.map((n) => ` | '${n}'`).join("\n");
return [
`export type ${THEME_TOKEN} =`,
union(Object.keys(getVarths(themeNames[0] ?? ""))),
union(Object.keys(getVarths(firstTheme))),
``,
`export type ${THEME_NAME} =`,
union(themeNames),
Expand Down
31 changes: 31 additions & 0 deletions src/react/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it } from "vitest";

afterEach(() => {
cleanup();
localStorage.clear();
});

const { inject, themeNames } = defineThemes({
Expand Down Expand Up @@ -70,4 +71,34 @@ describe("useTheme", () => {
fireEvent.click(screen.getByTestId("button-click"));
expect(screen.getByText("current: dark")).not.toBeNull();
});

it("setTheme ignores invalid theme names", () => {
const InvalidSwitcher = () => {
const { theme, setTheme } = useTheme();
return (
<button data-testid="invalid" onClick={() => setTheme("nonexistent")}>
current: {theme}
</button>
);
};
render(
<ThemeProvider default="light" inject={inject} themeNames={themeNames}>
<InvalidSwitcher />
</ThemeProvider>,
);
fireEvent.click(screen.getByTestId("invalid"));
expect(screen.getByText("current: light")).not.toBeNull();
});

it("setTheme does not throw when localStorage.setItem throws", () => {
const original = localStorage.setItem.bind(localStorage);
localStorage.setItem = () => { throw new Error("QuotaExceededError"); };
render(
<ThemeProvider default="light" inject={inject} themeNames={themeNames}>
<ThemeSwitcher />
</ThemeProvider>,
);
expect(() => fireEvent.click(screen.getByTestId("button-click"))).not.toThrow();
localStorage.setItem = original;
});
});
11 changes: 9 additions & 2 deletions src/react/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,20 @@ export const ThemeProvider = ({
);

const setTheme = (next: string) => {
if (!themeNames.includes(next)) return;
setThemeState(next);
localStorage.setItem("varth-theme", next);
if (typeof localStorage !== "undefined") {
try {
localStorage.setItem("varth-theme", next);
} catch {
// ignore QuotaExceededError / SecurityError
}
}
};

useEffect(() => {
inject();
}, []);
}, [inject]);

return (
<Ctx.Provider value={{ theme, setTheme, themeNames }}>
Expand Down
Loading