All files / src/components AddressAutofill.tsx

90% Statements 45/50
62.5% Branches 5/8
100% Functions 17/17
95% Lines 38/40

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 2159x   4x                                                                                                                                                                                                                                                             4x                   1x 1x   1x   1x       1x           1x 1x       1x 1x       1x 1x 1x   1x 1x   1x 1x 1x         1x 1x 1x   1x   1x 1x 1x         1x 1x 1x   1x 1x   1x 1x 1x         1x 1x     1x          
/* eslint-disable @typescript-eslint/no-namespace */
 
import React, { useRef, useEffect, useImperativeHandle } from 'react';
 
import {
  AutofillOptions,
  AutofillSuggestionResponse,
  AutofillRetrieveResponse
} from '@mapbox/search-js-core';
import {
  MapboxAddressAutofill,
  Theme,
  MapboxHTMLEvent
} from '@mapbox/search-js-web';
 
declare global {
  namespace JSX {
    interface IntrinsicElements {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      'mapbox-address-autofill': any;
    }
  }
}
 
/**
 * @typedef AddressAutofillRefType
 */
export interface AddressAutofillRefType {
  /**
   * @see {@link MapboxAddressAutofill#showConfirm}
   */
  showConfirm: typeof MapboxAddressAutofill.prototype.showConfirm;
  /**
   * @see {@link MapboxAddressAutofill#focus}
   */
  focus: typeof MapboxAddressAutofill.prototype.focus;
}
 
/**
 * @typedef AddressAutofillProps
 */
export interface AddressAutofillProps {
  /**
   * 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 MapboxAutofill} interface.
   * @example
   * ```typescript
   * <AddressAutofill options={{
   *  language: 'en',
   *  country: 'US',
   * }}>
   * ```
   */
  options?: Partial<AutofillOptions>;
  /**
   * The {@link Theme} to use for styling the autofill and confirmation dialog
   * components.
   * @example
   * ```typescript
   * <AddressAutofill theme={{
   *   variables: {
   *     colorPrimary: 'myBrandRed'
   *   }
   * }}>
   * ```
   */
  theme?: Theme;
 
  /**
   * Children to render inside the autofill component. This **must** include
   * an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/text) element
   * with either autocomplete type `"street-address"` or `"address-line1"`.
   */
  children: React.ReactChild;
 
  /**
   * Fired when the user is typing in the input and provides a list of suggestions.
   * The underlying response from {@link MapboxAutofill} is passed.
   */
  onSuggest?: (res: AutofillSuggestionResponse) => void;
  /**
   * Fired when {@link MapboxAutofill} has errored providing a list of suggestions.
   * The underlying error is passed.
   */
  onSuggestError?: (error: Error) => void;
  /**
   * Fired when the user has selected a suggestion, before the form is autofilled.
   * The underlying response from {@link MapboxAutofill} is passed.
   */
  onRetrieve?: (res: AutofillRetrieveResponse) => void;
}
 
/**
 * `<AddressAutofill>` is a React component that wraps an address
 * [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/text) element with intelligent, location-aware autocomplete functionality.
 *
 * To use this element, you must have a [Mapbox access token](https://www.mapbox.com/help/create-api-access-token/).
 *
 * This component must be a descendant of a [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form), and the form
 * must have inputs with proper HTML `autocomplete` attributes. If your application works with browser autofill, you may already have
 * this functionality.
 * - [The HTML autocomplete attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete)
 * - [Autofill](https://web.dev/learn/forms/autofill/)
 *
 * Internally, this wraps the [`<mapbox-address-autofill>`](https://docs.mapbox.com/mapbox-search-js/api/web/autofill/#mapboxaddressautofill) element.
 *
 * @function AddressAutofill
 * @param {AddressAutofillProps} props
 * @example
 * ```typescript
 * export function Component() {
 *   const [value, setValue] = React.useState('');
 *   return (
 *     <form>
 *       <AddressAutofill accessToken={<your access token here>}>
 *         <input
 *           autoComplete="shipping address-line1"
 *           value={value}
 *           onChange={(e) => setValue(e.target.value)}
 *         />
 *       </AddressAutofill>
 *     </form>
 *   );
 * }
 * ```
 */
export const AddressAutofill = React.forwardRef(
  (props: AddressAutofillProps, refProp): React.ReactElement => {
    const {
      accessToken,
      options,
      theme,
      children,
      onSuggest,
      onSuggestError,
      onRetrieve
    } = props;
    const ref = useRef<MapboxAddressAutofill>();
 
    useImperativeHandle(refProp, () => ({
      showConfirm: () => {
        if (ref.current) return ref.current.showConfirm();
        throw new Error('AddressAutofill is not mounted');
      },
      focus: () => {
        if (ref.current) return ref.current.focus();
        throw new Error('AddressAutofill is not mounted');
      }
    }));
 
    // Update options.
    useEffect(() => {
      if (ref.current) ref.current.options = options;
    }, [ref.current, options]);
 
    // Update theme.
    useEffect(() => {
      if (ref.current) ref.current.theme = theme;
    }, [ref.current, theme]);
 
    // Update onSuggest.
    useEffect(() => {
      const node = ref.current;
      Iif (!node) return;
 
      const fn = (e: MapboxHTMLEvent<AutofillSuggestionResponse>) =>
        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;
 
      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;
 
      const fn = (e: MapboxHTMLEvent<AutofillRetrieveResponse>) =>
        onRetrieve(e.detail);
 
      node.addEventListener('retrieve', fn);
      return () => {
        node.removeEventListener('retrieve', fn);
      };
    }, [ref.current, onRetrieve]);
 
    // Update accessToken.
    useEffect(() => {
      if (ref.current) ref.current.accessToken = accessToken;
    }, [ref.current, accessToken]);
 
    return (
      <mapbox-address-autofill ref={ref}>{children}</mapbox-address-autofill>
    );
  }
);