11import Storage from "store2"
2- import { TOGGLE_COLOR_THEMES , THEME , COLOR_THEME_AUTO } from "./config.js"
2+ import {
3+ TOGGLE_COLOR_THEMES ,
4+ THEME ,
5+ COLOR_THEME_AUTO ,
6+ COLOR_THEME_LIGHT ,
7+ COLOR_THEME_DARK ,
8+ } from "./config.js"
39; ( ( ) => {
410 applyTheme ( )
511} ) ( )
612
13+ function resolveStoredColorTheme ( stored ) {
14+ if ( TOGGLE_COLOR_THEMES . includes ( stored ) ) {
15+ return stored
16+ }
17+ if (
18+ stored === COLOR_THEME_AUTO ||
19+ stored === undefined ||
20+ stored === null ||
21+ stored === ""
22+ ) {
23+ return window . matchMedia ( "(prefers-color-scheme: dark)" ) . matches
24+ ? COLOR_THEME_DARK
25+ : COLOR_THEME_LIGHT
26+ }
27+ return COLOR_THEME_LIGHT
28+ }
29+
730document . addEventListener ( "DOMContentLoaded" , ( ) => {
831 const colorThemeToggle = document . getElementById ( "gdoc-color-theme" )
932
1033 function toggleColorTheme ( ) {
1134 let lstore = Storage . namespace ( THEME )
12- let currentColorTheme = lstore . get ( "color-theme" ) || COLOR_THEME_AUTO
35+ let currentColorTheme = resolveStoredColorTheme ( lstore . get ( "color-theme" ) )
1336 let nextColorTheme = toggle ( TOGGLE_COLOR_THEMES , currentColorTheme )
1437
1538 lstore . set ( "color-theme" , TOGGLE_COLOR_THEMES [ nextColorTheme ] )
@@ -33,18 +56,16 @@ function applyTheme(init = true) {
3356
3457 let lstore = Storage . namespace ( THEME )
3558 let html = document . documentElement
36- let currentColorTheme = TOGGLE_COLOR_THEMES . includes ( lstore . get ( "color-theme" ) )
37- ? lstore . get ( "color-theme" )
38- : COLOR_THEME_AUTO
59+ let raw = lstore . get ( "color-theme" )
60+ let currentColorTheme = resolveStoredColorTheme ( raw )
3961
40- html . setAttribute ( "class" , "color-toggle-" + currentColorTheme )
41-
42- if ( currentColorTheme === COLOR_THEME_AUTO ) {
43- html . removeAttribute ( "color-theme" )
44- } else {
45- html . setAttribute ( "color-theme" , currentColorTheme )
62+ if ( raw !== currentColorTheme ) {
63+ lstore . set ( "color-theme" , currentColorTheme )
4664 }
4765
66+ html . setAttribute ( "class" , "color-toggle-" + currentColorTheme )
67+ html . setAttribute ( "color-theme" , currentColorTheme )
68+
4869 if ( ! init ) {
4970 // Reload required to re-initialize e.g. Mermaid with the new theme
5071 // and re-parse the Mermaid code blocks.
0 commit comments