All files / publisher/pages/Listing/AdditionalInformation LicenseSearch.tsx

32.6% Statements 15/46
16.66% Branches 3/18
39.13% Functions 9/23
30.23% Lines 13/43

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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212                                                                              39x 39x     39x       39x 13x 13x           39x 26x   78x 78x       39x                                                                   39x                 26x                                                                                                                                                                                                                  
import {
  useState,
  SyntheticEvent,
  useEffect,
  Dispatch,
  SetStateAction,
} from "react";
import { UseFormRegister, UseFormSetValue, FieldValues } from "react-hook-form";
import Downshift from "downshift";
import { Button } from "@canonical/react-components";
 
import debounce from "../../../../libs/debounce";
 
type License = {
  key: string;
  name: string;
};
 
type Props = {
  licenses: Array<License>;
  license: string | undefined;
  register: UseFormRegister<FieldValues>;
  setValue: UseFormSetValue<FieldValues>;
  setLicense: Dispatch<SetStateAction<string>>;
  originalLicense: string;
};
 
function isDirty(newLicense: string, originalLicense: string) {
  return newLicense !== originalLicense;
}
 
function LicenseSearch({
  licenses,
  license,
  register,
  setValue,
  setLicense,
  originalLicense,
}: Props) {
  const [suggestions, setSuggestions] = useState<License[]>([]);
  const [selectedLicenseKeys, setSelectedLicenseKeys] = useState<string[]>(
    license?.split(" OR ") || [],
  );
  const [selectedLicenses, setSelectedLicenses] = useState<
    (License | undefined)[]
  >([]);
 
  useEffect(() => {
    if (license) {
      setSelectedLicenseKeys(license?.split(" OR "));
    } else E{
      setSelectedLicenseKeys([]);
    }
  }, [license]);
 
  useEffect(() => {
    setSelectedLicenses(
      selectedLicenseKeys
        .filter((key) => licenses.find((l) => l.key === key))
        .map((key) => licenses.find((l) => l.key === key)),
    );
  }, [selectedLicenseKeys]);
 
  return (
    <Downshift
      onChange={(selection) => {
        const newSelectedLicenses = [...selectedLicenses];
 
        newSelectedLicenses.push(selection);
 
        const newSelectedLicenseKeys = newSelectedLicenses
          .sort((a: License | undefined, b: License | undefined) => {
            if (a && b) {
              if (a?.name < b?.name) {
                return -1;
              }
 
              if (a?.name > b?.name) {
                return 1;
              }
            }
 
            return 0;
          })
          .map((item) => item?.key);
 
        const newLicense = newSelectedLicenseKeys.join(" OR ");
 
        setLicense(newLicense);
        setValue("license", newLicense, {
          shouldDirty: isDirty(newLicense, originalLicense),
        });
        setSuggestions([]);
      }}
      itemToString={() => ""}
    >
      {({ getInputProps, getItemProps, getMenuProps, highlightedIndex }) => (
        <div>
          <input
            type="hidden"
            {...register("license", {
              value: license,
            })}
          />
          <div className="p-multiselect u-no-margin--bottom">
            {selectedLicenses.map((selectedLicense) => (
              <span
                className="p-multiselect__item"
                data-key={selectedLicense?.key}
                key={selectedLicense?.key}
              >
                {selectedLicense?.name}
                <Button
                  type="button"
                  style={{
                    backgroundColor: "transparent",
                    border: 0,
                    color: "inherit",
                    margin: 0,
                    padding: 0,
                  }}
                  onClick={() => {
                    const newSelectedLicenses: (License | undefined)[] =
                      selectedLicenses.filter(
                        (item) => item?.key !== selectedLicense?.key,
                      );
 
                    const newSelectedLicenseKeys: (string | undefined)[] =
                      newSelectedLicenses.map((item) => item?.key);
 
                    const newLicense = newSelectedLicenseKeys.join(" OR ");
                    setLicense(newLicense);
                    setValue("license", newLicense, {
                      shouldDirty: isDirty(newLicense, originalLicense),
                    });
                  }}
                >
                  <i className="p-icon--close p-multiselect__item-remove">
                    Remove license
                  </i>
                </Button>
              </span>
            ))}
            <input
              type="text"
              className="p-multiselect__input"
              name="search"
              {...getInputProps({
                onKeyUp: debounce(
                  (
                    e: SyntheticEvent<HTMLInputElement> & {
                      target: HTMLInputElement;
                    },
                  ) => {
                    const value = e?.target?.value.toLowerCase();
 
                    setSuggestions(
                      licenses.filter((item) => {
                        return (
                          !selectedLicenseKeys.includes(item?.key) &&
                          item?.name.toLowerCase().startsWith(value)
                        );
                      }),
                    );
                  },
                  200,
                  false,
                ),
                onFocus: () => {
                  setSuggestions(
                    licenses.filter((item) => {
                      return !selectedLicenseKeys.includes(item?.key);
                    }),
                  );
                },
                onBlur: () => {
                  setSuggestions([]);
                },
              })}
            />
          </div>
          {suggestions.length ? (
            <ul
              className="p-list p-card--highlighted u-no-padding u-no-margin--bottom p-autocomplete__suggestions"
              {...getMenuProps()}
            >
              {suggestions.map((item: License, index) => (
                <li
                  key={item.key}
                  className="p-list__item p-autocomplete__suggestion"
                  {...getItemProps({
                    index,
                    item,
                    style: {
                      backgroundColor:
                        highlightedIndex === index ? "#f7f7f7" : "#fff",
                    },
                  })}
                >
                  {item.name}
                </li>
              ))}
            </ul>
          ) : null}
        </div>
      )}
    </Downshift>
  );
}
 
export default LicenseSearch;