All files / src/shared/GoogleMapsAutocomplete GiveMapsAutocomplete.tsx

28.2% Statements 22/78
14.28% Branches 7/49
34.78% Functions 8/23
30.43% Lines 21/69

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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287                                                                                                                              103x     103x     103x 103x   103x                     103x 16x             103x 16x           103x   16x                                               103x 16x 16x       103x 16x                                                     103x                             103x                     103x                                                             119x                                                                                                                   45x                          
import * as React from "react";
import {
  Box,
  Autocomplete,
  debounce,
  Paper,
  TextFieldProps,
  SxProps,
} from "@mui/material";
import parse from "autosuggest-highlight/parse";
import ErrorCatcher from "@common/Error/ErrorCatcher";
import { GiveInput } from "@shared/GiveInputs/GiveInput";
import GiveText from "@shared/Text/GiveText";
import { styled } from "@theme/v2/Provider";
import { MagnifyingGlassIcon } from "@phosphor-icons/react";
 
interface PlacePrediction {
  placeId: string;
  text: string;
  structuredFormat: {
    mainText: string;
    secondaryText?: string;
  };
}
 
interface PlaceType {
  placePrediction: PlacePrediction;
}
 
interface LegacyPlaceType {
  description: string;
  structured_formatting: {
    main_text: string;
    secondary_text: string;
    main_text_matched_substrings?: { offset: number; length: number }[];
  };
}
 
type TGiveMapsAutocomplete = {
  disabled?: boolean;
  label?: string;
  sx?: SxProps;
  initialValue?: string | null;
  reset?: boolean;
  onValueChange: (value: string) => void;
  inputProps?: TextFieldProps;
  isLoaded: boolean;
  error?: boolean;
  errorText?: string;
};
 
function GiveMapsAutocomplete({
  disabled,
  label,
  sx,
  inputProps,
  reset,
  initialValue,
  onValueChange,
  isLoaded,
  error,
  errorText,
}: TGiveMapsAutocomplete) {
  const [value, setValue] = React.useState<PlaceType | LegacyPlaceType | null>(
    null,
  );
  const [options, setOptions] = React.useState<
    readonly (PlaceType | LegacyPlaceType)[]
  >([]);
  const [inputValue, setInputValue] = React.useState("");
  const isMounted = React.useRef(false);
 
  const setInitialValue = (initialValue: string) => {
    setInputValue(initialValue);
    setValue({
      description: initialValue,
      structured_formatting: {
        main_text: initialValue,
        secondary_text: initialValue,
      },
    });
  };
 
  React.useEffect(() => {
    Iif (reset && initialValue) {
      setValue(null);
      setInputValue("");
      isMounted.current = false;
    }
  }, [reset, initialValue]);
 
  React.useEffect(() => {
    Iif (!isMounted.current && initialValue) {
      setInitialValue(initialValue);
      isMounted.current = true;
    }
  }, [initialValue]);
 
  const fetch = React.useMemo(
    () =>
      debounce(
        async (
          request: { input: string },
          callback: (
            results?: google.maps.places.AutocompleteSuggestion[],
          ) => void,
        ) => {
          try {
            const { suggestions } =
              await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(
                request,
              );
 
            callback(Array.isArray(suggestions) ? suggestions : []);
          } catch (err) {
            callback([]);
          }
        },
        400,
      ),
    [],
  );
 
  // Cleanup pending debounce calls on unmount
  React.useEffect(() => {
    return () => {
      fetch.clear();
    };
  }, [fetch]);
 
  React.useEffect(() => {
    Eif (!isLoaded || !(window as any).google?.maps?.places) return;
 
    if (inputValue === "") {
      setOptions(value ? [value] : []);
      return;
    }
 
    let active = true;
 
    fetch(
      { input: inputValue },
      (results?: google.maps.places.AutocompleteSuggestion[]) => {
        if (!active) return;
 
        const merged = [value, ...(results || [])].filter(Boolean) as (
          | PlaceType
          | LegacyPlaceType
        )[];
        setOptions(merged);
      },
    );
 
    return () => {
      active = false;
    };
  }, [inputValue, isLoaded, value, fetch]);
 
  const extractLabel = (
    option: PlaceType | LegacyPlaceType | string,
  ): string => {
    if (typeof option === "string") return option;
 
    if ("description" in option) return option.description;
 
    const text = option.placePrediction?.text;
 
    if (typeof text === "string") return text;
    if (text?.text) return text.text;
 
    return text?.toString?.() || "";
  };
 
  const extractSelectedText = (
    newValue: PlaceType | LegacyPlaceType | null,
  ): string => {
    if (!newValue) return "";
 
    if ("description" in newValue) return newValue.description;
 
    const t = newValue.placePrediction.text;
    return typeof t === "string" ? t : t?.text || t?.toString() || "";
  };
 
  return (
    <ErrorCatcher errorID="Autocomplete">
      <Autocomplete
        sx={sx}
        disabled={disabled}
        forcePopupIcon={false}
        autoComplete
        includeInputInList
        filterSelectedOptions
        autoHighlight
        noOptionsText="Start typing to see options"
        PaperComponent={OptionsContainer}
        filterOptions={(x) => x}
        openOnFocus={false}
        value={value}
        options={options}
        getOptionLabel={extractLabel}
        isOptionEqualToValue={(option, value) => {
          const optionLabel = extractLabel(option);
          const valueLabel = extractLabel(value);
          return optionLabel === valueLabel;
        }}
        onChange={(_, newValue) => {
          setValue(newValue);
          setOptions(newValue ? [newValue, ...options] : options);
          onValueChange(extractSelectedText(newValue));
        }}
        onInputChange={(_, newInputValue) => {
          setInputValue(newInputValue);
        }}
        renderInput={(params) => (
          <GiveInput
            {...params}
            label={label}
            onKeyDown={(e) => e.stopPropagation()}
            inputProps={{ ...params.inputProps }}
            {...inputProps}
            rightContent={<MagnifyingGlassIcon size={20} />}
            error={error}
            helperText={errorText}
          />
        )}
        renderOption={(props, option) => {
          if ("description" in option) {
            const matches =
              option.structured_formatting.main_text_matched_substrings || [];
            const parts = parse(
              option.structured_formatting.main_text,
              matches.map((m) => [m.offset, m.offset + m.length]),
            );
 
            return (
              <li {...props}>
                <GiveText variant="bodyS" color="primary">
                  {parts.map((part, idx) => (
                    <Box
                      key={idx}
                      component="span"
                      sx={{
                        ...(part.highlight && {
                          fontWeight: 500,
                        }),
                      }}
                    >
                      {part.text}
                    </Box>
                  ))}
                  {", "}
                  {option.structured_formatting.secondary_text}
                </GiveText>
              </li>
            );
          }
 
          const txt = extractLabel(option);
 
          return (
            <li {...props}>
              <GiveText variant="bodyS" color="primary">
                {txt}
              </GiveText>
            </li>
          );
        }}
      />
    </ErrorCatcher>
  );
}
 
const OptionsContainer = styled(Paper)(({ theme }) => ({
  margin: "8px 0",
  marginTop: "8px",
  padding: "8px",
  background: "yellow",
  border: `1px solid ${theme.palette.border?.secondary}`,
  borderRadius: "16px",
  backgroundColor: theme.palette.surface?.["tertiary-transparent"],
  backdropFilter: "blur(15px)",
  boxShadow: "none",
}));
 
export default GiveMapsAutocomplete;