toggle-group.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. function ToggleGroup({
  14. className,
  15. variant,
  16. size,
  17. children,
  18. ...props
  19. }: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
  20. VariantProps<typeof toggleVariants>) {
  21. return (
  22. <ToggleGroupPrimitive.Root
  23. data-slot="toggle-group"
  24. data-variant={variant}
  25. data-size={size}
  26. className={cn(
  27. "group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
  28. className
  29. )}
  30. {...props}
  31. >
  32. <ToggleGroupContext.Provider value={{ variant, size }}>
  33. {children}
  34. </ToggleGroupContext.Provider>
  35. </ToggleGroupPrimitive.Root>
  36. )
  37. }
  38. function ToggleGroupItem({
  39. className,
  40. children,
  41. variant,
  42. size,
  43. ...props
  44. }: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
  45. VariantProps<typeof toggleVariants>) {
  46. const context = React.useContext(ToggleGroupContext)
  47. return (
  48. <ToggleGroupPrimitive.Item
  49. data-slot="toggle-group-item"
  50. data-variant={context.variant || variant}
  51. data-size={context.size || size}
  52. className={cn(
  53. toggleVariants({
  54. variant: context.variant || variant,
  55. size: context.size || size,
  56. }),
  57. "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",
  58. className
  59. )}
  60. {...props}
  61. >
  62. {children}
  63. </ToggleGroupPrimitive.Item>
  64. )
  65. }
  66. export { ToggleGroup, ToggleGroupItem }