aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/helpers/themes.ts
blob: 66c06529d1623f5c66b4cb27c33b8c318c82f02c (plain)
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
import type { Theme } from '../../types';
import { VALID_THEMES } from '../constants';

/**
 * Check if the user prefers dark color scheme.
 *
 * @returns {boolean|undefined} True if `prefers-color-scheme` is set to `dark`.
 */
export const prefersDarkScheme = (): boolean | undefined => {
  if (typeof window === 'undefined') return undefined;

  return window.matchMedia('(prefers-color-scheme: dark)').matches;
};

/**
 * Retrieve the theme to use depending on the user system theme.
 */
export const getThemeFromSystem = () => {
  if (prefersDarkScheme()) return 'dark';
  return 'light';
};

export const themeValidator = (value: unknown): value is Theme =>
  typeof value === 'string' &&
  (VALID_THEMES as readonly string[]).includes(value);