@bookbox/view-html
Version:
Bookbox view for html
41 lines (40 loc) • 1.5 kB
JavaScript
export const THEME_STORE_KEY = 'book-box-theme';
function getBookboxNodes(options) {
const { element, selector = '.book-box' } = options !== null && options !== void 0 ? options : {};
if (element)
return [element];
return Array.from(document.querySelectorAll(selector));
}
const themeClassNames = {
light: '',
dark: 'book-box_theme-dark',
sepia: 'book-box_theme-sepia',
};
export function setTheme(options) {
const { theme, storageKey } = options;
for (const node of getBookboxNodes(options)) {
for (const t of Object.keys(themeClassNames)) {
const className = themeClassNames[t];
if (t === theme) {
if (className)
node.classList.add(className);
}
else if (className !== '') {
node.classList.remove(className);
}
}
}
localStorage.setItem(storageKey !== null && storageKey !== void 0 ? storageKey : THEME_STORE_KEY, theme);
}
/**
* set theme from localStorage
*/
export function setSavedTheme(options) {
const { storageKey } = options !== null && options !== void 0 ? options : {};
const savedTheme = localStorage.getItem(storageKey !== null && storageKey !== void 0 ? storageKey : THEME_STORE_KEY);
if (!savedTheme)
return;
if (!themeClassNames.hasOwnProperty(savedTheme))
return;
setTheme(Object.assign({ theme: savedTheme }, (options !== null && options !== void 0 ? options : {})));
}