toggle-group.tsx raw

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