Skip to content

Commit

Permalink
fix(docs): prevent scrolling up on pressing theme change switch (#4233)
Browse files Browse the repository at this point in the history
  • Loading branch information
macci001 authored Dec 6, 2024
1 parent 3660566 commit 05d546e
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions apps/docs/components/theme-switch.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import {FC} from "react";
import {FC, ChangeEvent} from "react";
import {VisuallyHidden} from "@react-aria/visually-hidden";
import {SwitchProps, useSwitch} from "@nextui-org/react";
import {useTheme} from "next-themes";
Expand All @@ -22,20 +22,27 @@ export const ThemeSwitch: FC<ThemeSwitchProps> = ({className, classNames}) => {

const initialTheme = isSSR ? "light" : theme;

const onChange = () => {
theme === "light" ? setTheme("dark") : setTheme("light");
const handleThemeChange = (
e?: ChangeEvent<HTMLInputElement> | React.MouseEvent | React.KeyboardEvent,
) => {
e?.preventDefault();
e?.stopPropagation();

const newTheme = theme === "light" ? "dark" : "light";

setTheme(newTheme);

posthog.capture("ThemeChange", {
action: "click",
category: "theme",
data: theme === "light" ? "dark" : "light",
data: newTheme,
});
};

const {Component, slots, isSelected, getBaseProps, getInputProps, getWrapperProps} = useSwitch({
isSelected: initialTheme === "light",
"aria-label": `Switch to ${initialTheme === "light" ? "dark" : "light"} mode`,
onChange,
onChange: handleThemeChange as (event: ChangeEvent<HTMLInputElement>) => void,
});

return (
Expand All @@ -46,6 +53,12 @@ export const ThemeSwitch: FC<ThemeSwitchProps> = ({className, classNames}) => {
className,
classNames?.base,
),
onClick: handleThemeChange,
onKeyDown: (e: React.KeyboardEvent) => {
if (e.key === "Enter" || e.key === " ") {
handleThemeChange(e);
}
},
})}
>
<VisuallyHidden>
Expand Down

0 comments on commit 05d546e

Please sign in to comment.