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(
|
2026-09-19 15:05:02 +08:00
|
|
|
"relative inline-flex h-5 w-9 shrink-0 items-center rounded-full p-0.5",
|
|
|
|
|
"after:absolute after:left-1/2 after:top-1/2 after:h-11 after:w-11 after:-translate-x-1/2 after:-translate-y-1/2 after:content-['']",
|
|
|
|
|
"transition-colors duration-200 ease-out motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
2026-07-13 13:11:46 +08:00
|
|
|
checked
|
2026-09-19 15:05:02 +08:00
|
|
|
? "bg-foreground"
|
|
|
|
|
: "bg-muted-foreground/25 hover:bg-muted-foreground/30",
|
2026-07-13 13:11:46 +08:00
|
|
|
disabled && "cursor-default opacity-60",
|
2026-09-19 15:05:02 +08:00
|
|
|
disabled && !checked && "hover:bg-muted-foreground/25",
|
2026-07-13 13:11:46 +08:00
|
|
|
)}
|
|
|
|
|
>
|
|
|
|
|
<span
|
|
|
|
|
aria-hidden
|
|
|
|
|
className={cn(
|
2026-09-19 15:05:02 +08:00
|
|
|
"h-4 w-4 rounded-full bg-background shadow-sm",
|
|
|
|
|
"transition-transform duration-200 ease-out motion-reduce:transition-none",
|
2026-07-13 13:11:46 +08:00
|
|
|
checked ? "translate-x-[16px]" : "translate-x-0",
|
|
|
|
|
)}
|
|
|
|
|
/>
|
|
|
|
|
<span className="sr-only">{label}</span>
|
|
|
|
|
</button>
|
|
|
|
|
);
|
|
|
|
|
}
|