# All files / theme ColorSchemeProvider.tsx

97.1% Statements 235/242
63.63% Branches 7/11
50% Functions 2/4
97.1% Lines 235/242

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
    234
    235
    236
    237
    238
    239
    240
    241
    242
    2431x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    2x
    2x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x

    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    177x
    122x
    122x
    122x
    122x
    177x
    177x
    177x
    177x
    122x

    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    177x
    177x
    177x
    177x
     "use client";
    import {
      createContext,
      useContext,
      useEffect,
      useMemo,
      type ReactElement,
      type ReactNode,
    } from "react";
    import { useMediaQuery } from "../media-queries/useMediaQuery.js";
    import { type UseStateInitializer, type UseStateSetter } from "../types.js";
    import { useLocalStorage } from "../useLocalStorage.js";
    import { backgroundColorVar } from "./cssVars.js";
    import { getContrastRatio } from "./utils.js";

    /** @remarks \@since 6.0.0 */
    export type ColorScheme = "light" | "dark";

    /** @remarks \@since 6.0.0 */
    export type ColorSchemeMode = ColorScheme | "system";
    /** @remarks \@since 6.0.0 */
    export type SetColorSchemeMode = UseStateSetter<ColorSchemeMode>;

    /** @remarks \@since 6.0.0 */
    export interface ColorSchemeContext {
      /**
       * The current color scheme that is being used. This is only useful when the
       * {@link colorSchemeMode} is set to `"system"`.
       */
      colorScheme: ColorScheme;

      /**
       * The current color scheme mode that is being used by your app that should
       * default to the `$color-scheme` SCSS variable. If the
       * {@link setColorSchemeMode} is called, this will update to that new value.
       *
       * TODO: Figure out how to document this
       *
       * - `colorScheme` - only `light` or `dark` -- only useful when the `colorSchemeMode` is set to `system`
       * - `colorSchemeMode` - current **user** defined color scheme behavior? should default to `$color-scheme`, but will change based on `setColorSchemeMode`
       */
      colorSchemeMode: ColorSchemeMode;

      /**
       * A function to update the color scheme.
       *
       * @see {@link useColorScheme} for an example usage
       */
      setColorSchemeMode: SetColorSchemeMode;
    }

    const context = createContext<ColorSchemeContext>({
      colorScheme: "light",
      colorSchemeMode: "light",
      setColorSchemeMode() {
        if (process.env.NODE_ENV !== "production") {
          throw new Error("The `ColorSchemeProvider` has not been initialized.");
        }
      },
    });
    context.displayName = "ColorScheme";
    const { Provider } = context;

    /** @remarks \@since 6.0.0 */
    export type DefaultColorScheme = UseStateInitializer<ColorScheme>;

    /**
     * @example
     * Lazy Load Configurable Themes
     * ```tsx
     * import type { ChangeEvent, ReactElement } from "react";
     * import { lazy } from "react";
     * import { createRoot } from "react-doc/client";
     * import { Checkbox, ColorSchemeProvider, useColorScheme } from "@react-md/core";
     *
     * const DarkTheme = lazy(() => import("./DarkTheme"));
     * const SystemTheme = lazy(() => import("./SystemTheme"));
     *
     * function App(): ReactElement {
     *   const { colorScheme, colorSchemeMode, setColorSchemeMode } =
     *     useColorScheme();
     *
     *   const onChange = (event: ChangeEvent<HTMLInputElement>): void => {
     *     const { value } = event.currentTarget;
     *     if (value === "light" || value === "dark" || value === "system") {
     *       setColorSchemeMode(value);
     *     }
     *   };
     *
     *   return (
     *     <>
     *       {colorSchemeMode === "dark" && <DarkTheme />}
     *       {colorSchemeMode === "system" && <SystemTheme />}
     *       <Checkbox
     *         label="Light"
     *         value="light"
     *         checked={colorSchemeMode === "light"}
     *         onChange={onChange}
     *       />
     *       <Checkbox
     *         label="Dark"
     *         value="dark"
     *         checked={colorSchemeMode === "dark"}
     *         onChange={onChange}
     *       />
     *       <Checkbox
     *         label="System"
     *         value="system"
     *         checked={colorSchemeMode === "system"}
     *         onChange={onChange}
     *       />
     *     </>
     *   );
     * }
     *
     *
     * const root = createRoot(document.getElementById("root"));
     * root.render(
     *   <ColorSchemeProvider>
     *     <App />
     *   </ColorSchemeProvider>
     * );
     *
     * // DarkTheme.tsx
     * import { useHtmlClassName } from "@react-md/core";
     *
     * import styles from "./DarkTheme.module.scss";
     *
     * export default function DarkTheme(): null {
     *   useHtmlClassName(styles.theme);
     *   return null
     * }
     *
     * // DarkTheme.module.scss
     * @use "@react-md/core";
     *
     * .theme {
     *   @include core.use-dark-theme;
     * }
     * ```
     *
     * @remarks \@since 6.0.0
     */
    export function useColorScheme(): Readonly<ColorSchemeContext> {
      return useContext(context);
    }

    /** @remarks \@since 6.0.0 */
    export interface ColorSchemeProviderProps {
      /**
       * The current color scheme mode that is being used by your app. This should
       * match the `$color-scheme` SCSS variable.
       *
       * @defaultValue `"light"`
       */
      mode?: ColorSchemeMode;

      /**
       * Set this to a string like `"colorScheme"` if you want to store the user's
       * color scheme preference in local storage.
       *
       * @defaultValue `""`
       */
      localStorageKey?: string;

      /**
       * Set this to `true` to prevent a `<meta name="color-scheme" content="{COLOR_SCHEME}">`
       * from being added to the `document.head`.
       *
       * @defaultValue `false`
       */
      disableMetaTag?: boolean;
      children: ReactNode;
    }

    /**
     * **Client Component**
     *
     * @see {@link useColorScheme} for an example usage.
     * @remarks \@since 6.0.0
     */
    export function ColorSchemeProvider(
      props: ColorSchemeProviderProps
    ): ReactElement {
      const {
        children,
        mode = "light",
        localStorageKey = "",
        disableMetaTag,
      } = props;
      const { value: colorSchemeMode, setValue: setColorSchemeMode } =
        useLocalStorage({
          key: localStorageKey,
          defaultValue: mode,
          deserializer: (item) =>
            item === "light" || item === "dark" || item === "system" ? item : mode,
        });

      const prefersDarkTheme = useMediaQuery(
        "(prefers-color-scheme: dark)",
        colorSchemeMode !== "system"
      );
      const derivedColorScheme = prefersDarkTheme ? "dark" : "light";
      const colorScheme =
        colorSchemeMode === "system" ? derivedColorScheme : colorSchemeMode;

      const value = useMemo<ColorSchemeContext>(
        () => ({
          colorScheme,
          colorSchemeMode,
          setColorSchemeMode,
        }),
        [colorScheme, colorSchemeMode, setColorSchemeMode]
      );

      useEffect(() => {
        if (disableMetaTag || document.querySelector('meta[name="color-scheme"]')) {
          return;
        }

        // Adding the meta tag allows the default browser styles for form inputs to
        // be updated as well.
        //
        // Chrome and Firefox:
        // - the input type="number"'s spinner color will update from grey to white
        // - native `<select>` background color updates from grey/white to a dark color
        //
        // Chrome:
        // - the date/time/datetime icons will change from black to white
        // - the date/time/datetime pickers will use a darker theme instead of white
        const meta = document.createElement("meta");
        meta.name = "color-scheme";
        meta.content = colorSchemeMode === "system" ? colorScheme : colorSchemeMode;
        document.head.appendChild(meta);

        return () => {
          document.head.removeChild(meta);
        };
      }, [colorScheme, colorSchemeMode, disableMetaTag, mode]);

      return <Provider value={value}>{children}</Provider>;
    }