Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/native. An initiative which aims to make it easy to create complex, light-weight, and perfor okikio.github.io/native
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384// Based on [joshwcomeau.com/gatsby/dark-mode/]export let getTheme = (): string | null => { let theme = window.localStorage.getItem("theme"); // If the user has explicitly chosen light or dark, // let's use it. Otherwise, this value will be null. if (typeof theme === "string") return theme;
// If they are using a browser/OS that doesn't support // color themes, let's default to 'light'. return null;};
export let setTheme = (theme: string): void => { // If the user has explicitly chosen light or dark, store the default theme if (typeof theme === "string") window.localStorage.setItem("theme", theme);};
export let mediaTheme = (): string | null => { // If they haven't been explicitly set, let's check the media query let mql = window.matchMedia("(prefers-color-scheme: dark)"); let hasMediaQueryPreference = typeof mql.matches === "boolean"; if (hasMediaQueryPreference) return mql.matches ? "dark" : "light"; return null;};
let html = document.querySelector("html");// Get theme from html tag, if it has a theme or get it from localStorageexport let themeGet = () => { let themeAttr = html.getAttribute("data-theme"); if (typeof themeAttr === "string" && themeAttr.length) { return themeAttr; }
return getTheme();};
// Set theme in localStorage, as well as in the html tagexport let themeSet = (theme: string) => { html.setAttribute("data-theme", theme); html.classList.toggle("dark", theme == "dark");};
export let runTheme = () => { try { let theme = getTheme(); if (theme === null) theme = mediaTheme(); theme && themeSet(theme);
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => { themeSet(e.matches ? "dark" : "light"); });
window.matchMedia("(prefers-color-scheme: light)").addEventListener("change", (e) => { themeSet(e.matches ? "light" : "dark"); });
} catch (e) { console.warn("Theming isn't available on this browser.", e); }};
let handler = (() => { document.removeEventListener("DOMContentLoaded", handler); window.removeEventListener("load", handler);
try { // On theme switcher button click (mouseup is a tiny bit more efficient) toggle the theme between dark and light mode let themeSwitch = Array.from(document.querySelectorAll(".theme-toggle")); if (themeSwitch[0]) { for (let el of themeSwitch) el.addEventListener("click", () => { let theme = themeGet() === "dark" ? "light" : "dark"; themeSet(theme); setTheme(theme); }); } } catch (e) { console.warn("Theming seems to break on this browser.", e); }}).bind(this);
runTheme();document.addEventListener("DOMContentLoaded", handler);window.addEventListener("load", handler);