78 lines
2.1 KiB
TypeScript
78 lines
2.1 KiB
TypeScript
import {
|
|
type DetailedHTMLProps,
|
|
type HTMLAttributes,
|
|
useEffect,
|
|
useState,
|
|
} from "react";
|
|
import { twMerge } from "tailwind-merge";
|
|
|
|
export type TWUI_TOGGLE_PROPS = DetailedHTMLProps<
|
|
HTMLAttributes<HTMLDivElement>,
|
|
HTMLDivElement
|
|
> & {
|
|
circleProps?: DetailedHTMLProps<
|
|
HTMLAttributes<HTMLDivElement>,
|
|
HTMLDivElement
|
|
>;
|
|
default_active?: boolean;
|
|
changeHandler?: (checked: boolean) => void;
|
|
};
|
|
|
|
/**
|
|
* # Toggle Component
|
|
* @className_wrapper twui-toggle-wrapper
|
|
* @className_circle twui-toggle-circle
|
|
*/
|
|
export default function Toggle({
|
|
circleProps,
|
|
default_active,
|
|
changeHandler,
|
|
...props
|
|
}: TWUI_TOGGLE_PROPS) {
|
|
const [active, setActive] = useState(default_active || false);
|
|
const [ready, setReady] = useState(false);
|
|
|
|
useEffect(() => {
|
|
if (!ready) return;
|
|
changeHandler?.(active);
|
|
}, [active]);
|
|
|
|
useEffect(() => {
|
|
setTimeout(() => {
|
|
setReady(true);
|
|
}, 200);
|
|
}, []);
|
|
|
|
return (
|
|
<div
|
|
{...props}
|
|
className={twMerge(
|
|
"flex flex-row items-center w-[40px] p-[3px] transition-all",
|
|
"border border-slate-300 dark:border-white/30 border-solid rounded-full",
|
|
active ? "justify-end" : "justify-start",
|
|
"twui-toggle-wrapper",
|
|
props.className,
|
|
)}
|
|
onClick={() => {
|
|
setActive(!active);
|
|
}}
|
|
>
|
|
{typeof active == "undefined" ? (
|
|
<div className="w-3.5 h-3.5 twui-toggle-circle"></div>
|
|
) : (
|
|
<div
|
|
{...circleProps}
|
|
className={twMerge(
|
|
"w-3.5 h-3.5 rounded-full ",
|
|
active
|
|
? "bg-blue-600 dark:bg-blue-500"
|
|
: "bg-slate-300 dark:bg-white/40",
|
|
"twui-toggle-circle",
|
|
circleProps?.className,
|
|
)}
|
|
></div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|