export const ThemeChange = new Event ( 'theme-change' , { bubbles : true , cancelable : true , composed : false } ) ; export let getTheme = ( ) : string | null => { let theme = window . localStorage . getItem ( "theme" ) ; if ( typeof theme === "string" ) return theme ; return null ; } ; export let setTheme = ( theme ) : void => { if ( typeof theme === "string" ) window . localStorage . setItem ( "theme" , theme ) ; } ; export let mediaTheme = ( ) : string | null => { 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" ) ; export let themeGet = ( ) => { let themeAttr = html . getAttribute ( "data-theme" ) ; if ( typeof themeAttr === "string" && themeAttr . length ) { return themeAttr ; } return getTheme ( ) ; } ; export let themeSet = ( theme ) => { let themeColor = theme == "system" ? mediaTheme ( ) : theme ; html . setAttribute ( "data-theme" , theme ) ; html . classList . toggle ( "dark" , themeColor == "dark" ) ; setTheme ( theme ) ; document . dispatchEvent ( ThemeChange ) ; } ; export let runTheme = ( ) => { try { let theme = getTheme ( ) ; if ( theme === null ) { themeSet ( "system" ) ; } else themeSet ( theme ) ; window . matchMedia ( "(prefers-color-scheme: dark)" ) . addEventListener ( "change" , ( e ) => { themeSet ( "system" ) ; } ) ; window . matchMedia ( "(prefers-color-scheme: light)" ) . addEventListener ( "change" , ( e ) => { themeSet ( "system" ) ; } ) ; } catch ( e ) { console . warn ( "Theming isn't available on this browser." , e ) ; } } ; runTheme ( ) ;