Skip to content

Commit 1243a9f

Browse files
committed
feat: add keyboard shortcut for toggling theme in ThemeProvider component
1 parent 316576e commit 1243a9f

1 file changed

Lines changed: 35 additions & 1 deletion

File tree

components/theme-provider.tsx

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,39 @@
11
"use client";
22

3-
import { ThemeProvider as NextThemesProvider } from "next-themes";
3+
import { ThemeProvider as NextThemesProvider, useTheme } from "next-themes";
4+
import { useEffect } from "react";
5+
6+
const ThemeShortcut = () => {
7+
const { setTheme, resolvedTheme } = useTheme();
8+
9+
useEffect(() => {
10+
const down = (e: KeyboardEvent) => {
11+
if (
12+
(e.key === "d" || e.key === "D") &&
13+
!e.metaKey &&
14+
!e.ctrlKey &&
15+
!e.altKey
16+
) {
17+
if (
18+
(e.target instanceof HTMLElement && e.target.isContentEditable) ||
19+
e.target instanceof HTMLInputElement ||
20+
e.target instanceof HTMLTextAreaElement ||
21+
e.target instanceof HTMLSelectElement
22+
) {
23+
return;
24+
}
25+
26+
e.preventDefault();
27+
setTheme(resolvedTheme === "dark" ? "light" : "dark");
28+
}
29+
};
30+
31+
document.addEventListener("keydown", down);
32+
return () => document.removeEventListener("keydown", down);
33+
}, [resolvedTheme, setTheme]);
34+
35+
return null;
36+
};
437

538
export const ThemeProvider = ({
639
children,
@@ -14,6 +47,7 @@ export const ThemeProvider = ({
1447
enableColorScheme
1548
{...props}
1649
>
50+
<ThemeShortcut />
1751
{children}
1852
</NextThemesProvider>
1953
);

0 commit comments

Comments
 (0)