-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme-cookie.js
More file actions
41 lines (35 loc) · 1.12 KB
/
theme-cookie.js
File metadata and controls
41 lines (35 loc) · 1.12 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* @copyright 2023 Chris Zuber <admin@kernvalley.us>
*/
import { data, attr, ready, query } from './dom.js';
const COOKIE_NAME = 'theme';
const THEMES = ['light', 'dark', 'auto'];
const DEFAULT_THEME = 'auto';
const EVENT = 'themechange';
if ('cookieStore' in globalThis && globalThis.cookieStore.get instanceof Function) {
Promise.all([
cookieStore.get({ name: COOKIE_NAME }),
ready(),
]).then(([cookie]) => {
const $data = query(':root, [data-theme="auto"]');
const $attr = query('[theme="auto"]');
const setTheme = ({ name, value: theme = DEFAULT_THEME } = {}) => {
if (name === COOKIE_NAME && THEMES.includes(theme)) {
document.dispatchEvent(new CustomEvent(EVENT, { detail: { theme }}));
requestAnimationFrame(() => {
data($data, { theme });
attr($attr, { theme });
});
}
};
if (cookie && typeof cookie.value === 'string') {
setTheme(cookie);
}
globalThis.cookieStore.addEventListener('change', ({ changed, deleted }) => {
const cookie = [...changed, ...deleted].find(({ name }) => name === COOKIE_NAME);
if (cookie) {
setTheme(cookie);
}
});
});
}