All files / app/components/LocationAutocomplete LocationAutocomplete.tsx

95.65% Statements 44/46
87.5% Branches 28/32
100% Functions 12/12
95.45% Lines 42/44

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  6x 6x 6x 6x 6x 6x 6x 6x                                       6x                                     298x   295x   295x               9x       9x                       295x 295x   295x     45x   41x     295x         15x         15x   9x 9x 9x     6x 6x                                           5x     417x   39x   6x 6x     37x 8x 8x           1x                           417x 339x   78x 55x   23x     245x  
import { AutocompleteChangeReason } from "@mui/material";
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 {
  className?: string;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  control: Control<any>;
  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;
}
 
const LocationAutocomplete = React.forwardRef(function LocationAutocomplete(
  props: LocationAutocompleteProps,
  ref,
) {
  const {
    className,
    control,
    defaultValue,
    fieldError,
    fullWidth,
    label,
    placeholder,
    id = "location-autocomplete",
    name,
    variant = "standard",
    onChange,
    required,
    showFullDisplayName = false,
    disableRegions = false,
  } = props;
 
  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") {
      //createOption is when enter is pressed on user-entered string
      if (reason === "createOption") {
        query(value);
        setIsOpen(true);
      }
    } else {
      onChange?.(value ?? "");
      setIsOpen(false);
    }
  };
 
  return (
    <Autocomplete
      className={className}
      id={id}
      ref={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, "createOption");
        }
      }}
      endAdornment={
        <IconButton
          aria-label={t("location_autocomplete.search_location_button")}
          onClick={() => searchSubmit(controller.field.value, "createOption")}
          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;
}
 
export default LocationAutocomplete;