UNPKG

@wix/design-system

Version:

@wix/design-system

59 lines 3.14 kB
import React, { useCallback, useMemo, useRef, useImperativeHandle, } from 'react'; import AddressInput from '../AddressInput'; import { addressInputItemBuilder } from '../AddressInputItem'; import usePlacesAutocomplete from '../providers/usePlacesAutocomplete'; import useAtlasClient from '../providers/useAtlasClient'; import { dataHooks } from './constants'; const AtlasAddressInput = React.forwardRef(({ baseUrl, token, language = 'en', locale = 'en-us', debounceMs, debounceFn, onChange, onClear, onSelect, onError, selectOnSubmit, optionLayout, optionPrefix, optionSuffix, status: statusProp, ...props }, ref) => { const client = useAtlasClient({ baseUrl, token, language, locale }); const { predictions, updatePredictions, clearPredictions, loading } = usePlacesAutocomplete({ client, debounceMs, debounceFn, onError }); // If not loading, show the status passed from props const status = loading ? 'loading' : statusProp; const options = useMemo(() => predictions.map(prediction => addressInputItemBuilder({ id: prediction.searchId, mainLabel: prediction.textStructure.mainText, secondaryLabel: prediction.textStructure.secondaryText, displayLabel: prediction.description, optionLayout, prefix: optionPrefix, suffix: optionSuffix, dataHook: dataHooks.item, })), [predictions, optionLayout, optionPrefix, optionSuffix]); const innerRef = useRef(null); useImperativeHandle(ref, () => ({ focus: () => innerRef.current && innerRef.current.focus(), })); const _onChange = useCallback(event => { updatePredictions(event.target.value); onChange && onChange(event); }, [updatePredictions, onChange]); const _onClear = useCallback(() => { clearPredictions(); onClear && onClear(); }, [clearPredictions, onClear]); const _onSelect = useCallback(option => { const getAddress = () => client.getAddress(option.id); onSelect && onSelect(option, getAddress); }, [client, onSelect]); // A callback which is called when the user performs a Submit-Action const _onManualSubmit = useCallback(inputValue => { if (selectOnSubmit && onSelect && inputValue) { const option = addressInputItemBuilder({ id: inputValue, mainLabel: inputValue, displayLabel: inputValue, }); const getAddress = async () => { // search for address matching input value const addresses = await client.searchAddresses(inputValue); // Return first address result return addresses[0]; }; onSelect(option, getAddress); } }, [selectOnSubmit, onSelect, client]); return (React.createElement(AddressInput, { ...props, options: options, onChange: _onChange, onClear: _onClear, onSelect: _onSelect, onManuallyInput: _onManualSubmit, status: status, ref: innerRef })); }); AtlasAddressInput.displayName = 'AtlasAddressInput'; export default AtlasAddressInput; //# sourceMappingURL=AtlasAddressInput.js.map