aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/organisms/forms/theme-toggle/theme-toggle.tsx
blob: da303d38c9435cb306dd29c15937caaf9e3d35dc (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
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
import { useTheme } from 'next-themes';
import { ChangeEvent, FC } from 'react';
import { useIntl } from 'react-intl';
import { Legend, Moon, Sun } from '../../../atoms';
import { Switch, SwitchOption, SwitchProps } from '../../../molecules';

export type ThemeToggleProps = Omit<
  SwitchProps,
  'isInline' | 'items' | 'name' | 'onSwitch' | 'value'
>;

/**
 * ThemeToggle component
 *
 * Render a Toggle component to set theme.
 */
export const ThemeToggle: FC<ThemeToggleProps> = (props) => {
  const intl = useIntl();
  const { resolvedTheme, setTheme } = useTheme();
  const isDarkTheme = resolvedTheme === 'dark';

  const updateTheme = (e: ChangeEvent<HTMLInputElement>) => {
    setTheme(e.target.value === 'light' ? 'light' : 'dark');
  };

  const themeLabel = intl.formatMessage({
    defaultMessage: 'Theme:',
    description: 'ThemeToggle: theme label',
    id: 'suXOBu',
  });
  const lightThemeLabel = intl.formatMessage({
    defaultMessage: 'Light theme',
    description: 'ThemeToggle: light theme label',
    id: 'Ygea7s',
  });
  const darkThemeLabel = intl.formatMessage({
    defaultMessage: 'Dark theme',
    description: 'ThemeToggle: dark theme label',
    id: '2QwvtS',
  });

  const options: [SwitchOption, SwitchOption] = [
    {
      id: 'theme-light',
      label: (
        <>
          <span className="screen-reader-text">{lightThemeLabel}</span>
          <Sun />
        </>
      ),
      value: 'light',
    },
    {
      id: 'theme-dark',
      label: (
        <>
          <span className="screen-reader-text">{darkThemeLabel}</span>
          <Moon />
        </>
      ),
      value: 'dark',
    },
  ];

  return (
    <Switch
      {...props}
      isInline
      items={options}
      legend={<Legend>{themeLabel}</Legend>}
      name="theme"
      onSwitch={updateTheme}
      value={isDarkTheme ? 'dark' : 'light'}
    />
  );
};