All files / components/ColorScheme usePersistedColorScheme.ts

100% Statements 27/27
100% Branches 6/6
100% Functions 1/1
100% Lines 27/27

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 281x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 2x 3x 1x 2x 5x 5x 5x 1x 1x 5x 5x 5x 5x  
import { useCallback, useState } from 'react';
 
import type { ColorScheme, ColorSchemeOutput } from './ColorScheme';
import { COLOR_SCHEMES } from './colorSchemeConstants';
 
const COLOR_SCHEME_STORED_KEY = 'fratch-color-scheme';
 
export default function usePersistedColorScheme(
  defaultColorScheme: ColorScheme
): ColorSchemeOutput {
  const storedData = globalThis.localStorage.getItem(COLOR_SCHEME_STORED_KEY);
 
  const [colorScheme, setInnerColorScheme] = useState<ColorScheme>(
    storedData === COLOR_SCHEMES.DARK
      ? COLOR_SCHEMES.DARK
      : storedData === COLOR_SCHEMES.LIGHT
        ? COLOR_SCHEMES.LIGHT
        : defaultColorScheme
  );
 
  const setColorScheme = useCallback((newColorScheme: ColorScheme): void => {
    globalThis.localStorage.setItem(COLOR_SCHEME_STORED_KEY, newColorScheme);
    setInnerColorScheme(newColorScheme);
  }, []);
 
  return [colorScheme, setColorScheme];
}