UNPKG

@dfinity/gix-components

Version:
44 lines (43 loc) 1.8 kB
import { Theme } from "../types/theme"; import { isNode } from "./env.utils"; import { notEmptyString } from "@dfinity/utils"; import { enumFromStringExists } from "./enum.utils"; export const THEME_ATTRIBUTE = "theme"; export const LOCALSTORAGE_THEME_KEY = "nnsTheme"; export const initTheme = () => { // No DOM therefore cannot guess the theme if (isNode()) { return undefined; } const theme = document.documentElement.getAttribute(THEME_ATTRIBUTE); const initialTheme = enumFromStringExists({ obj: Theme, value: theme, }) ? theme : Theme.DARK; applyTheme({ theme: initialTheme, preserve: false }); return initialTheme; }; export const applyTheme = ({ theme, preserve = true, }) => { const { documentElement, head } = document; documentElement.setAttribute(THEME_ATTRIBUTE, theme); const color = getComputedStyle(documentElement).getPropertyValue("--theme-color"); // Update theme-color for mobile devices to customize the display of the page or of the surrounding user interface // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name/theme-color head?.children ?.namedItem("theme-color") ?.setAttribute("content", color.trim()); if (preserve) { localStorage.setItem(LOCALSTORAGE_THEME_KEY, JSON.stringify(theme)); } }; export const getThemeFromSystemSettings = () => { const isDarkPreferred = window.matchMedia("(prefers-color-scheme: dark)").matches; return isDarkPreferred ? Theme.DARK : Theme.LIGHT; }; export const resetTheme = (theme) => { localStorage.removeItem(LOCALSTORAGE_THEME_KEY); applyTheme({ theme, preserve: false }); }; export const isThemeSelected = () => notEmptyString(localStorage.getItem(LOCALSTORAGE_THEME_KEY));