tickle/modules/utils/documentState.mjs
2023-05-09 04:00:53 +02:00

36 lines
869 B
JavaScript

//@ts-check
/**
* Creates a document state object that can toggle between exclusive states.
* All passed states' css classnames will be prepended with `mode-`.
* @param {string[]} states
*/
export const documentState = (states) => {
const all = states.map((state) => `mode-${state}`);
/**
* @param {any} state
* @returns {state is number}
*/
const isValidIndex = (state) =>
typeof state === "number" && state >= 0 && state < all.length;
/**
* @param {number} state
*/
const is = (state) =>
isValidIndex(state) && document.body.classList.contains(all[state]);
/**
* @param {number|undefined|null|false} state
*/
const set = (state = false) => {
document.body.classList.remove(...all);
isValidIndex(state) && document.body.classList.add(all[state]);
};
return { set, is };
};
export default documentState;