web-humas-fe/components/theme-switch.tsx

86 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-01-05 06:57:30 +00:00
"use client";
import { FC } from "react";
import { VisuallyHidden } from "@react-aria/visually-hidden";
2025-02-13 08:25:39 +00:00
import { SwitchProps, useSwitch } from "@heroui/switch";
2024-01-05 06:57:30 +00:00
import { useTheme } from "next-themes";
2024-01-29 06:38:26 +00:00
import { useIsSSR } from "@react-aria/ssr";
2024-01-05 06:57:30 +00:00
import clsx from "clsx";
import { SunFilledIcon, MoonFilledIcon } from "@/components/icons";
export interface ThemeSwitchProps {
2025-02-24 12:24:58 +00:00
className?: string;
classNames?: SwitchProps["classNames"];
2024-01-05 06:57:30 +00:00
}
export const ThemeSwitch: FC<ThemeSwitchProps> = ({
2025-02-24 12:24:58 +00:00
className,
classNames,
2024-01-05 06:57:30 +00:00
}) => {
2025-02-24 12:24:58 +00:00
const { theme, setTheme } = useTheme();
const isSSR = useIsSSR();
2024-01-05 06:57:30 +00:00
2025-02-24 12:24:58 +00:00
const onChange = () => {
theme === "light" ? setTheme("dark") : setTheme("light");
};
2024-01-05 06:57:30 +00:00
2025-02-24 12:24:58 +00:00
const {
Component,
slots,
isSelected,
getBaseProps,
getInputProps,
getWrapperProps,
} = useSwitch({
isSelected: theme === "light" || isSSR,
"aria-label": `Switch to ${
theme === "light" || isSSR ? "dark" : "light"
} mode`,
onChange,
});
2024-01-05 06:57:30 +00:00
2025-02-24 12:24:58 +00:00
return (
<Component
{...getBaseProps({
className: clsx(
"px-px transition-opacity hover:opacity-80 cursor-pointer",
className,
classNames?.base
),
})}
>
2025-04-17 13:04:04 +00:00
{/* <VisuallyHidden>
2025-02-24 12:24:58 +00:00
<input {...getInputProps()} />
2025-04-17 13:04:04 +00:00
</VisuallyHidden> */}
<input {...getInputProps()} />
2025-02-24 12:24:58 +00:00
<div
{...getWrapperProps()}
className={slots.wrapper({
class: clsx(
[
"w-auto h-auto",
"bg-transparent",
"rounded-lg",
"flex items-center justify-center",
"group-data-[selected=true]:bg-transparent",
"!text-default-500",
"pt-px",
"px-0",
"mx-0",
],
classNames?.wrapper
),
})}
>
{!isSelected || isSSR ? (
<SunFilledIcon size={16} />
) : (
<MoonFilledIcon size={16} />
)}
</div>
</Component>
);
2024-01-05 06:57:30 +00:00
};