2026-09-10 11:10:51 +08:00
|
|
|
import type { ComponentProps } from "react";
|
2026-07-13 13:11:46 +08:00
|
|
|
import { cn } from "@/lib/utils";
|
|
|
|
|
|
|
|
|
|
export function ToggleButton({
|
|
|
|
|
checked,
|
|
|
|
|
disabled,
|
|
|
|
|
onChange,
|
|
|
|
|
ariaLabel,
|
|
|
|
|
label,
|
2026-09-10 11:10:51 +08:00
|
|
|
...accessibility
|
2026-07-13 13:11:46 +08:00
|
|
|
}: {
|
|
|
|
|
checked: boolean;
|
|
|
|
|
disabled?: boolean;
|
|
|
|
|
onChange: (checked: boolean) => void;
|
|
|
|
|
ariaLabel?: string;
|
|
|
|
|
label: string;
|
2026-09-10 11:10:51 +08:00
|
|
|
} & Pick<ComponentProps<"button">, "id" | "aria-describedby" | "aria-invalid">) {
|
2026-07-13 13:11:46 +08:00
|
|
|
return (
|
|
|
|
|
<button
|
2026-09-10 11:10:51 +08:00
|
|
|
{...accessibility}
|
2026-07-13 13:11:46 +08:00
|
|
|
type="button"
|
|
|
|
|
role="switch"
|
|
|
|
|
aria-checked={checked}
|
|
|
|
|
aria-label={ariaLabel ?? label}
|
|
|
|
|
disabled={disabled}
|
|
|
|
|
onClick={() => {
|
|
|
|
|
if (!disabled) onChange(!checked);
|
|
|
|
|
}}
|
|
|
|
|
className={cn(
|
|
|
|
|
"relative inline-flex h-[22px] w-[38px] shrink-0 items-center rounded-full p-[2px]",
|
|
|
|
|
"transition-colors duration-200 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
|
|
|
|
checked
|
2026-07-23 17:47:20 +08:00
|
|
|
? "bg-[#2997FF]"
|
|
|
|
|
: "bg-muted-foreground/20 hover:bg-muted-foreground/25",
|
2026-07-13 13:11:46 +08:00
|
|
|
disabled && "cursor-default opacity-60",
|
|
|
|
|
disabled && checked && "hover:bg-[#2997FF]",
|
2026-07-23 17:47:20 +08:00
|
|
|
disabled && !checked && "hover:bg-muted-foreground/20",
|
2026-07-13 13:11:46 +08:00
|
|
|
)}
|
|
|
|
|
>
|
|
|
|
|
<span
|
|
|
|
|
aria-hidden
|
|
|
|
|
className={cn(
|
2026-07-23 17:47:20 +08:00
|
|
|
"h-[18px] w-[18px] rounded-full bg-background",
|
2026-07-13 13:11:46 +08:00
|
|
|
"transition-transform duration-200 ease-out",
|
|
|
|
|
checked ? "translate-x-[16px]" : "translate-x-0",
|
|
|
|
|
)}
|
|
|
|
|
/>
|
|
|
|
|
<span className="sr-only">{label}</span>
|
|
|
|
|
</button>
|
|
|
|
|
);
|
|
|
|
|
}
|