reference/scripts/utils/darkMode.mjs

48 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-10-01 02:29:00 +08:00
import path from 'path';
import { getSVGNode } from './getSVGNode.mjs';
const scripts = `
2022-10-01 11:59:29 +08:00
const LOCAL_NANE = '_dark_mode_theme_'
const rememberedValue = localStorage.getItem(LOCAL_NANE);
if (rememberedValue && ['light', 'dark'].includes(rememberedValue)) {
document.documentElement.setAttribute('data-color-mode', rememberedValue);
}
2022-10-01 02:29:00 +08:00
const button = document.querySelector('#darkMode');
button.onclick = () => {
const theme = document.documentElement.dataset.colorMode;
2022-10-01 11:59:29 +08:00
const mode = theme === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-color-mode', mode);
localStorage.setItem(LOCAL_NANE, mode);
2022-10-01 02:29:00 +08:00
}
`;
const ICONS_PATH = path.resolve(process.cwd(), 'scripts/assets');
export function darkMode() {
const iconSunPath = path.resolve(ICONS_PATH, `sun.svg`);
const iconMoonPath = path.resolve(ICONS_PATH, `moon.svg`);
2022-10-29 00:24:39 +08:00
const sunNode = getSVGNode(iconSunPath);
const moonNode = getSVGNode(iconMoonPath);
2022-10-01 02:29:00 +08:00
return [
{
type: 'element',
tagName: 'button',
properties: {
id: 'darkMode',
2022-10-29 00:24:39 +08:00
type: 'button',
2022-10-01 02:29:00 +08:00
},
2022-10-29 00:24:39 +08:00
children: [...sunNode, ...moonNode],
},
{
2022-10-01 02:29:00 +08:00
type: 'element',
tagName: 'script',
2022-10-29 00:24:39 +08:00
children: [
{
type: 'text',
value: scripts,
},
],
},
2022-10-01 02:29:00 +08:00
];
}