toggle-group.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group';
  2. import { type VariantProps } from 'class-variance-authority';
  3. import * as React from 'react';
  4. import { cn } from '@/common/helpers/cn';
  5. import { toggleVariants } from '@/shadcn/toggle';
  6. const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
  7. size: 'default',
  8. variant: 'default',
  9. });
  10. function ToggleGroup({
  11. className,
  12. variant,
  13. size,
  14. children,
  15. ...props
  16. }: React.ComponentProps<typeof ToggleGroupPrimitive.Root> & VariantProps<typeof toggleVariants>) {
  17. return (
  18. <ToggleGroupPrimitive.Root
  19. data-slot="toggle-group"
  20. data-variant={variant}
  21. data-size={size}
  22. className={cn('group/toggle-group flex items-center rounded-md data-[variant=outline]:shadow-xs', className)}
  23. {...props}
  24. >
  25. <ToggleGroupContext.Provider value={{ variant, size }}>{children}</ToggleGroupContext.Provider>
  26. </ToggleGroupPrimitive.Root>
  27. );
  28. }
  29. function ToggleGroupItem({
  30. className,
  31. children,
  32. variant,
  33. size,
  34. ...props
  35. }: React.ComponentProps<typeof ToggleGroupPrimitive.Item> & VariantProps<typeof toggleVariants>) {
  36. const context = React.useContext(ToggleGroupContext);
  37. return (
  38. <ToggleGroupPrimitive.Item
  39. data-slot="toggle-group-item"
  40. data-variant={context.variant || variant}
  41. data-size={context.size || size}
  42. className={cn(
  43. toggleVariants({
  44. variant: context.variant || variant,
  45. size: context.size || size,
  46. }),
  47. 'min-w-0 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',
  48. className,
  49. )}
  50. {...props}
  51. >
  52. {children}
  53. </ToggleGroupPrimitive.Item>
  54. );
  55. }
  56. export { ToggleGroup, ToggleGroupItem };