forked from Start9Labs/start-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme-toggle.js
More file actions
54 lines (47 loc) · 1.81 KB
/
Copy paththeme-toggle.js
File metadata and controls
54 lines (47 loc) · 1.81 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
(function () {
// --- THEME LOGIC ---
const LIGHT = 'light';
const DARK = 'ayu';
const STORAGE_KEY = 'mdbook-theme';
function getStoredTheme() {
return (
localStorage.getItem(STORAGE_KEY) ||
(window.matchMedia('(prefers-color-scheme: dark)').matches ? DARK : LIGHT)
);
}
function applyTheme(theme) {
document.documentElement.classList.remove(LIGHT, DARK);
document.documentElement.classList.add(theme);
localStorage.setItem(STORAGE_KEY, theme);
}
function switchTheme() {
const next = getStoredTheme() === LIGHT ? DARK : LIGHT;
applyTheme(next);
}
function insertToggleButton() {
const menuBar = document.getElementById('menu-bar');
if (!menuBar) return;
const toggleButton = document.createElement('button');
toggleButton.id = 'custom-theme-toggle';
toggleButton.type = 'button';
toggleButton.innerHTML = '<i class="fa fa-sun-o light-mode" aria-hidden="true"></i><i class="fa fa-moon-o dark-mode" aria-hidden="true"></i>';
toggleButton.addEventListener('click', switchTheme);
const rightButtons = menuBar.querySelector('.right-buttons');
(rightButtons || menuBar).prepend(toggleButton);
}
// --- EXTERNAL LINK LOGIC ---
function patchExternalLinks() {
document.querySelectorAll('a[href^="http"]').forEach(link => {
if (!link.href.startsWith(window.location.origin)) {
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
}
});
}
// --- INIT ---
document.addEventListener('DOMContentLoaded', function () {
applyTheme(getStoredTheme());
insertToggleButton();
patchExternalLinks();
});
})();