|
1 | | -import * as SwitchPrimitives from '@radix-ui/react-switch'; |
| 1 | +import { useState } from 'react'; |
2 | 2 |
|
3 | 3 | import { COLORS, SwitchColor } from '@/shared/lib/colors'; |
4 | 4 |
|
5 | | -type Props = React.ComponentProps<typeof SwitchPrimitives.Root> & { |
| 5 | +type Props = Omit<React.ComponentProps<'button'>, 'onClick'> & { |
6 | 6 | /** |
7 | 7 | * color of the switch. |
8 | 8 | * @default 'primary' |
9 | 9 | */ |
10 | 10 | color?: SwitchColor; |
| 11 | + checked?: boolean; |
| 12 | + defaultChecked?: boolean; |
| 13 | + onCheckedChange?: (checked: boolean) => void; |
11 | 14 | }; |
12 | 15 |
|
13 | | -export function Switch({ color = 'primary', ...props }: Props) { |
| 16 | +export function Switch({ |
| 17 | + color = 'primary', |
| 18 | + checked, |
| 19 | + defaultChecked = false, |
| 20 | + onCheckedChange, |
| 21 | + className, |
| 22 | + disabled, |
| 23 | + ...props |
| 24 | +}: Props) { |
| 25 | + const [uncontrolledChecked, setUncontrolledChecked] = useState(defaultChecked); |
| 26 | + const isChecked = checked ?? uncontrolledChecked; |
| 27 | + |
| 28 | + const handleClick = () => { |
| 29 | + if (disabled) return; |
| 30 | + |
| 31 | + const next = !isChecked; |
| 32 | + if (checked === undefined) { |
| 33 | + setUncontrolledChecked(next); |
| 34 | + } |
| 35 | + onCheckedChange?.(next); |
| 36 | + }; |
| 37 | + |
14 | 38 | return ( |
15 | | - <SwitchPrimitives.Root |
| 39 | + <button |
16 | 40 | {...props} |
17 | | - className="group flex h-3.5 w-7 items-center rounded-full shadow-lg data-[state=checked]:bg-[var(--switch-color)] data-[state=unchecked]:bg-gray-500" |
18 | | - style={color && ({ '--switch-color': COLORS[color] } as React.CSSProperties)} |
| 41 | + type="button" |
| 42 | + role="switch" |
| 43 | + disabled={disabled} |
| 44 | + onClick={handleClick} |
| 45 | + aria-checked={isChecked} |
| 46 | + data-state={isChecked ? 'checked' : 'unchecked'} |
| 47 | + className={[ |
| 48 | + 'group flex h-3.5 w-7 items-center rounded-full shadow-lg', |
| 49 | + 'data-[state=checked]:bg-[var(--switch-color)]', |
| 50 | + 'data-[state=unchecked]:bg-gray-500', |
| 51 | + className, |
| 52 | + ] |
| 53 | + .filter(Boolean) |
| 54 | + .join(' ')} |
| 55 | + style={{ '--switch-color': COLORS[color] } as React.CSSProperties} |
19 | 56 | > |
20 | | - <SwitchPrimitives.Thumb className="h-5 w-5 -translate-x-1.5 rounded-full bg-white shadow-inner drop-shadow-md duration-100 group-data-[state=checked]:translate-x-3.5" /> |
21 | | - </SwitchPrimitives.Root> |
| 57 | + <span className="h-5 w-5 -translate-x-1.5 rounded-full bg-white shadow-inner drop-shadow-md duration-100 group-data-[state=checked]:translate-x-3.5" /> |
| 58 | + </button> |
22 | 59 | ); |
23 | 60 | } |
0 commit comments