toggle-group.tsx 1.7 KB

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