Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

feat(useSetDocumentColorScheme): set document color scheme css hook #2880

Merged
merged 8 commits into from Oct 6, 2022
16 changes: 7 additions & 9 deletions src/components/DarkModeToggle/index.tsx
@@ -1,25 +1,23 @@
import React, { useEffect } from 'react';
import React from 'react';
import { useTheme } from '@skagami/gatsby-plugin-dark-mode';
import ModeNightIcon from '@mui/icons-material/ModeNight';
import BrightnessMediumIcon from '@mui/icons-material/BrightnessMedium';
import { useUpdateDocumentColorScheme } from '../../hooks/useUpdateDocumentColorScheme';
import styles from './index.module.scss';

const DarkModeToggle = () => {
const [theme, toggleTheme] = useTheme();

useEffect(() => {
// This is responsible for setting the color-scheme of the scroll-bars
if (typeof document === 'object' && document.documentElement) {
document.documentElement.style['color-scheme'] = theme;
}
}, [theme]);
const updateColorScheme = useUpdateDocumentColorScheme(theme);

const handleThemeOnClick = (isKeyPress = false): void => {
if (isKeyPress) {
return;
}

toggleTheme(theme === 'light' ? 'dark' : 'light');
const newTheme = theme === 'light' ? 'dark' : 'light';

toggleTheme(newTheme);
updateColorScheme(newTheme);
};

return (
Expand Down
20 changes: 20 additions & 0 deletions src/hooks/__tests__/useUpdateDocumentColorScheme.test.tsx
@@ -0,0 +1,20 @@
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { useUpdateDocumentColorScheme } from '../useUpdateDocumentColorScheme';

describe('useUpdateDocumentColorScheme', () => {
const HookRenderer = ({ theme }: { theme: string | null }): JSX.Element => {
const updateColorScheme = useUpdateDocumentColorScheme();

return <button type="button" onClick={() => updateColorScheme(theme)} />;
};

it('should update color scheme of document', () => {
render(<HookRenderer theme="testTheme" />);

const button = screen.getByRole('button');
fireEvent.click(button);

expect(document.documentElement.style['color-scheme']).toEqual('testTheme');
});
});
16 changes: 16 additions & 0 deletions src/hooks/useUpdateDocumentColorScheme.ts
@@ -0,0 +1,16 @@
import { useEffect, useState } from 'react';

export const useUpdateDocumentColorScheme = (
defaultTheme: string | null = null
) => {
const [currentTheme, setCurrentTheme] = useState(defaultTheme);

useEffect(() => {
// This is responsible for setting the color-scheme of the scroll-bars
if (typeof document === 'object' && document.documentElement) {
document.documentElement.style['color-scheme'] = currentTheme;
}
}, [currentTheme]);

return (theme: string | null) => setCurrentTheme(theme);
};