@kelvininc/ui-components
Version:
Kelvin UI Components
56 lines (55 loc) • 2.15 kB
JavaScript
import { StyleMode } from "../types";
import { DEFAULT_CONFIG } from "./config";
export const initialize = (userConfig = {}) => {
var _a, _b;
const { window: win } = window;
if (typeof win === 'undefined') {
return;
}
const instance = (win.KvUiComponents = (_a = win.KvUiComponents) !== null && _a !== void 0 ? _a : {});
const actualConfig = (instance.config = (_b = instance.config) !== null && _b !== void 0 ? _b : {});
win.KvUiComponents.config = Object.assign(Object.assign(Object.assign({}, DEFAULT_CONFIG), actualConfig), userConfig);
};
/**
* Dynamically sets the theme mode without requiring a page refresh.
* This updates the mode attribute on the body element, which triggers
* CSS custom properties to update across all components.
*
* @param mode - The StyleMode to set ('night' or 'light')
*/
export const setThemeMode = (mode) => {
var _a;
if (!Object.values(StyleMode).includes(mode)) {
console.warn(`Invalid theme mode: ${mode}, expected: ${Object.values(StyleMode).join(',')}`);
return;
}
document.body.setAttribute('mode', mode);
if (typeof window !== 'undefined' && ((_a = window.KvUiComponents) === null || _a === void 0 ? void 0 : _a.config)) {
window.KvUiComponents.config.styleMode = mode;
}
};
/**
* Gets the current theme mode.
*
* @returns The current StyleMode
*/
export const getThemeMode = () => {
var _a, _b, _c;
const bodyMode = document.body.getAttribute('mode');
if (bodyMode && Object.values(StyleMode).includes(bodyMode)) {
return bodyMode;
}
return (_c = (_b = (_a = window.KvUiComponents) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.styleMode) !== null && _c !== void 0 ? _c : StyleMode.Night;
};
/**
* Toggles between light and dark theme modes.
*
* @returns The new StyleMode after toggling
*/
export const toggleThemeMode = () => {
const currentMode = getThemeMode();
const newMode = currentMode === StyleMode.Night ? StyleMode.Light : StyleMode.Night;
setThemeMode(newMode);
return newMode;
};
export default initialize;