All files / publisher/components/SearchAutocomplete SearchAutocomplete.tsx

46.42% Statements 13/28
14.28% Branches 1/7
47.05% Functions 8/17
42.3% Lines 11/26

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                                                                              48x 20x     48x             48x       48x         48x 20x 20x       48x                                         48x   24x                                                                                                                                                    
import { useState, useEffect } from "react";
import Downshift from "downshift";
import { useWatch } from "react-hook-form";
import { Button } from "@canonical/react-components";
 
import type {
  UseFormRegister,
  UseFormSetValue,
  UseFormGetValues,
  Control,
  FieldValues,
} from "react-hook-form";
 
type DataItem = {
  key: string;
  name: string;
};
 
type Props = {
  data: DataItem[];
  field: string;
  currentValues: string[];
  register: UseFormRegister<FieldValues>;
  setValue: UseFormSetValue<FieldValues>;
  getValues: UseFormGetValues<FieldValues>;
  control: Control<FieldValues>;
  disabled?: boolean;
};
 
function SearchAutocomplete({
  data,
  field,
  currentValues,
  register,
  setValue,
  getValues,
  control,
  disabled,
}: Props): React.JSX.Element {
  const [selections, setSelections] = useState(() => {
    return data.filter((value) => currentValues.includes(value.key));
  });
 
  const getNewSelectionKeys = (newSelections: DataItem[]): string => {
    return newSelections
      .map((selection: DataItem) => selection.key)
      .sort()
      .join(" ");
  };
 
  const shouldDirty = (newSelectionsKeys: string) => {
    return newSelectionsKeys !== getValues(field);
  };
 
  const selectionKeyValues = useWatch({
    control,
    name: field,
  });
 
  useEffect(() => {
    setSelections(() => {
      return data.filter((value) => selectionKeyValues.includes(value.key));
    });
  }, [selectionKeyValues]);
 
  return (
    <Downshift
      onChange={(selection) => {
        const newSelections = selections.concat([selection]);
        const newSelectionsKeys = getNewSelectionKeys(newSelections);
 
        setSelections(newSelections);
        setValue(field, newSelectionsKeys, {
          shouldDirty: shouldDirty(newSelectionsKeys),
        });
      }}
      itemToString={() => ""}
    >
      {({
        getInputProps,
        getItemProps,
        getMenuProps,
        isOpen,
        inputValue,
        highlightedIndex,
      }) => (
        <div className="p-multiselect">
          {selections.map((suggestion: DataItem) => (
            <span key={suggestion.key} className="p-multiselect__item">
              {suggestion.name}
              <Button
                type="button"
                style={{
                  backgroundColor: "transparent",
                  border: 0,
                  color: "inherit",
                  margin: 0,
                  padding: 0,
                }}
                onClick={() => {
                  const newSelections = selections.filter(
                    (item: DataItem) => item.key !== suggestion.key,
                  );
 
                  const newSelectionsKeys = getNewSelectionKeys(newSelections);
 
                  setSelections(newSelections);
                  setValue(field, newSelectionsKeys, {
                    shouldDirty: shouldDirty(newSelectionsKeys),
                  });
                }}
              >
                <i className="p-icon--close p-multiselect__item-remove">
                  Remove suggestion
                </i>
              </Button>
            </span>
          ))}
 
          <input type="hidden" {...register(field)} />
 
          <input
            type="text"
            className="p-multiselect__input"
            disabled={disabled}
            {...getInputProps()}
          />
 
          {isOpen && (
            <ul className="p-multiselect__options" {...getMenuProps()}>
              {data
                .filter(
                  (item) =>
                    !inputValue ||
                    item.key.toLowerCase().includes(inputValue) ||
                    item.name.toLowerCase().includes(inputValue),
                )
                .map((item, index) => (
                  <li
                    key={item.key}
                    className="p-multiselect__option"
                    {...getItemProps({
                      index,
                      item,
                      style: {
                        backgroundColor:
                          highlightedIndex === index ? "#f7f7f7" : "#fff",
                      },
                    })}
                  >
                    {item.name}
                  </li>
                ))}
            </ul>
          )}
        </div>
      )}
    </Downshift>
  );
}
 
export default SearchAutocomplete;