toggle-group.tsx73 lines, 1.9 KB
| 1 | "use client" |
| 2 | |
| 3 | import * as React from "react" |
| 4 | import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group" |
| 5 | import { type VariantProps } from "class-variance-authority" |
| 6 | |
| 7 | import { cn } from "@/lib/utils" |
| 8 | import { toggleVariants } from "@/components/ui/toggle" |
| 9 | |
| 10 | const ToggleGroupContext = React.createContext< |
| 11 | VariantProps<typeof toggleVariants> |
| 12 | >({ |
| 13 | size: "default", |
| 14 | variant: "default", |
| 15 | }) |
| 16 | |
| 17 | function ToggleGroup({ |
| 18 | className, |
| 19 | variant, |
| 20 | size, |
| 21 | children, |
| 22 | ...props |
| 23 | }: React.ComponentProps<typeof ToggleGroupPrimitive.Root> & |
| 24 | VariantProps<typeof toggleVariants>) { |
| 25 | return ( |
| 26 | <ToggleGroupPrimitive.Root |
| 27 | data-slot="toggle-group" |
| 28 | data-variant={variant} |
| 29 | data-size={size} |
| 30 | className={cn( |
| 31 | "group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs", |
| 32 | className |
| 33 | )} |
| 34 | {...props} |
| 35 | > |
| 36 | <ToggleGroupContext.Provider value={{ variant, size }}> |
| 37 | {children} |
| 38 | </ToggleGroupContext.Provider> |
| 39 | </ToggleGroupPrimitive.Root> |
| 40 | ) |
| 41 | } |
| 42 | |
| 43 | function ToggleGroupItem({ |
| 44 | className, |
| 45 | children, |
| 46 | variant, |
| 47 | size, |
| 48 | ...props |
| 49 | }: React.ComponentProps<typeof ToggleGroupPrimitive.Item> & |
| 50 | VariantProps<typeof toggleVariants>) { |
| 51 | const context = React.useContext(ToggleGroupContext) |
| 52 | |
| 53 | return ( |
| 54 | <ToggleGroupPrimitive.Item |
| 55 | data-slot="toggle-group-item" |
| 56 | data-variant={context.variant || variant} |
| 57 | data-size={context.size || size} |
| 58 | className={cn( |
| 59 | toggleVariants({ |
| 60 | variant: context.variant || variant, |
| 61 | size: context.size || size, |
| 62 | }), |
| 63 | "min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l", |
| 64 | className |
| 65 | )} |
| 66 | {...props} |
| 67 | > |
| 68 | {children} |
| 69 | </ToggleGroupPrimitive.Item> |
| 70 | ) |
| 71 | } |
| 72 | |
| 73 | export { ToggleGroup, ToggleGroupItem } |