alpineuse
Version:
Collection of Alpine, Extending Plugins.
2 lines (1 loc) • 1.11 kB
JavaScript
const e=new Set(["auto","light","dark"]),t="auto",a="dark",o="light",r="useTheme",s=()=>{const s=window.matchMedia("(prefers-color-scheme: dark)");return{applyTheme:c=>{const l=e.has(c)?c:t,n=l===a||"auto"===l&&s.matches;document.documentElement.classList.remove(a,o),document.documentElement.classList.add(n?a:o),(e=>{try{e&&localStorage.setItem(r,e)}catch(t){console.warn("localStorage is disabled. Failed to store theme preference.")}})(l)},getStoredTheme:()=>{const a=localStorage.getItem(r);return e.has(a)?a:t},prefersDark:s}},c=()=>{const a=document.querySelector("[x-use-theme]");if(!a)return;const o=a.getAttribute("x-use-theme"),c=localStorage.getItem(r);let l=t;o&&e.has(o)?l=o:c&&e.has(c)&&(l=c);const{prefersDark:n,applyTheme:u,getStoredTheme:m}=s();u(l),n.addEventListener("change",(()=>{"auto"===m()&&u("auto")}))},l=t=>{(()=>{const{applyTheme:t,getStoredTheme:a}=s();window.Alpine.magic("useTheme",(()=>{const o={value:a()};return{set:a=>{e.has(a)&&(t(a),o.value=a)},get:()=>o.value,get value(){return o.value},set value(a){e.has(a)&&(t(a),o.value=a)}}}))})(),c()};export{s as T,c as l,l as u};