wix-style-react
Version:
261 lines (202 loc) • 11 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _AddressInput = _interopRequireDefault(require("../AddressInput"));
var _AddressInputItem = require("../AddressInputItem");
var _usePlacesAutocomplete = _interopRequireDefault(require("../providers/usePlacesAutocomplete"));
var _useAtlasClient = _interopRequireDefault(require("../providers/useAtlasClient"));
var _constants = require("./constants");
var _excluded = ["baseUrl", "token", "debounceMs", "debounceFn", "onChange", "onClear", "onSelect", "onError", "selectOnSubmit", "optionLayout", "optionPrefix", "optionSuffix", "status"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var AtlasAddressInput = /*#__PURE__*/_react["default"].forwardRef(function (_ref, ref) {
var baseUrl = _ref.baseUrl,
token = _ref.token,
debounceMs = _ref.debounceMs,
debounceFn = _ref.debounceFn,
onChange = _ref.onChange,
onClear = _ref.onClear,
onSelect = _ref.onSelect,
onError = _ref.onError,
selectOnSubmit = _ref.selectOnSubmit,
optionLayout = _ref.optionLayout,
optionPrefix = _ref.optionPrefix,
optionSuffix = _ref.optionSuffix,
statusProp = _ref.status,
props = (0, _objectWithoutProperties2["default"])(_ref, _excluded);
var client = (0, _useAtlasClient["default"])({
baseUrl: baseUrl,
token: token
});
var _usePlacesAutocomplet = (0, _usePlacesAutocomplete["default"])({
client: client,
debounceMs: debounceMs,
debounceFn: debounceFn,
onError: onError
}),
predictions = _usePlacesAutocomplet.predictions,
updatePredictions = _usePlacesAutocomplet.updatePredictions,
clearPredictions = _usePlacesAutocomplet.clearPredictions,
loading = _usePlacesAutocomplet.loading; // If not loading, show the status passed from props
var status = loading ? 'loading' : statusProp;
var options = (0, _react.useMemo)(function () {
return predictions.map(function (prediction) {
return (0, _AddressInputItem.addressInputItemBuilder)({
id: prediction.searchId,
mainLabel: prediction.textStructure.mainText,
secondaryLabel: prediction.textStructure.secondaryText,
displayLabel: prediction.description,
optionLayout: optionLayout,
prefix: optionPrefix,
suffix: optionSuffix,
dataHook: _constants.dataHooks.item
});
});
}, [predictions, optionLayout, optionPrefix, optionSuffix]);
var innerRef = (0, _react.useRef)();
(0, _react.useImperativeHandle)(ref, function () {
return {
focus: function focus() {
var _innerRef$current;
return innerRef === null || innerRef === void 0 ? void 0 : (_innerRef$current = innerRef.current) === null || _innerRef$current === void 0 ? void 0 : _innerRef$current.focus();
}
};
});
var _onChange = (0, _react.useCallback)(function (event) {
updatePredictions(event.target.value);
onChange && onChange(event);
}, [updatePredictions, onChange]);
var _onClear = (0, _react.useCallback)(function () {
clearPredictions();
onClear && onClear();
}, [clearPredictions, onClear]);
var _onSelect = (0, _react.useCallback)(function (option) {
var getAddress = function getAddress() {
return client.getAddress(option.id);
};
onSelect && onSelect(option, getAddress);
}, [client, onSelect]); // A callback which is called when the user performs a Submit-Action
var _onManualSubmit = (0, _react.useCallback)(function (inputValue) {
if (selectOnSubmit && onSelect && inputValue) {
var option = (0, _AddressInputItem.addressInputItemBuilder)({
id: inputValue,
mainLabel: inputValue,
displayLabel: inputValue
});
var getAddress = /*#__PURE__*/function () {
var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
var addresses;
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return client.searchAddresses(inputValue);
case 2:
addresses = _context.sent;
return _context.abrupt("return", addresses[0]);
case 4:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function getAddress() {
return _ref2.apply(this, arguments);
};
}();
onSelect(option, getAddress);
}
}, [selectOnSubmit, onSelect, client]);
return /*#__PURE__*/_react["default"].createElement(_AddressInput["default"], (0, _extends2["default"])({}, props, {
options: options,
onChange: _onChange,
onClear: _onClear,
onSelect: _onSelect,
onManuallyInput: _onManualSubmit,
status: status,
ref: innerRef
}));
});
AtlasAddressInput.displayName = 'AtlasAddressInput';
AtlasAddressInput.propTypes = {
/** Accept a custom domain for WixAtlasServiceWeb to retrieve predictions from */
baseUrl: _propTypes["default"].string,
/** Sets an authorization token to pass to the Atlas Service */
token: _propTypes["default"].string,
/** Fetch predictions debounce in milliseconds (default: 200) */
debounceMs: _propTypes["default"].number,
/** Allows passing a custom debounce function (default: lodash debounce).
* Usage:
* (callback: Function, debounceMs: number) => Function */
debounceFn: _propTypes["default"].func,
/** Applies a data-hook HTML attribute that can be used in the tests */
dataHook: _propTypes["default"].string,
/** Specifies a CSS class name to be appended to the component’s root element */
className: _propTypes["default"].string,
/** Displays clear button (X) on a non-empty input */
clearButton: _propTypes["default"].bool,
/** Sets the initial input value */
initialValue: _propTypes["default"].string,
/** Sets a value to display (controlled mode) */
value: _propTypes["default"].string,
/** Specifies whether input is disabled */
disabled: _propTypes["default"].bool,
/** Defines a callback function which is called whenever a user selects a different option in the list.
* @param {DropdownLayoutOption} option selected option
* @param {() => Promise<Address>} getAddress function for retrieving additional place details
*/
onSelect: _propTypes["default"].func,
/** Defines a callback function which is called every time input value is changed */
onChange: _propTypes["default"].func,
/** Defines a handler for getting notified upon a clear event. When passed, it displays a clear button in the input. */
onClear: _propTypes["default"].func,
/** Defines a standard input onBlur callback */
onBlur: _propTypes["default"].func,
/** Specifies whether to trigger `onSelect` handler when performing a Submit-Action (Enter or Tab key down).
* If set to true, `onSelect` will be called with the following params:
*
* `option`: an option with a label set to the input value.
*
* `getAddress`: function for retrieving additional place details
* uses Atlas's search function to return the closest result to the input value
*
* This is useful when looking for locations for which Atlas does not give suggestions - for example: Apartment/Apt. */
selectOnSubmit: _propTypes["default"].bool,
/** Defines a handler for prediction fetching errors. Returns an error object.
* you can read these [guidelines](https://bo.wix.com/wix-docs/rnd/platformization-guidelines/errors#platformization-guidelines_errors_errors)
* to learn about the meaning of each error status.
*/
onError: _propTypes["default"].func,
/** Specify the status of a field. Mostly used for a “loading” indication upon async request calls. */
status: _propTypes["default"].oneOf(['loading', 'error', 'warning']),
/** Defines the message to display on status icon hover. If not given or empty there will be no tooltip */
statusMessage: _propTypes["default"].node,
/** Control the border style of an input */
border: _propTypes["default"].oneOf(['standard', 'round', 'bottomLine']),
/** Controls the size of the input */
size: _propTypes["default"].oneOf(['small', 'medium', 'large']),
/** Sets a placeholder message to display */
placeholder: _propTypes["default"].string,
/** Sets the message to show in a dropdown when no results are found */
noResultsText: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].node]),
/** Sets the layout of `mainLabel` and `secondaryLabel`. The possible options can be either side by side or vertically stacked. */
optionLayout: _propTypes["default"].oneOf(['single-line', 'double-line']),
/** Pass any component to show as the prefix of the option, e.g., text, icon. */
optionPrefix: _propTypes["default"].node,
/** Pass any component to show as the suffix of the option, e.g., text, icon, button. */
optionSuffix: _propTypes["default"].node
};
var _default = AtlasAddressInput;
exports["default"] = _default;