-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
fix(app): theme switcher implementation #2167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AchuAshwath
wants to merge
4
commits into
kriasoft:main
Choose a base branch
from
AchuAshwath:fix/theme-switcher
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
56cc21c
fix(app): wire dark mode toggle
AchuAshwath 3db29cd
fix(app): harden theme persistence and add theme tests
AchuAshwath 5e09ebc
fix(app): add 3-way theme preference with system-follow, bootstrap, a…
AchuAshwath 41970e5
fix(app): align theme runtime with bootstrap and harden tests
AchuAshwath File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,251 @@ | ||
| import { | ||
| cleanup, | ||
| fireEvent, | ||
| render, | ||
| screen, | ||
| waitFor, | ||
| } from "@testing-library/react"; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
| import { ThemeProvider, useTheme } from "./theme"; | ||
|
|
||
| function ThemeProbe() { | ||
| const { theme, setTheme, toggleTheme } = useTheme(); | ||
|
|
||
| return ( | ||
| <> | ||
| <div data-testid="theme-value">{theme}</div> | ||
| <button onClick={() => setTheme("dark")} type="button"> | ||
| set-dark | ||
| </button> | ||
| <button onClick={() => setTheme("light")} type="button"> | ||
| set-light | ||
| </button> | ||
| <button onClick={toggleTheme} type="button"> | ||
| toggle-theme | ||
| </button> | ||
| </> | ||
| ); | ||
| } | ||
|
|
||
| describe("ThemeProvider", () => { | ||
| const storage = new Map<string, string>(); | ||
| let originalMatchMedia: typeof window.matchMedia | undefined; | ||
| let originalLocalStorage: Storage; | ||
|
|
||
| const localStorageMock: Storage = { | ||
| getItem: (key: string) => storage.get(key) ?? null, | ||
| setItem: (key: string, value: string) => { | ||
| storage.set(key, value); | ||
| }, | ||
| removeItem: (key: string) => { | ||
| storage.delete(key); | ||
| }, | ||
| clear: () => { | ||
| storage.clear(); | ||
| }, | ||
| key: (index: number) => { | ||
| const keys = Array.from(storage.keys()); | ||
| return keys[index] ?? null; | ||
| }, | ||
| get length() { | ||
| return storage.size; | ||
| }, | ||
| }; | ||
|
|
||
| beforeEach(() => { | ||
| originalMatchMedia = window.matchMedia; | ||
| originalLocalStorage = window.localStorage; | ||
|
|
||
| Object.defineProperty(window, "localStorage", { | ||
| configurable: true, | ||
| writable: true, | ||
| value: localStorageMock, | ||
| }); | ||
| window.localStorage.clear(); | ||
| document.documentElement.classList.remove("dark"); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| cleanup(); | ||
|
|
||
| if (originalMatchMedia) { | ||
| Object.defineProperty(window, "matchMedia", { | ||
| configurable: true, | ||
| writable: true, | ||
| value: originalMatchMedia, | ||
| }); | ||
| } | ||
|
|
||
| Object.defineProperty(window, "localStorage", { | ||
| configurable: true, | ||
| writable: true, | ||
| value: originalLocalStorage, | ||
| }); | ||
|
|
||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| it("uses persisted localStorage theme on first render", () => { | ||
| window.localStorage.setItem("app-theme", "dark"); | ||
|
|
||
| render( | ||
| <ThemeProvider> | ||
| <ThemeProbe /> | ||
| </ThemeProvider>, | ||
| ); | ||
|
|
||
| expect(screen.getByTestId("theme-value")).toHaveTextContent("dark"); | ||
| expect(document.documentElement.classList.contains("dark")).toBe(true); | ||
| }); | ||
|
|
||
| it("falls back to system preference when no theme is persisted", () => { | ||
| Object.defineProperty(window, "matchMedia", { | ||
| configurable: true, | ||
| writable: true, | ||
| value: vi.fn().mockImplementation((query: string) => ({ | ||
| matches: query === "(prefers-color-scheme: dark)", | ||
| media: query, | ||
| onchange: null, | ||
| addEventListener: vi.fn(), | ||
| removeEventListener: vi.fn(), | ||
| dispatchEvent: vi.fn(), | ||
| })), | ||
| }); | ||
|
|
||
| render( | ||
| <ThemeProvider> | ||
| <ThemeProbe /> | ||
| </ThemeProvider>, | ||
| ); | ||
|
|
||
| expect(screen.getByTestId("theme-value")).toHaveTextContent("dark"); | ||
| expect(document.documentElement.classList.contains("dark")).toBe(true); | ||
| }); | ||
|
|
||
| it("writes updates to localStorage and keeps DOM class in sync", () => { | ||
| render( | ||
| <ThemeProvider> | ||
| <ThemeProbe /> | ||
| </ThemeProvider>, | ||
| ); | ||
|
|
||
| fireEvent.click(screen.getByRole("button", { name: "set-dark" })); | ||
| expect(window.localStorage.getItem("app-theme")).toBe("dark"); | ||
| expect(document.documentElement.classList.contains("dark")).toBe(true); | ||
|
|
||
| fireEvent.click(screen.getByRole("button", { name: "set-light" })); | ||
| expect(window.localStorage.getItem("app-theme")).toBe("light"); | ||
| expect(document.documentElement.classList.contains("dark")).toBe(false); | ||
| }); | ||
|
|
||
| it("reacts to theme updates from storage events", async () => { | ||
| render( | ||
| <ThemeProvider> | ||
| <ThemeProbe /> | ||
| </ThemeProvider>, | ||
| ); | ||
|
|
||
| const event = new Event("storage"); | ||
| Object.defineProperty(event, "key", { value: "app-theme" }); | ||
| Object.defineProperty(event, "newValue", { value: "dark" }); | ||
| window.dispatchEvent(event); | ||
|
|
||
| await waitFor(() => { | ||
| expect(screen.getByTestId("theme-value")).toHaveTextContent("dark"); | ||
| expect(document.documentElement.classList.contains("dark")).toBe(true); | ||
| }); | ||
| }); | ||
|
|
||
| it("falls back to system preference when storage key is cleared", async () => { | ||
| Object.defineProperty(window, "matchMedia", { | ||
| configurable: true, | ||
| writable: true, | ||
| value: vi.fn().mockImplementation((query: string) => ({ | ||
| matches: query === "(prefers-color-scheme: dark)", | ||
| media: query, | ||
| onchange: null, | ||
| addEventListener: vi.fn(), | ||
| removeEventListener: vi.fn(), | ||
| dispatchEvent: vi.fn(), | ||
| })), | ||
| }); | ||
|
|
||
| render( | ||
| <ThemeProvider> | ||
| <ThemeProbe /> | ||
| </ThemeProvider>, | ||
| ); | ||
|
|
||
| fireEvent.click(screen.getByRole("button", { name: "set-light" })); | ||
| window.localStorage.removeItem("app-theme"); | ||
|
|
||
| const event = new Event("storage"); | ||
| Object.defineProperty(event, "key", { value: "app-theme" }); | ||
| Object.defineProperty(event, "newValue", { value: null }); | ||
| window.dispatchEvent(event); | ||
|
|
||
| await waitFor(() => { | ||
| expect(screen.getByTestId("theme-value")).toHaveTextContent("dark"); | ||
| }); | ||
| }); | ||
|
|
||
| it("recovers when storage read throws", () => { | ||
| Object.defineProperty(window, "localStorage", { | ||
| configurable: true, | ||
| writable: true, | ||
| value: { | ||
| ...localStorageMock, | ||
| getItem: () => { | ||
| throw new Error("read denied"); | ||
| }, | ||
| } as Storage, | ||
| }); | ||
|
|
||
| Object.defineProperty(window, "matchMedia", { | ||
| configurable: true, | ||
| writable: true, | ||
| value: vi.fn().mockImplementation((query: string) => ({ | ||
| matches: query === "(prefers-color-scheme: dark)", | ||
| media: query, | ||
| onchange: null, | ||
| addEventListener: vi.fn(), | ||
| removeEventListener: vi.fn(), | ||
| dispatchEvent: vi.fn(), | ||
| })), | ||
| }); | ||
|
|
||
| render( | ||
| <ThemeProvider> | ||
| <ThemeProbe /> | ||
| </ThemeProvider>, | ||
| ); | ||
|
|
||
| expect(screen.getByTestId("theme-value")).toHaveTextContent("dark"); | ||
| }); | ||
|
|
||
| it("ignores storage write failures", () => { | ||
| const setItem = vi.fn(() => { | ||
| throw new Error("write denied"); | ||
| }); | ||
|
|
||
| Object.defineProperty(window, "localStorage", { | ||
| configurable: true, | ||
| writable: true, | ||
| value: { | ||
| ...localStorageMock, | ||
| setItem, | ||
| } as Storage, | ||
| }); | ||
|
|
||
| render( | ||
| <ThemeProvider> | ||
| <ThemeProbe /> | ||
| </ThemeProvider>, | ||
| ); | ||
|
|
||
| fireEvent.click(screen.getByRole("button", { name: "set-dark" })); | ||
| expect(screen.getByTestId("theme-value")).toHaveTextContent("dark"); | ||
| expect(document.documentElement.classList.contains("dark")).toBe(true); | ||
| expect(setItem).toHaveBeenCalled(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import { | ||
| createContext, | ||
| type ReactNode, | ||
| use, | ||
| useCallback, | ||
| useEffect, | ||
| useLayoutEffect, | ||
| useMemo, | ||
| useState, | ||
| } from "react"; | ||
|
|
||
| type Theme = "light" | "dark"; | ||
|
|
||
| interface ThemeContextValue { | ||
| theme: Theme; | ||
| setTheme: (theme: Theme) => void; | ||
| toggleTheme: () => void; | ||
| } | ||
|
|
||
| const ThemeContext = createContext<ThemeContextValue | null>(null); | ||
|
|
||
| const STORAGE_KEY = "app-theme"; | ||
|
|
||
| function getInitialTheme(): Theme { | ||
| if (typeof window === "undefined") return "light"; | ||
|
|
||
| try { | ||
| const stored = window.localStorage.getItem(STORAGE_KEY); | ||
| if (stored === "light" || stored === "dark") { | ||
| return stored; | ||
| } | ||
| } catch { | ||
| // Continue with system preference fallback. | ||
| } | ||
|
|
||
| if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) { | ||
| return "dark"; | ||
| } | ||
|
|
||
| return "light"; | ||
| } | ||
|
|
||
| export function ThemeProvider({ children }: { children: ReactNode }) { | ||
| const [theme, setTheme] = useState<Theme>(getInitialTheme); | ||
|
|
||
| useLayoutEffect(() => { | ||
| const root = document.documentElement; | ||
|
|
||
| if (theme === "dark") { | ||
| root.classList.add("dark"); | ||
| } else { | ||
| root.classList.remove("dark"); | ||
| } | ||
|
|
||
| try { | ||
| window.localStorage.setItem(STORAGE_KEY, theme); | ||
| } catch { | ||
| // Ignore storage write failures (e.g., private browsing mode). | ||
| } | ||
| }, [theme]); | ||
|
|
||
| useEffect(() => { | ||
| const onStorage = (event: StorageEvent) => { | ||
| if (event.key !== STORAGE_KEY) return; | ||
| if (event.newValue === "light" || event.newValue === "dark") { | ||
| setTheme(event.newValue); | ||
| return; | ||
| } | ||
|
|
||
| setTheme(getInitialTheme()); | ||
| }; | ||
|
|
||
| window.addEventListener("storage", onStorage); | ||
| return () => { | ||
| window.removeEventListener("storage", onStorage); | ||
| }; | ||
| }, []); | ||
|
|
||
| const toggleTheme = useCallback(() => { | ||
| setTheme((prev) => (prev === "dark" ? "light" : "dark")); | ||
| }, []); | ||
|
|
||
| const value = useMemo( | ||
| () => ({ | ||
| theme, | ||
| setTheme, | ||
| toggleTheme, | ||
| }), | ||
| [theme], | ||
| ); | ||
|
Comment on lines
+171
to
+178
|
||
|
|
||
| return <ThemeContext value={value}>{children}</ThemeContext>; | ||
| } | ||
|
|
||
| export function useTheme() { | ||
| const ctx = use(ThemeContext); | ||
| if (!ctx) { | ||
| throw new Error("useTheme must be used within a ThemeProvider"); | ||
| } | ||
| return ctx; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
useMemodependency array[theme]omitstoggleTheme. WhiletoggleThemeis currently stable (due touseCallback([], [])), this will break silently iftoggleThemeever gains dependencies—and it will trigger anreact-hooks/exhaustive-depslint warning. IncludetoggleThemein the dependency array for correctness and future safety. (setThemefromuseStateis guaranteed stable by React, so it doesn't need to be listed.)