-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseDemystifyTheme.js
More file actions
52 lines (44 loc) · 1.82 KB
/
Copy pathuseDemystifyTheme.js
File metadata and controls
52 lines (44 loc) · 1.82 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
42
43
44
45
46
47
48
49
50
51
52
import { useEffect } from 'react';
import usePersistentState from '../../hooks/usePersistentState';
/**
* Theme registry shared by every /demystify page. The id is written to
* <html data-demystify-theme="..."> which drives the --dm-* custom properties
* defined in src/styles/Demystify.css.
*/
export const DEMYSTIFY_THEMES = [
{ id: '1', label: 'LIGHT' },
{ id: '2', label: 'SLATE' },
{ id: '3', label: 'DARK' },
{ id: '4', label: 'MATRIX' },
];
// Light. Bare :root in Demystify.css carries the same palette so the first
// paint matches — change both together.
const DEFAULT_THEME = '1';
/**
* Keeps the demystify palette consistent across the hub and its collections,
* and remembers the reader's choice between visits.
*
* The attribute is deliberately never removed on unmount: route transitions
* mount the next page before the previous one tears down, so a cleanup would
* strip the attribute the incoming page just set and snap the palette back to
* the :root default. The attribute only affects --dm-* vars, which nothing
* outside /demystify consumes.
*/
const useDemystifyTheme = () => {
const [theme, setTheme] = usePersistentState('demystify-theme', DEFAULT_THEME);
const isKnown = DEMYSTIFY_THEMES.some((entry) => entry.id === theme);
const activeTheme = isKnown ? theme : DEFAULT_THEME;
useEffect(() => {
document.documentElement.setAttribute('data-demystify-theme', activeTheme);
}, [activeTheme]);
const cycleTheme = () => {
setTheme((current) => {
const idx = DEMYSTIFY_THEMES.findIndex((entry) => entry.id === current);
return DEMYSTIFY_THEMES[(idx + 1) % DEMYSTIFY_THEMES.length].id;
});
};
const themeLabel = DEMYSTIFY_THEMES.find((entry) => entry.id === activeTheme)
.label;
return { theme: activeTheme, themeLabel, cycleTheme };
};
export default useDemystifyTheme;