| 1 | "use client"; |
| 2 | |
| 3 | import { Switch as SwitchPrimitive } from "@base-ui/react/switch"; |
| 4 | |
| 5 | import { cn } from "~/lib/utils"; |
| 6 | |
| 7 | /** |
| 8 | * `mixed` renders the thumb centred on a muted track for a selection whose |
| 9 | * targets disagree (the macOS mixed-state convention). It is presentational: |
| 10 | * the caller still decides what a click sets, usually on for everyone. |
| 11 | */ |
| 12 | function Switch({ |
| 13 | className, |
| 14 | size = "default", |
| 15 | mixed = false, |
| 16 | ...props |
| 17 | }: SwitchPrimitive.Root.Props & { size?: "default" | "sm"; mixed?: boolean }) { |
| 18 | return ( |
| 19 | <SwitchPrimitive.Root |
| 20 | className={cn( |
| 21 | "inline-flex h-[calc(var(--thumb-size)+2px)] w-[calc(var(--thumb-size)*2-2px)] shrink-0 cursor-pointer items-center rounded-full p-[2px] outline-none transition-[background-color,box-shadow] duration-200 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-checked:bg-primary data-unchecked:bg-input data-disabled:cursor-not-allowed data-disabled:opacity-64 data-[mixed]:bg-input", |
| 22 | size === "sm" |
| 23 | ? "[--thumb-size:--spacing(4)] sm:[--thumb-size:--spacing(3.5)]" |
| 24 | : "[--thumb-size:--spacing(5)] sm:[--thumb-size:--spacing(4)]", |
| 25 | className, |
| 26 | )} |
| 27 | data-size={size} |
| 28 | data-slot="switch" |
| 29 | data-mixed={mixed ? "" : undefined} |
| 30 | // Base UI copies every key we pass, even `undefined`, over its own |
| 31 | // aria-checked. Only pass the attribute when mixed so the real state |
| 32 | // survives for screen readers. |
| 33 | {...(mixed ? { "aria-checked": "mixed" as const } : {})} |
| 34 | {...props} |
| 35 | > |
| 36 | <SwitchPrimitive.Thumb |
| 37 | className={cn( |
| 38 | "pointer-events-none block size-[calc(var(--thumb-size)-2px)] shrink-0 origin-left in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:not-data-disabled:scale-x-110 in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.1)] rounded-(--thumb-size) bg-background shadow-sm/5 [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s] data-checked:origin-right data-checked:translate-x-[calc(var(--thumb-size)-4px)]", |
| 39 | mixed && |
| 40 | "translate-x-[calc((var(--thumb-size)-4px)/2)] opacity-70 data-checked:translate-x-[calc((var(--thumb-size)-4px)/2)]", |
| 41 | )} |
| 42 | data-slot="switch-thumb" |
| 43 | /> |
| 44 | </SwitchPrimitive.Root> |
| 45 | ); |
| 46 | } |
| 47 | |
| 48 | export { Switch }; |