All files / src/components Geocoder.tsx

94.28% Statements 99/105
74.07% Branches 20/27
100% Functions 31/31
100% Lines 78/78

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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 34112x   5x                                                                                                                                                                                                                                                                                                                                             5x                                   2x 2x   2x   2x 1x     2x 1x         2x 2x       2x 2x       2x 2x       2x 2x       2x 2x       2x 2x       2x 2x 2x   2x 2x 2x         2x 2x       2x 2x       2x 2x 2x   2x   1x   1x 1x 1x         2x 2x 2x   2x   1x   1x 1x 1x         2x 2x 2x   2x   1x   1x 1x 1x         2x 2x 2x   2x   1x 5x 3x     1x 1x 1x         2x 2x 2x   2x   1x 1x     1x 1x 1x         2x 2x     2x      
/* eslint-disable @typescript-eslint/no-namespace */
 
import React, { useRef, useEffect, useImperativeHandle } from 'react';
import mapboxgl from 'mapbox-gl';
 
import {
  GeocodingOptions,
  GeocodingResponse,
  GeocodingFeature
} from '@mapbox/search-js-core';
import {
  MapboxGeocoder,
  Theme,
  MapboxHTMLEvent,
  PopoverOptions
} from '@mapbox/search-js-web';
 
declare global {
  namespace JSX {
    interface IntrinsicElements {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      'mapbox-geocoder': any;
    }
  }
}
 
/**
 * @typedef GeocoderRefType
 */
export interface GeocoderRefType {
  /**
   * @see {@link MapboxGeocoder#focus}
   */
  focus: typeof MapboxGeocoder.prototype.focus;
  /**
   * @see {@link MapboxGeocoder#search}
   */
  search: typeof MapboxGeocoder.prototype.search;
}
 
/**
 * @typedef GeocoderProps
 */
export interface GeocoderProps {
  /**
   * The [Mapbox access token](https://docs.mapbox.com/help/glossary/access-token/) to use for all requests.
   */
  accessToken: string;
  /**
   * Options to pass to the underlying {@link GeocodingCore} interface.
   * @example
   * ```typescript
   * <Geocoder options={{
   *  language: 'en',
   *  country: 'US',
   * }}>
   * ```
   */
  options?: Partial<GeocodingOptions>;
  /**
   * The {@link Theme} to use for styling the geocoder.
   * @example
   * ```typescript
   * <Geocoder theme={{
   *   variables: {
   *     colorPrimary: 'myBrandRed'
   *   }
   * }}>
   * ```
   */
  theme?: Theme;
  /**
   * The {@link PopoverOptions} to define popover positioning.
   * @example
   * ```typescript
   * <Geocoder popoverOptions={{
   *   placement: 'top-start',
   *   flip: true,
   *   offset: 5
   * }}>
   * ```
   */
  popoverOptions?: Partial<PopoverOptions>;
  /**
   * The input element's placeholder text. The default value may be localized if {@link GeocodingOptions#language} is set.
   */
  placeholder?: string;
  /**
   * If specified, the map will be centered on the retrieved suggestion.
   */
  map?: mapboxgl.Map;
  /**
   * If `true`, a [Marker](https://docs.mapbox.com/mapbox-gl-js/api/#marker) will be added to the map at the location of the user-selected result using a default set of Marker options.  If the value is an object, the marker will be constructed using these options. If `false`, no marker will be added to the map. Requires that {@link GeocoderProps#mapboxgl} also be set.
   */
  marker?: boolean | mapboxgl.MarkerOptions;
  /**
   * A [mapbox-gl](https://github.com/mapbox/mapbox-gl-js) instance to use when creating [Markers](https://docs.mapbox.com/mapbox-gl-js/api/#marker). Required if {@link GeocoderProps#marker} is `true`.
   */
  mapboxgl?: typeof mapboxgl;
  /**
   * Value to display in the geocoder.
   */
  value?: string;
  /**
   * Callback for when the value changes.
   */
  onChange?: (value: string) => void;
  /**
   * Fired when the user is typing in the input and provides a list of suggestions.
   * The underlying response from {@link GeocodingCore} is passed.
   */
  onSuggest?: (res: GeocodingResponse) => void;
  /**
   * Fired when {@link GeocodingCore} has errored providing a list of suggestions.
   * The underlying error is passed.
   */
  onSuggestError?: (error: Error) => void;
  /**
   * Fired when the user has selected a suggestion.
   * The underlying feature from {@link GeocodingCore} is passed.
   */
  onRetrieve?: (res: GeocodingFeature) => void;
  /**
   * Fired when the user has cleared the search box.
   */
  onClear?: () => void;
 
  /**
   * A callback providing the opportunity to validate and/or manipulate the input text before it triggers a search, for example by using a regular expression.
   * If a truthy string value is returned, it will be passed into the underlying search API. If `null`, `undefined` or empty string  is returned, no search request will be performed.
   */
  interceptSearch?: (value: string) => string;
}
 
/**
 * `<Geocoder>` is a React component that provides an interactive geocoder,
 * powered by the Mapbox Geocoding API.
 *
 * To use this element, you must have a [Mapbox access token](https://www.mapbox.com/help/create-api-access-token/).
 *
 * Internally, this wraps the [`<mapbox-geocoder>`](https://docs.mapbox.com/mapbox-search-js/api/web/search/#mapboxgeocoder) element.
 *
 * @function Geocoder
 * @param {GeocoderProps} props
 * @example
 * ```typescript
 * import { Geocoder } from "@mapbox/search-js-react";
 * export function Component() {
 *   const [value, setValue] = React.useState('');
 *
 *   const handleChange = (d) => {
 *     setValue(d);
 *   };
 *   return (
 *     <Geocoder
 *       options={{
 *         proximity: {
 *           lng: -122.431297,
 *           lat: 37.773972,
 *         },
 *       }}
 *       value={value}
 *       onChange={handleChange}
 *       accessToken="YOUR_MAPBOX_ACCESS_TOKEN"
 *     />
 *   );
 * }
 * ```
 */
export const Geocoder = React.forwardRef(
  (props: GeocoderProps, refProp): React.ReactElement => {
    const {
      accessToken,
      options,
      theme,
      popoverOptions,
      placeholder,
      map,
      marker,
      mapboxgl,
      value,
      onChange,
      onSuggest,
      onSuggestError,
      onRetrieve,
      onClear,
      interceptSearch
    } = props;
    const ref = useRef<MapboxGeocoder>();
 
    useImperativeHandle(refProp, () => ({
      focus: () => {
        if (ref.current) return ref.current.focus();
        throw new Error('Geocoder is not mounted');
      },
      search: (text: string) => {
        if (ref.current) return ref.current.search(text);
        throw new Error('Geocoder is not mounted');
      }
    }));
 
    // Update options.
    useEffect(() => {
      if (ref.current) ref.current.options = options || {};
    }, [ref.current, options]);
 
    // Update intercept search.
    useEffect(() => {
      if (ref.current) ref.current.interceptSearch = interceptSearch;
    }, [ref.current, interceptSearch]);
 
    // Update theme.
    useEffect(() => {
      if (ref.current) ref.current.theme = theme;
    }, [ref.current, theme]);
 
    // Update popoverOptions
    useEffect(() => {
      if (ref.current) ref.current.popoverOptions = popoverOptions;
    }, [ref.current, popoverOptions]);
 
    // Update placeholder
    useEffect(() => {
      if (ref.current) ref.current.placeholder = placeholder;
    }, [ref.current, placeholder]);
 
    // Update value.
    useEffect(() => {
      if (ref.current) ref.current.value = value || '';
    }, [ref.current, value]);
 
    // Update map.
    useEffect(() => {
      const node = ref.current;
      Iif (!node) return;
 
      node.bindMap(map);
      return () => {
        node.unbindMap();
      };
    }, [ref.current, map]);
 
    // Update marker.
    useEffect(() => {
      if (ref.current) ref.current.marker = marker;
    }, [ref.current, marker]);
 
    // Update mapboxgl.
    useEffect(() => {
      if (ref.current) ref.current.mapboxgl = mapboxgl;
    }, [ref.current, mapboxgl]);
 
    // Update onSuggest.
    useEffect(() => {
      const node = ref.current;
      Iif (!node) return;
 
      if (!onSuggest) return;
 
      const fn = (e: MapboxHTMLEvent<GeocodingResponse>) => onSuggest(e.detail);
 
      node.addEventListener('suggest', fn);
      return () => {
        node.removeEventListener('suggest', fn);
      };
    }, [ref.current, onSuggest]);
 
    // Update onSuggestError.
    useEffect(() => {
      const node = ref.current;
      Iif (!node) return;
 
      if (!onSuggestError) return;
 
      const fn = (e: MapboxHTMLEvent<Error>) => onSuggestError(e.detail);
 
      node.addEventListener('suggesterror', fn);
      return () => {
        node.removeEventListener('suggesterror', fn);
      };
    }, [ref.current, onSuggestError]);
 
    // Update onRetrieve.
    useEffect(() => {
      const node = ref.current;
      Iif (!node) return;
 
      if (!onRetrieve) return;
 
      const fn = (e: MapboxHTMLEvent<GeocodingFeature>) => onRetrieve(e.detail);
 
      node.addEventListener('retrieve', fn);
      return () => {
        node.removeEventListener('retrieve', fn);
      };
    }, [ref.current, onRetrieve]);
 
    // Update onChange.
    useEffect(() => {
      const node = ref.current;
      Iif (!node) return;
 
      if (!onChange) return;
 
      const fn = (e: MapboxHTMLEvent<string>) => {
        if (e.target !== e.currentTarget) return; // ignore child input event
        onChange(e.detail);
      };
 
      node.addEventListener('input', fn);
      return () => {
        node.removeEventListener('input', fn);
      };
    }, [ref.current, onChange]);
 
    // Update onClear.
    useEffect(() => {
      const node = ref.current;
      Iif (!node) return;
 
      if (!onClear) return;
 
      const fn = () => {
        onClear();
      };
 
      node.addEventListener('clear', fn);
      return () => {
        node.removeEventListener('clear', fn);
      };
    }, [ref.current, onClear]);
 
    // Update accessToken.
    useEffect(() => {
      if (ref.current) ref.current.accessToken = accessToken;
    }, [ref.current, accessToken]);
 
    return <mapbox-geocoder ref={ref} />;
  }
);