Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
296 lines (272 loc) · 9.57 KB
/
Copy pathscript.js
File metadata and controls
296 lines (272 loc) · 9.57 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/**
* @file script.js
* @description Handles the theme toggling functionality for the Offscale application.
* Provides pure, strongly-typed functions for resolving, persisting, and applying
* light/dark theme states across the DOM, Storage, and OS MediaQueryList listeners.
*/
/**
* Valid theme mode literals supported by the application.
*
* @typedef {'light' | 'dark'} ThemeMode
*/
/**
* Minimal storage interface required for reading and persisting theme state.
*
* @typedef {object} ThemeStorage
* @property {(key: string) => string | null} getItem Reads a key from storage.
* @property {(key: string, value: string) => void} setItem Writes a key-value pair to storage.
*/
/**
* Type guard verifying whether an arbitrary string is a valid ThemeMode ('light' | 'dark').
*
* @param {string | null | undefined} value The candidate value to check.
* @returns {value is ThemeMode} True if value is strictly 'light' or 'dark'.
*/
function isValidTheme(value) {
return value === 'light' || value === 'dark';
}
/**
* Safely reads the stored theme preference from a Storage instance.
* Traps SecurityError or QuotaExceededError exceptions when storage is disabled.
*
* @param {ThemeStorage | null | undefined} storage The storage object (e.g. window.localStorage).
* @returns {ThemeMode | null} The validated stored theme mode, or null if absent/inaccessible.
*/
function readStoredTheme(storage) {
if (!storage) {
return null;
}
try {
const rawValue = storage.getItem('theme');
return isValidTheme(rawValue) ? rawValue : null;
} catch {
return null;
}
}
/**
* Safely writes the chosen theme preference to a Storage instance.
* Traps SecurityError or QuotaExceededError exceptions in private or sandboxed browsing.
*
* @param {ThemeStorage | null | undefined} storage The storage object (e.g. window.localStorage).
* @param {ThemeMode} theme The theme mode to persist ('light' or 'dark').
* @returns {boolean} True if persistence succeeded, false if storage was unavailable or threw.
*/
function writeStoredTheme(storage, theme) {
if (!storage) {
return false;
}
try {
storage.setItem('theme', theme);
return true;
} catch {
return false;
}
}
/**
* Resolves the effective active ThemeMode from the root element attribute, stored preference,
* or OS-level prefers-color-scheme media query.
*
* @param {Element} rootElement The document root element (document.documentElement).
* @param {ThemeMode | null} storedTheme The validated theme from storage, if any.
* @param {boolean} prefersDark Whether the OS prefers dark mode via matchMedia.
* @returns {ThemeMode} The effective active theme ('light' or 'dark').
*/
function resolveEffectiveTheme(rootElement, storedTheme, prefersDark) {
const domTheme = rootElement.getAttribute('data-theme');
if (isValidTheme(domTheme)) {
return domTheme;
}
if (isValidTheme(storedTheme)) {
return storedTheme;
}
return prefersDark ? 'dark' : 'light';
}
/**
* Synchronizes the toggle button's accessible attributes (aria-label and aria-pressed)
* with the currently active theme.
*
* @param {HTMLElement} toggleBtn The theme toggle button element.
* @param {ThemeMode} activeTheme The currently active theme mode.
* @returns {void}
*/
function syncToggleButtonA11y(toggleBtn, activeTheme) {
const isDark = activeTheme === 'dark';
toggleBtn.setAttribute(
'aria-label',
isDark ? 'Switch to light mode' : 'Switch to dark mode'
);
toggleBtn.setAttribute('aria-pressed', isDark ? 'true' : 'false');
}
/**
* Applies the specified theme to the root element and synchronizes the toggle button's ARIA state.
*
* @param {Element} rootElement The document root element (document.documentElement).
* @param {HTMLElement} toggleBtn The theme toggle button element.
* @param {ThemeMode} theme The theme mode to apply ('light' or 'dark').
* @returns {void}
*/
function applyThemeToDOM(rootElement, toggleBtn, theme) {
rootElement.setAttribute('data-theme', theme);
syncToggleButtonA11y(toggleBtn, theme);
}
/**
* Handles OS-level prefers-color-scheme change events when no explicit user override is stored.
*
* @param {Element} rootElement The document root element.
* @param {HTMLElement} toggleBtn The theme toggle button element.
* @param {ThemeStorage | null | undefined} storage The storage object to check for user overrides.
* @param {{ matches: boolean }} event The MediaQueryListEvent (or compatible object).
* @returns {void}
*/
function handleSystemThemeChange(rootElement, toggleBtn, storage, event) {
const stored = readStoredTheme(storage);
if (stored !== null) {
return;
}
const nextTheme = event.matches ? 'dark' : 'light';
rootElement.removeAttribute('data-theme');
syncToggleButtonA11y(toggleBtn, nextTheme);
}
/**
* Initializes the theme controller for a given Document and Window environment.
* Attaches click and system preference change listeners and returns a deterministic cleanup function.
*
* @param {Document} doc The DOM Document instance.
* @param {Window} win The browser Window instance.
* @returns {() => void} A teardown function that removes attached event listeners.
*/
function initThemeController(doc, win) {
const themeToggleBtn = doc.getElementById('theme-toggle');
if (!themeToggleBtn) {
/**
* No-op teardown when the toggle button is absent from the document.
*
* @returns {void}
*/
const noopCleanup = () => {};
return noopCleanup;
}
const rootElement = doc.documentElement;
const prefersDarkScheme =
typeof win.matchMedia === 'function'
? win.matchMedia('(prefers-color-scheme: dark)')
: null;
const prefersDark = Boolean(prefersDarkScheme && prefersDarkScheme.matches);
let storage = null;
try {
storage = win.localStorage;
} catch {
storage = null;
}
const storedTheme = readStoredTheme(storage);
if (storedTheme !== null) {
applyThemeToDOM(rootElement, themeToggleBtn, storedTheme);
} else {
const initialEffective = resolveEffectiveTheme(rootElement, null, prefersDark);
syncToggleButtonA11y(themeToggleBtn, initialEffective);
}
/**
* Click handler that flips the active theme and persists the selection.
*
* @returns {void}
*/
const onToggleClick = () => {
const currentPrefersDark = Boolean(
prefersDarkScheme && prefersDarkScheme.matches
);
const currentEffective = resolveEffectiveTheme(
rootElement,
readStoredTheme(storage),
currentPrefersDark
);
const nextTheme = currentEffective === 'dark' ? 'light' : 'dark';
applyThemeToDOM(rootElement, themeToggleBtn, nextTheme);
writeStoredTheme(storage, nextTheme);
};
/**
* System color scheme change handler.
*
* @param {MediaQueryListEvent} event The media query change event.
* @returns {void}
*/
const onSystemChange = (event) => {
handleSystemThemeChange(rootElement, themeToggleBtn, storage, event);
};
themeToggleBtn.addEventListener('click', onToggleClick);
if (
prefersDarkScheme &&
typeof prefersDarkScheme.addEventListener === 'function'
) {
prefersDarkScheme.addEventListener('change', onSystemChange);
}
/**
* Removes the click and media query change listeners registered by initThemeController.
*
* @returns {void}
*/
const cleanup = () => {
themeToggleBtn.removeEventListener('click', onToggleClick);
if (
prefersDarkScheme &&
typeof prefersDarkScheme.removeEventListener === 'function'
) {
prefersDarkScheme.removeEventListener('change', onSystemChange);
}
};
return cleanup;
}
/**
* Bootstraps the theme controller on the provided Document and Window, either immediately
* if the document is already parsed or on DOMContentLoaded if still loading.
*
* @param {Document} doc The DOM Document instance.
* @param {Window} win The browser Window instance.
* @returns {() => void} A teardown function that removes any registered listeners.
*/
function bootstrap(doc, win) {
/** @type {(() => void) | null} */
let controllerCleanup = null;
/**
* DOMContentLoaded callback that initializes the theme controller.
*
* @returns {void}
*/
const onReady = () => {
controllerCleanup = initThemeController(doc, win);
};
if (doc.readyState === 'loading') {
doc.addEventListener('DOMContentLoaded', onReady);
/**
* Cleanup function removing both the DOMContentLoaded listener and any active controller listeners.
*
* @returns {void}
*/
const removeDeferred = () => {
doc.removeEventListener('DOMContentLoaded', onReady);
if (controllerCleanup) {
controllerCleanup();
}
};
return removeDeferred;
}
controllerCleanup = initThemeController(doc, win);
return controllerCleanup;
}
/* istanbul ignore next */
if (typeof document !== 'undefined' && typeof window !== 'undefined') {
bootstrap(document, window);
}
/* istanbul ignore next */
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
isValidTheme,
readStoredTheme,
writeStoredTheme,
resolveEffectiveTheme,
syncToggleButtonA11y,
applyThemeToDOM,
handleSystemThemeChange,
initThemeController,
bootstrap
};
}