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

70.83% Statements 51/72
59.21% Branches 45/76
30% Functions 3/10
82.69% Lines 43/52

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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173                                                                                                        33914x       941x   941x 941x     941x     941x 941x   941x 941x 941x     1111x 941x 941x   941x   82x 82x 82x 1111x           941x   45x     45x 1373x   941x                       1882x 274x             85x   1111x 85x       43x     941x 1026x 274x   1026x 274x     822x         33914x   33914x         45x                         274x         2037x   1489x   1763x 4705x      
"use client";
 
import { Check } from "lucide-react";
import * as React from "react";
import {
  AccessControlledProps,
  useAccessControlledState,
} from "@/ahuora-design-system/ui/accessControlled";
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 extends AccessControlledProps {
  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;
  disabled?: boolean;
  open?: boolean;
  onOpenChange?: (isOpen: boolean) => void;
}
 
export const Combobox: React.FC<ComboboxProps> = ({
  options,
  selectedValues,
  onChange,
  searchPlaceholder = "Search...",
  renderItem,
  emptyMessage = "No options found.",
  noGroupItemsMessage = "No items selected.",
  trigger,
  renderSelectedValues,
  disabled = false,
  open: controlledOpen,
  onOpenChange,
  writeAccessOnly = true,
  hideIfNoAccess = false,
}) => {
  const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false);
  const commandList = React.useRef<HTMLDivElement>(null);
  const { lacksWriteAccess, shouldHide } = useAccessControlledState({
    writeAccessOnly,
    hideIfNoAccess,
  });
  const isDisabled = disabled || lacksWriteAccess;
  const open = controlledOpen ?? uncontrolledOpen;
 
  const handleOpenChange = React.useCallback(
    (isOpen: boolean) => {
      const nextOpen = isDisabled ? false : isOpen;
      setUncontrolledOpen(nextOpen);
      onOpenChange?.(nextOpen);
    },
    [isDisabled, onOpenChange],
  );
 
  Iif (shouldHide) return null;
 
  const handleToggle = (value: string) => {
    Iif (isDisabled) return;
    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={handleOpenChange} 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(handleOpenChange)}</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 (
                    groupHasOptions && (
                      <CommandGroup key={idx} heading={option.label}>
                        {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>
                          );
                        })}
                      </CommandGroup>
                    )
                  );
                }
 
                if (option.type === "separator") {
                  return <CommandSeparator key={idx} />;
                }
 
                return null;
              })}
            </ScrollArea>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
};