|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +/** |
| 4 | + * This script is designed to be inlined in the <head> of the HTML template. |
| 5 | + * It must execute BEFORE the body renders to prevent a Flash of Unstyled Content (FOUC). |
| 6 | + */ |
| 7 | +function initializeTheme() { |
| 8 | + const THEME_STORAGE_KEY = 'theme'; |
| 9 | + const THEME_DATA_ATTRIBUTE = 'data-theme'; |
| 10 | + const DARK_QUERY = '(prefers-color-scheme: dark)'; |
| 11 | + |
| 12 | + // 1. Retrieve the user's preference from localStorage |
| 13 | + const savedUserPreference = localStorage.getItem(THEME_STORAGE_KEY); |
| 14 | + |
| 15 | + // 2. Determine if the system/browser is currently set to dark mode |
| 16 | + const systemSupportsDarkMode = window.matchMedia(DARK_QUERY).matches; |
| 17 | + |
| 18 | + /** |
| 19 | + * 3. Logic to determine if 'dark' should be applied: |
| 20 | + * - User explicitly saved 'dark' |
| 21 | + * - User set preference to 'system' AND system is dark |
| 22 | + * - No preference exists yet AND system is dark |
| 23 | + */ |
| 24 | + const shouldApplyDark = |
| 25 | + savedUserPreference === 'dark' || |
| 26 | + (savedUserPreference === 'system' && systemSupportsDarkMode) || |
| 27 | + (!savedUserPreference && systemSupportsDarkMode); |
| 28 | + |
| 29 | + const themeToApply = shouldApplyDark ? 'dark' : 'light'; |
| 30 | + |
| 31 | + // 4. Apply the theme attribute to the document element (<html>) |
| 32 | + document.documentElement.setAttribute(THEME_DATA_ATTRIBUTE, themeToApply); |
| 33 | + |
| 34 | + // 5. Set color-scheme to ensure browser UI (scrollbars, etc.) matches the theme |
| 35 | + document.documentElement.style.colorScheme = themeToApply; |
| 36 | +} |
| 37 | + |
| 38 | +// Export the function body wrapped in an IIFE string |
| 39 | +export default `(${initializeTheme.toString()})();`; |
0 commit comments