All files / src/ahuora-design-system/ui combobox.tsx

90% Statements 18/20
77.27% Branches 17/22
87.5% Functions 7/8
90% Lines 18/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150                                                                                          49x                     703x 703x   703x 36x     36x     703x 355446x                 703x                                 34x                 2812x   2109x 2109x       355446x     355446x       36x                                       703x 703x                        
"use client";
 
import { Check } from "lucide-react";
import * as React from "react";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
} from "@/ahuora-design-system/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/ahuora-design-system/ui/popover";
import { cn } from "@/lib/utils";
import { ScrollArea } from "./scroll-area";
 
export interface ComboboxOption {
  value: string;
  label: string;
}
 
export interface ComboboxProps {
  options: {
    type: "group" | "item" | "separator";
    label?: string; // Only for groups
    options?: ComboboxOption[]; // Only for groups
    value?: string; // Only for items
  }[];
  selectedValues: string[];
  onChange: (values: string[]) => void;
  searchPlaceholder?: string;
  renderItem?: (option: ComboboxOption, isSelected: boolean) => React.ReactNode;
  emptyMessage?: string;
  noGroupItemsMessage?: React.ReactNode;
  trigger: React.ReactNode;
  renderSelectedValues?: (
    setOpen?: (isOpen: boolean) => void,
  ) => React.ReactNode;
}
 
export const Combobox: React.FC<ComboboxProps> = ({
  options,
  selectedValues,
  onChange,
  searchPlaceholder = "Search...",
  renderItem,
  emptyMessage = "No options found.",
  noGroupItemsMessage = "No items selected.",
  trigger,
  renderSelectedValues,
}) => {
  const [open, setOpen] = React.useState(false);
  const commandList = React.useRef<HTMLDivElement>(null);
 
  const handleToggle = (value: string) => {
    const updatedValues = selectedValues.includes(value)
      ? selectedValues.filter((v) => v !== value) // Remove if already selected
      : [...selectedValues, value]; // Add if not selected
    onChange(updatedValues);
  };
 
  const defaultRenderItem = (option: ComboboxOption, isSelected: boolean) => (
    <>
      {option.label}
      <Check
        size={16}
        className={cn("ml-auto", isSelected ? "opacity-100" : "opacity-0")}
      />
    </>
  );
 
  return (
    <Popover open={open} onOpenChange={setOpen} modal={true}>
      <PopoverTrigger asChild>{trigger}</PopoverTrigger>
      <PopoverContent
        className="w-[250px] p-2"
        side="right"
        sideOffset={26}
        align="start"
      >
        <Command position="popper" className="h-[300px]">
          {renderSelectedValues && (
            <div className="p-2">{renderSelectedValues(setOpen)}</div>
          )}
          <CommandInput
            placeholder={searchPlaceholder}
            onValueChange={() => {
              // Scroll to top when search input changes
              commandList.current
                ?.querySelector("[data-radix-scroll-area-viewport]")
                .scrollTo(0, 0);
            }}
          />
          <CommandList className="h-[300px]">
            <ScrollArea ref={commandList} className="h-[300px]">
              <CommandEmpty>{emptyMessage}</CommandEmpty>
              {options.map((option, idx) => {
                if (option.type === "group") {
                  const groupHasOptions =
                    option.options && option.options.length > 0;
                  return (
                    <CommandGroup key={idx} heading={option.label}>
                      {groupHasOptions
                        ? option.options?.map((item) => {
                            const isSelected = selectedValues?.includes(
                              item?.value,
                            );
                            return (
                              <CommandItem
                                key={item.value}
                                value={item.value}
                                onSelect={() => handleToggle(item.value)}
                              >
                                {renderItem
                                  ? renderItem(item, isSelected)
                                  : defaultRenderItem(item, isSelected)}
                              </CommandItem>
                            );
                          })
                        : (option.label === "Selected compounds" ||
                            option.label === "Recommended") && (
                            <small className="px-2 py-0 text-zinc-500 italic">
                              {option.label === "Selected compounds"
                                ? noGroupItemsMessage
                                : "No recommended compounds"}
                            </small>
                          )}
                    </CommandGroup>
                  );
                }
 
                if (option.type === "separator") {
                  return <CommandSeparator key={idx} />;
                }
 
                return null;
              })}
            </ScrollArea>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
};