toggle-group.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use client"
  2. import * as React from "react"
  3. import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
  4. import { type VariantProps } from "class-variance-authority"
  5. import { cn } from "@/lib/utils"
  6. import { toggleVariants } from "@/components/ui/toggle"
  7. const ToggleGroupContext = React.createContext<
  8. VariantProps<typeof toggleVariants>
  9. >({
  10. size: "default",
  11. variant: "default",
  12. })
  13. const ToggleGroup = React.forwardRef<
  14. React.ElementRef<typeof ToggleGroupPrimitive.Root>,
  15. React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &
  16. VariantProps<typeof toggleVariants>
  17. >(({ className, variant, size, children, ...props }, ref) => (
  18. <ToggleGroupPrimitive.Root
  19. ref={ref}
  20. className={cn("flex items-center justify-center gap-1", className)}
  21. {...props}
  22. >
  23. <ToggleGroupContext.Provider value={{ variant, size }}>
  24. {children}
  25. </ToggleGroupContext.Provider>
  26. </ToggleGroupPrimitive.Root>
  27. ))
  28. ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName
  29. const ToggleGroupItem = React.forwardRef<
  30. React.ElementRef<typeof ToggleGroupPrimitive.Item>,
  31. React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &
  32. VariantProps<typeof toggleVariants>
  33. >(({ className, children, variant, size, ...props }, ref) => {
  34. const context = React.useContext(ToggleGroupContext)
  35. return (
  36. <ToggleGroupPrimitive.Item
  37. ref={ref}
  38. className={cn(
  39. toggleVariants({
  40. variant: context.variant || variant,
  41. size: context.size || size,
  42. }),
  43. className
  44. )}
  45. {...props}
  46. >
  47. {children}
  48. </ToggleGroupPrimitive.Item>
  49. )
  50. })
  51. ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName
  52. export { ToggleGroup, ToggleGroupItem }