All files / app/components/LocationAutocomplete LocationAutocomplete.tsx

95.45% Statements 42/44
93.75% Branches 30/32
100% Functions 12/12
95.34% Lines 41/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  8x 8x 8x 8x 8x 8x 8x 8x                                   8x                             154x   154x               14x       9x                       154x 154x   154x     56x   46x     154x         16x         16x   9x 9x 9x     7x 7x       154x                                 6x     309x   49x   7x 7x     41x 8x 8x           1x                           309x 171x   138x 80x   58x    
import { AutocompleteChangeReason } from "@material-ui/lab";
import Autocomplete from "components/Autocomplete";
import IconButton from "components/IconButton";
import { SearchIcon } from "components/Icons";
import { GLOBAL } from "i18n/namespaces";
import { useTranslation } from "next-i18next";
import React, { useState } from "react";
import { Control, useController } from "react-hook-form";
import { GeocodeResult, useGeocodeQuery } from "utils/hooks";
 
interface LocationAutocompleteProps {
  control: Control;
  defaultValue: GeocodeResult | "";
  fieldError: string | undefined;
  fullWidth?: boolean;
  label?: string;
  placeholder?: string;
  id?: string;
  variant?: "filled" | "standard" | "outlined" | undefined;
  name: string;
  onChange?(value: GeocodeResult | ""): void;
  required?: string;
  showFullDisplayName?: boolean;
  disableRegions?: boolean;
}
 
export default function LocationAutocomplete({
  control,
  defaultValue,
  fieldError,
  fullWidth,
  label,
  placeholder,
  id = "location-autocomplete",
  name,
  variant = "standard",
  onChange,
  required,
  showFullDisplayName = false,
  disableRegions = false,
}: LocationAutocompleteProps) {
  const { t } = useTranslation(GLOBAL);
 
  const controller = useController({
    name,
    defaultValue: defaultValue ?? "",
    control,
    rules: {
      required,
      validate: {
        didSelect: (value) =>
          value === "" || typeof value !== "string"
            ? true
            : t("location_autocomplete.select_location_hint"),
        isSpecific: (value) =>
          !value?.isRegion || !disableRegions
            ? true
            : t("location_autocomplete.more_specific"),
      },
    },
  });
 
  const {
    query,
    results: options,
    error: geocodeError,
    isLoading,
  } = useGeocodeQuery();
  const [isOpen, setIsOpen] = useState(false);
 
  const handleChange = (value: GeocodeResult | string | null) => {
    //workaround - autocomplete seems to call onChange with the string value on mount
    //this line prevents needing to reselect the location even if there are no changes
    if (value === controller.field.value?.simplifiedName) return;
 
    controller.field.onChange(value ?? "");
  };
 
  const searchSubmit = (
    value: GeocodeResult | string | null,
    reason: AutocompleteChangeReason
  ) => {
    //just close if the menu is clicked away
    Iif (reason === "blur") {
      setIsOpen(false);
      return;
    }
 
    if (typeof value === "string") {
      //create-option is when enter is pressed on user-entered string
      if (reason === "create-option") {
        query(value);
        setIsOpen(true);
      }
    } else {
      onChange?.(value ?? "");
      setIsOpen(false);
    }
  };
 
  return (
    <Autocomplete
      id={id}
      innerRef={controller.field.ref}
      label={label}
      error={fieldError || geocodeError}
      fullWidth={fullWidth}
      variant={variant}
      placeholder={placeholder}
      helperText={
        fieldError === t("location_autocomplete.select_location_hint")
          ? t("location_autocomplete.select_location_hint")
          : t("location_autocomplete.search_location_hint")
      }
      loading={isLoading}
      options={options || []}
      open={isOpen}
      onClose={() => setIsOpen(false)}
      value={controller.field.value}
      getOptionLabel={(option: GeocodeResult | string) => {
        return geocodeResult2String(option, showFullDisplayName);
      }}
      onInputChange={(_e, value) => handleChange(value)}
      onChange={(_e, value, reason) => {
        handleChange(value);
        searchSubmit(value, reason);
      }}
      onKeyDown={(e) => {
        if (e.key === "Enter") {
          e.preventDefault();
          searchSubmit(controller.field.value, "create-option");
        }
      }}
      endAdornment={
        <IconButton
          aria-label={t("location_autocomplete.search_location_button")}
          onClick={() => searchSubmit(controller.field.value, "create-option")}
          size="small"
        >
          <SearchIcon />
        </IconButton>
      }
      onBlur={controller.field.onBlur}
      freeSolo
      multiple={false}
    />
  );
}
 
function geocodeResult2String(option: GeocodeResult | string, full: boolean) {
  if (typeof option === "string") {
    return option;
  }
  if (full) {
    return option.name;
  }
  return option.simplifiedName;
}