-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy paththeme-script.mjs
More file actions
25 lines (19 loc) · 917 Bytes
/
theme-script.mjs
File metadata and controls
25 lines (19 loc) · 917 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
'use strict';
/**
* This script is designed to be inlined in the <head> of the HTML template.
* It must execute BEFORE the body renders to prevent a Flash of Unstyled Content (FOUC).
*/
export default `(function initializeTheme() {
const THEME_STORAGE_KEY = 'theme';
const THEME_DATA_ATTRIBUTE = 'data-theme';
const DARK_QUERY = '(prefers-color-scheme: dark)';
const savedUserPreference = localStorage.getItem(THEME_STORAGE_KEY);
const systemSupportsDarkMode = window.matchMedia(DARK_QUERY).matches;
const shouldApplyDark =
savedUserPreference === 'dark' ||
(savedUserPreference === 'system' && systemSupportsDarkMode) ||
(!savedUserPreference && systemSupportsDarkMode);
const themeToApply = shouldApplyDark ? 'dark' : 'light';
document.documentElement.setAttribute(THEME_DATA_ATTRIBUTE, themeToApply);
document.documentElement.style.colorScheme = themeToApply;
})();`.trim();