-
Notifications
You must be signed in to change notification settings - Fork 45
fix(theming): allow three states in useTheme #656
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
Merged
+44
−35
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
aa859bb
refracto: theming
AugustinMauroy bc6e7e7
Update useTheme.mjs
AugustinMauroy 1ec7936
Update useTheme.mjs
AugustinMauroy 729901f
Merge branch 'main' into fix-theme-toggle
AugustinMauroy 68bdbd3
Update useTheme.mjs
AugustinMauroy 8713762
Update useTheme.mjs
avivkeller 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 |
|---|---|---|
| @@ -1,49 +1,112 @@ | ||
| import { useState, useEffect, useCallback } from 'react'; | ||
|
|
||
| const THEME_STORAGE_KEY = 'theme'; | ||
| const THEME_PREFERENCES = new Set(['system', 'light', 'dark']); | ||
|
|
||
| /** | ||
| * Sets up theme toggle button and system preference listener | ||
| */ | ||
| const getSystemTheme = () => | ||
| matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; | ||
|
|
||
| /** | ||
| * Applies the given theme to the `<html>` element's `data-theme` attribute | ||
| * and persists the theme preference in `localStorage`. | ||
| * Retrieves the stored theme preference from local storage. | ||
| * | ||
| * @param {string} theme - The theme to apply ('light' or 'dark'). | ||
| * @returns {'system'|'light'|'dark'|null} The stored theme preference or null if not found. | ||
| */ | ||
| const applyTheme = theme => { | ||
| document.documentElement.setAttribute('data-theme', theme); | ||
| document.documentElement.style.colorScheme = theme; | ||
| localStorage.setItem('theme', theme); | ||
| const getStoredThemePreference = () => { | ||
| try { | ||
| const storedTheme = localStorage.getItem(THEME_STORAGE_KEY); | ||
| return THEME_PREFERENCES.has(storedTheme) ? storedTheme : null; | ||
| } catch { | ||
| return null; | ||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * A React hook for managing the application's light/dark theme. | ||
| * Stores the theme preference in local storage. | ||
| * If storage is unavailable, it fails silently, allowing the application to continue functioning with an in-memory preference. | ||
| * | ||
| * @param {'system'|'light'|'dark'} themePreference - The theme preference to store. | ||
| */ | ||
| const setStoredThemePreference = themePreference => { | ||
| try { | ||
AugustinMauroy marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| localStorage.setItem(THEME_STORAGE_KEY, themePreference); | ||
| } catch { | ||
| // Ignore storage failures and keep non-persistent in-memory preference. | ||
avivkeller marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * Applies a theme preference to the document. | ||
| * | ||
| * The persisted preference can be 'system', but the applied document theme is | ||
| * always resolved to either 'light' or 'dark'. | ||
| * | ||
| * @param {'system'|'light'|'dark'} themePreference - Theme preference. | ||
| */ | ||
| const applyThemePreference = themePreference => { | ||
| const resolvedTheme = | ||
| themePreference === 'system' ? getSystemTheme() : themePreference; | ||
|
|
||
| document.documentElement.setAttribute('data-theme', resolvedTheme); | ||
| document.documentElement.style.colorScheme = resolvedTheme; | ||
| }; | ||
|
|
||
| /** | ||
| * A React hook for managing the application's theme preference. | ||
| */ | ||
| export const useTheme = () => { | ||
| const [theme, setTheme] = useState('light'); | ||
| const [themePreference, setThemePreferenceState] = useState('system'); | ||
|
|
||
| useEffect(() => { | ||
| const initial = | ||
| // Try to get the theme from localStorage first. | ||
| localStorage.getItem('theme') || | ||
| // If not found, check the `data-theme` attribute on the document element | ||
| document.documentElement.getAttribute('data-theme') || | ||
| // As a final fallback, check the user's system preference for dark mode. | ||
| (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'); | ||
|
|
||
| applyTheme(initial); | ||
| setTheme(initial); | ||
| // Use persisted preference if available, otherwise default to system. | ||
| const initialPreference = getStoredThemePreference() || 'system'; | ||
|
|
||
| applyThemePreference(initialPreference); | ||
| setThemePreferenceState(initialPreference); | ||
| }, []); | ||
|
|
||
| /** | ||
| * Callback function to toggle between 'light' and 'dark' themes. | ||
| * Keep the resolved document theme in sync with system changes | ||
| * whenever the preference is set to 'system'. | ||
| */ | ||
| useEffect(() => { | ||
| if (themePreference !== 'system') { | ||
| return; | ||
| } | ||
|
|
||
| const mediaQueryList = matchMedia('(prefers-color-scheme: dark)'); | ||
| /** | ||
| * | ||
| */ | ||
| const handleSystemThemeChange = () => applyThemePreference('system'); | ||
|
|
||
| if ('addEventListener' in mediaQueryList) { | ||
| mediaQueryList.addEventListener('change', handleSystemThemeChange); | ||
| return () => { | ||
| mediaQueryList.removeEventListener('change', handleSystemThemeChange); | ||
| }; | ||
| } | ||
|
|
||
| mediaQueryList.addListener(handleSystemThemeChange); | ||
| return () => { | ||
| mediaQueryList.removeListener(handleSystemThemeChange); | ||
| }; | ||
AugustinMauroy marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| }, [themePreference]); | ||
|
|
||
| /** | ||
| * Updates the theme preference and applies it immediately. | ||
| */ | ||
| const toggleTheme = useCallback(() => { | ||
| setTheme(prev => { | ||
| // Determine the next theme based on the current theme. | ||
| const next = prev === 'light' ? 'dark' : 'light'; | ||
| // Apply the new theme. | ||
| applyTheme(next); | ||
| // Return the new theme to update the state. | ||
| return next; | ||
| }); | ||
| const setThemePreference = useCallback(nextPreference => { | ||
| if (!THEME_PREFERENCES.has(nextPreference)) { | ||
| return; | ||
| } | ||
AugustinMauroy marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| setThemePreferenceState(nextPreference); | ||
| setStoredThemePreference(nextPreference); | ||
| applyThemePreference(nextPreference); | ||
| }, []); | ||
|
|
||
| return [theme, toggleTheme]; | ||
| return [themePreference, setThemePreference]; | ||
| }; | ||
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.
Uh oh!
There was an error while loading. Please reload this page.