# All files / src/hooks useTheme.ts

47.91% Statements 46/96
14.28% Branches 6/42
65% Functions 13/20
47.87% Lines 45/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233

    436x
    436x
    436x

    436x
    436x

    436x

    436x

    872x

    872x
    872x
    872x

    872x

    872x

    872x
    872x

    4276x

    4276x
    4276x

    4276x

    2356x

    2356x

    2356x

    436x
    436x

    3840x
    436x

    3840x

    1920x
    1920x
    1484x

    1920x
    1920x

    1920x

    1920x

    1920x

    1920x
    1920x

    1920x
    1920x

    1920x
    1920x

    1920x

    1920x
    1484x

    1920x

     import { useCallback, useEffect, useSyncExternalStore } from "react";
    import { THEMES, THEME_IDS, DEFAULT_THEME_ID, getThemeById } from "../themes.js";
    import type { ThemeDefinition } from "../themes.js";

    interface ThemeSnapshot {
      themeId: string;
      systemDark: boolean;
      preferSystem: boolean;
    }

    const STORAGE_KEY: string = "grackle-theme";
    const PREFER_SYSTEM_KEY: string = "grackle-prefer-system";
    const MEDIA_QUERY: string = "(prefers-color-scheme: dark)";

    let listeners: Array<() => void> = [];
    let lastSnapshot: ThemeSnapshot | undefined = undefined;

    /** Notify all subscribers of a state change. */
    function emitChange(): void {
      lastSnapshot = undefined;
      for (const listener of listeners) {
        listener();
      }
    }

    /** Check whether the OS prefers dark mode. */
    function getSystemDark(): boolean {
      Iif (typeof window === "undefined") {
        return false;
      }
      return window.matchMedia(MEDIA_QUERY).matches;
    }

    /** Read the persisted theme ID from localStorage, defaulting to the registry default. */
    function getStored(): string {
      Iif (typeof localStorage === "undefined") {
        return DEFAULT_THEME_ID;
      }
      try {
        const raw: string | null = localStorage.getItem(STORAGE_KEY);
        Iif (raw !== null && THEME_IDS.has(raw)) {
          return raw;
        }
      } catch {
        // localStorage may be unavailable
      }
      return DEFAULT_THEME_ID;
    }

    /** Read the persisted prefer-system flag from localStorage. */
    function getPreferSystem(): boolean {
      Iif (typeof localStorage === "undefined") {
        return false;
      }
      try {
        return localStorage.getItem(PREFER_SYSTEM_KEY) === "true";
      } catch {
        return false;
      }
    }

    /** Find the parent theme for a hidden variant ID (e.g., "grackle-dark" → Grackle). */
    function findParentTheme(variantId: string): ThemeDefinition | undefined {
      return THEMES.find((t) => t.variantLightId === variantId || t.variantDarkId === variantId);
    }

    /** Resolve a theme ID to the data-theme attribute value applied to the document. */
    function resolveDataTheme(themeId: string, preferSystem: boolean): string {
      const def = getThemeById(themeId);
      // Parent theme with variants → resolve to light or dark
      if (def?.variantDarkId) {
        Iif (preferSystem && def.variantLightId) {
          return getSystemDark() ? def.variantDarkId : def.variantLightId;
        }
        return def.variantDarkId;
      }
      // Concrete variant ID (e.g., "grackle-dark") — if preferSystem, resolve via parent
      Iif (def?.hidden && preferSystem) {
        const parent = findParentTheme(themeId);
        Iif (parent?.variantLightId && parent.variantDarkId) {
          return getSystemDark() ? parent.variantDarkId : parent.variantLightId;
        }
      }
      return themeId;
    }

    /** Apply the resolved theme to the document root element. */
    function applyTheme(
      themeId: string,
      preferSystem: boolean,
      suppressTransitions: boolean = false,
    ): void {
      Iif (suppressTransitions) {
        document.documentElement.classList.add("no-transitions");
      }

      document.documentElement.dataset.theme = resolveDataTheme(themeId, preferSystem);

      Iif (suppressTransitions) {
        // Force a reflow so the no-transitions class takes effect before removal
        // eslint-disable-next-line no-unused-expressions
        document.documentElement.offsetHeight;
        requestAnimationFrame(() => {
          document.documentElement.classList.remove("no-transitions");
        });
      }
    }

    // Apply immediately on module load to prevent flash of wrong theme
    if (typeof document !== "undefined") {
      applyTheme(getStored(), getPreferSystem());
    }

    /** Build the current snapshot for useSyncExternalStore. */
    function getSnapshot(): ThemeSnapshot {
      if (lastSnapshot === undefined) {
        lastSnapshot = {
          themeId: getStored(),
          systemDark: getSystemDark(),
          preferSystem: getPreferSystem(),
        };
      }
      return lastSnapshot;
    }

    /** Subscribe to snapshot changes. */
    function subscribe(listener: () => void): () => void {
      listeners = [...listeners, listener];
      return () => {
        listeners = listeners.filter((l) => l !== listener);
      };
    }

    /** Result shape for the useTheme hook. */
    export interface UseThemeResult {
      /** The user's chosen theme ID. */
      themeId: string;
      /** The actually-applied data-theme value after resolving system preference. */
      resolvedThemeId: string;
      /** Set a new theme by ID. */
      setTheme: (nextId: string) => void;
      /** Whether the theme follows the OS light/dark preference. */
      preferSystem: boolean;
      /** Toggle the OS preference auto-switch behavior. */
      setPreferSystem: (prefer: boolean) => void;
    }

    /** React hook for reading and setting the application theme. */
    export function useTheme(): UseThemeResult {
      const snapshot = useSyncExternalStore(subscribe, getSnapshot);
      const { themeId, preferSystem } = snapshot;

      const resolvedThemeId: string = resolveDataTheme(themeId, preferSystem);

      const setTheme = useCallback((nextId: string) => {
        Iif (!THEME_IDS.has(nextId)) {
          return;
        }
        try {
          localStorage.setItem(STORAGE_KEY, nextId);
        } catch {
          // localStorage may be unavailable
        }
        applyTheme(nextId, getPreferSystem(), true);
        emitChange();
      }, []);

      const setPreferSystem = useCallback((prefer: boolean) => {
        try {
          localStorage.setItem(PREFER_SYSTEM_KEY, prefer ? "true" : "false");
        } catch {
          // localStorage may be unavailable
        }
        // When enabling preferSystem, convert variant ID to parent ID
        Iif (prefer) {
          const stored = getStored();
          const def = getThemeById(stored);
          Iif (def?.hidden) {
            const parent = findParentTheme(stored);
            Iif (parent) {
              try {
                localStorage.setItem(STORAGE_KEY, parent.id);
              } catch {
                // localStorage may be unavailable
              }
            }
          }
        }
        applyTheme(getStored(), prefer, true);
        emitChange();
      }, []);

      // Keep DOM in sync on mount/change
      useEffect(() => {
        applyTheme(themeId, preferSystem);
      }, [themeId, preferSystem]);

      useEffect(() => {
        Iif (typeof window === "undefined") {
          return undefined;
        }

        const mediaQueryList: MediaQueryList = window.matchMedia(MEDIA_QUERY);
        const handleChange = (): void => {
          const stored: string = getStored();
          const prefer: boolean = getPreferSystem();
          Iif (prefer) {
            const def = getThemeById(stored);
            // Parent theme with variants
            Iif (def?.variantDarkId && def.variantLightId) {
              applyTheme(stored, prefer);
            }
            // Concrete variant — resolve via parent
            Iif (def?.hidden) {
              const parent = findParentTheme(stored);
              Iif (parent?.variantDarkId && parent.variantLightId) {
                applyTheme(stored, prefer);
              }
            }
          }
          emitChange();
        };

        mediaQueryList.addEventListener("change", handleChange);

        return () => {
          mediaQueryList.removeEventListener("change", handleChange);
        };
      }, []);

      return { themeId, setTheme, resolvedThemeId, preferSystem, setPreferSystem };
    }