@dfds-ui/google-places 2.2.0-alpha.8d87a90d → 2.2.0-alpha.e74a6756

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,29 @@
1
+ /// <reference types="react" />
2
+ import { ILocation, IPrediction } from './GooglePlaces';
3
+ export type AddressSelectProps = {
4
+ components?: any;
5
+ name: string;
6
+ disabled?: boolean;
7
+ error?: string;
8
+ size?: 'small' | 'medium';
9
+ types?: string[];
10
+ onFocus?: (event: FocusEvent) => void;
11
+ onBlur?: (event: FocusEvent) => void;
12
+ onChange?: (changed: {
13
+ value: string;
14
+ label: string;
15
+ }, predictions: IPrediction[]) => void;
16
+ location?: ILocation;
17
+ radius?: number;
18
+ countries?: string[] | string;
19
+ placeholder?: string;
20
+ assistiveText?: string;
21
+ autoFocus?: boolean;
22
+ isClearable?: boolean;
23
+ /**
24
+ * Class name to be assigned to the component
25
+ */
26
+ className?: string;
27
+ };
28
+ declare const AddressSelect: ({ name, disabled, error, size, types, onFocus, onBlur, onChange, location, radius, countries, ...rest }: AddressSelectProps) => JSX.Element;
29
+ export default AddressSelect;
@@ -0,0 +1,96 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ var _excluded = ["name", "disabled", "error", "size", "types", "onFocus", "onBlur", "onChange", "location", "radius", "countries"];
3
+ function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
4
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) { if (n.call(e, o)) return next.value = e[o], next.done = !1, next; } return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) { r.push(n); } return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) { "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); } }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
5
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
6
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
7
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
8
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
9
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
10
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
11
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) { ; } } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
12
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
13
+ function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
14
+ function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
15
+ import React, { useState } from 'react';
16
+ import { AsyncSearchableSelect } from '@dfds-ui/react-components';
17
+ import debounce from 'lodash.debounce';
18
+ import { useAddressPredictions } from './GooglePlaces';
19
+ import { jsx as ___EmotionJSX } from "@emotion/react";
20
+ var AddressSelect = function AddressSelect(_ref) {
21
+ var name = _ref.name,
22
+ disabled = _ref.disabled,
23
+ error = _ref.error,
24
+ _ref$size = _ref.size,
25
+ size = _ref$size === void 0 ? 'medium' : _ref$size,
26
+ types = _ref.types,
27
+ onFocus = _ref.onFocus,
28
+ onBlur = _ref.onBlur,
29
+ onChange = _ref.onChange,
30
+ location = _ref.location,
31
+ radius = _ref.radius,
32
+ _ref$countries = _ref.countries,
33
+ countries = _ref$countries === void 0 ? [] : _ref$countries,
34
+ rest = _objectWithoutProperties(_ref, _excluded);
35
+ var _useState = useState([]),
36
+ _useState2 = _slicedToArray(_useState, 2),
37
+ predictions = _useState2[0],
38
+ setPredictions = _useState2[1];
39
+ var _useAddressPrediction = useAddressPredictions('', {
40
+ types: types,
41
+ location: location,
42
+ radius: radius,
43
+ components: {
44
+ countries: countries
45
+ }
46
+ }),
47
+ available = _useAddressPrediction.available,
48
+ getPlacePredictions = _useAddressPrediction.getPlacePredictions;
49
+ var loadOptions = /*#__PURE__*/function () {
50
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(input, callback) {
51
+ var placePredictions, options;
52
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
53
+ while (1) {
54
+ switch (_context.prev = _context.next) {
55
+ case 0:
56
+ _context.next = 2;
57
+ return getPlacePredictions(input);
58
+ case 2:
59
+ placePredictions = _context.sent;
60
+ setPredictions(placePredictions);
61
+ options = placePredictions.map(function (prediction) {
62
+ return {
63
+ value: prediction.description,
64
+ label: prediction.description,
65
+ prediction: prediction
66
+ };
67
+ });
68
+ callback(options);
69
+ case 6:
70
+ case "end":
71
+ return _context.stop();
72
+ }
73
+ }
74
+ }, _callee);
75
+ }));
76
+ return function loadOptions(_x, _x2) {
77
+ return _ref2.apply(this, arguments);
78
+ };
79
+ }();
80
+ var handleChange = function handleChange(value) {
81
+ if (onChange) {
82
+ onChange(value, predictions);
83
+ }
84
+ };
85
+ return ___EmotionJSX(AsyncSearchableSelect, _extends({
86
+ disabled: disabled || !available,
87
+ name: name,
88
+ error: error,
89
+ size: size,
90
+ onChange: handleChange,
91
+ loadOptions: debounce(loadOptions, 500),
92
+ onFocus: onFocus,
93
+ onBlur: onBlur
94
+ }, rest));
95
+ };
96
+ export default AddressSelect;
@@ -0,0 +1,54 @@
1
+ import React from 'react';
2
+ export declare const GooglePlacesAPIContext: React.Context<{
3
+ available: boolean;
4
+ }>;
5
+ export interface ILocation {
6
+ lat: number;
7
+ lng: number;
8
+ }
9
+ interface IPredictionsOptions {
10
+ types?: string[] | undefined;
11
+ location?: ILocation | undefined;
12
+ radius?: number | undefined;
13
+ components: {
14
+ countries: string | string[] | undefined;
15
+ };
16
+ }
17
+ interface IPredictionSubstring {
18
+ length: number;
19
+ offset: number;
20
+ }
21
+ interface IAutocompleteStructuredFormatting {
22
+ main_text: string;
23
+ main_text_matched_substrings: IPredictionSubstring[];
24
+ secondary_text: string;
25
+ }
26
+ interface IPredictionTerm {
27
+ offset: number;
28
+ value: string;
29
+ }
30
+ export interface IPrediction {
31
+ description: string;
32
+ matched_substrings: IPredictionSubstring[];
33
+ place_id: string;
34
+ reference: string;
35
+ structured_formatting: IAutocompleteStructuredFormatting;
36
+ terms: IPredictionTerm[];
37
+ types: string[];
38
+ }
39
+ export interface IGooglePlacesAPIProviderProps {
40
+ children: React.ReactNode;
41
+ apiKey: string;
42
+ language?: string;
43
+ libraries?: string;
44
+ }
45
+ export declare const GooglePlacesAPIProvider: ({ children, apiKey, language, libraries, }: IGooglePlacesAPIProviderProps) => JSX.Element;
46
+ export declare const useGooglePlacesAPI: () => {
47
+ available: boolean;
48
+ };
49
+ export declare const useAddressPredictions: (input: string, { types, location, radius, components }: IPredictionsOptions) => {
50
+ available: boolean;
51
+ predictions: IPrediction[];
52
+ getPlacePredictions: (input: string) => Promise<IPrediction[]>;
53
+ };
54
+ export {};
@@ -0,0 +1,114 @@
1
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
2
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
4
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
5
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) { ; } } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
7
+ /// <reference types="@types/googlemaps" />
8
+ import React, { createContext, useState, useContext, useRef, useEffect } from 'react';
9
+ import { useScript } from '@dfds-ui/hooks';
10
+ import { jsx as ___EmotionJSX } from "@emotion/react";
11
+ export var GooglePlacesAPIContext = /*#__PURE__*/createContext({
12
+ available: false
13
+ });
14
+ export var GooglePlacesAPIProvider = function GooglePlacesAPIProvider(_ref) {
15
+ var _window, _window$google;
16
+ var children = _ref.children,
17
+ apiKey = _ref.apiKey,
18
+ language = _ref.language,
19
+ _ref$libraries = _ref.libraries,
20
+ libraries = _ref$libraries === void 0 ? 'places' : _ref$libraries;
21
+ // On SSR window does not exist.
22
+ var hasWindow = typeof window !== 'undefined';
23
+
24
+ // We want to prevent the google maps api to be loaded more than once
25
+ var isGoogleMapsDefined = hasWindow && Boolean((_window = window) === null || _window === void 0 ? void 0 : (_window$google = _window.google) === null || _window$google === void 0 ? void 0 : _window$google.maps);
26
+ var languageParam = language ? "&language=".concat(language) : '';
27
+ // NOTE: Google Maps API requires a callback when ran asynchronously. See https://developers.google.com/maps/documentation/javascript/url-params#required_parameters
28
+ // Dummy callback to satisfy Google Maps API.
29
+ var dummyCallback = function dummyCallback() {
30
+ return;
31
+ };
32
+ // @ts-expect-error dummyCallback does not exist on window. A callback is required by Google Maps API.
33
+ if (hasWindow) window.dummyCallback = dummyCallback;
34
+ var callback = hasWindow ? "&callback=dummyCallback" : '';
35
+ var scriptUrl = "https://maps.googleapis.com/maps/api/js?key=".concat(apiKey, "&libraries=").concat(libraries).concat(languageParam).concat(callback);
36
+ var _useScript = useScript(scriptUrl, isGoogleMapsDefined),
37
+ _useScript2 = _slicedToArray(_useScript, 2),
38
+ loaded = _useScript2[0],
39
+ error = _useScript2[1];
40
+ var _useState = useState(false),
41
+ _useState2 = _slicedToArray(_useState, 2),
42
+ available = _useState2[0],
43
+ setAvailable = _useState2[1];
44
+ useEffect(function () {
45
+ setAvailable(loaded && !error);
46
+ if (error) {
47
+ throw new Error('Google Places API script failed to load');
48
+ }
49
+ }, [loaded, error]);
50
+ return ___EmotionJSX(GooglePlacesAPIContext.Provider, {
51
+ value: {
52
+ available: available
53
+ }
54
+ }, children);
55
+ };
56
+ export var useGooglePlacesAPI = function useGooglePlacesAPI() {
57
+ var context = useContext(GooglePlacesAPIContext);
58
+ if (context === undefined) {
59
+ throw new Error('useGooglePlaces must be used inside of GooglePlacesAPIProvider');
60
+ }
61
+ return context;
62
+ };
63
+ export var useAddressPredictions = function useAddressPredictions(input, _ref2) {
64
+ var types = _ref2.types,
65
+ location = _ref2.location,
66
+ radius = _ref2.radius,
67
+ components = _ref2.components;
68
+ var _useState3 = useState([]),
69
+ _useState4 = _slicedToArray(_useState3, 2),
70
+ predictions = _useState4[0],
71
+ setPredictions = _useState4[1];
72
+ var _useGooglePlacesAPI = useGooglePlacesAPI(),
73
+ available = _useGooglePlacesAPI.available;
74
+ var autocomplete = useRef();
75
+ if (!autocomplete.current && available && typeof window !== 'undefined') {
76
+ autocomplete.current = new google.maps.places.AutocompleteService();
77
+ }
78
+ function getPlacePredictions(input) {
79
+ return new Promise(function (resolve) {
80
+ autocomplete.current.getPlacePredictions({
81
+ input: input,
82
+ types: types,
83
+ radius: radius,
84
+ location: location !== undefined ? {
85
+ lat: function lat() {
86
+ return location !== undefined ? location.lat : undefined;
87
+ },
88
+ lng: function lng() {
89
+ return location !== undefined ? location.lng : undefined;
90
+ }
91
+ } : undefined,
92
+ componentRestrictions: {
93
+ country: components.countries
94
+ }
95
+ }, function (predictions) {
96
+ var _predictions;
97
+ predictions = (_predictions = predictions) !== null && _predictions !== void 0 ? _predictions : [];
98
+ setPredictions(predictions);
99
+ resolve(predictions);
100
+ });
101
+ });
102
+ }
103
+ useEffect(function () {
104
+ if (input !== '') {
105
+ void getPlacePredictions(input);
106
+ }
107
+ // eslint-disable-next-line react-hooks/exhaustive-deps
108
+ }, [input]);
109
+ return {
110
+ available: available,
111
+ predictions: predictions,
112
+ getPlacePredictions: getPlacePredictions
113
+ };
114
+ };
@@ -0,0 +1,29 @@
1
+ /// <reference types="react" />
2
+ import { ILocation, IPrediction } from './GooglePlaces';
3
+ export type AddressSelectProps = {
4
+ components?: any;
5
+ name: string;
6
+ disabled?: boolean;
7
+ error?: string;
8
+ size?: 'small' | 'medium';
9
+ types?: string[];
10
+ onFocus?: (event: FocusEvent) => void;
11
+ onBlur?: (event: FocusEvent) => void;
12
+ onChange?: (changed: {
13
+ value: string;
14
+ label: string;
15
+ }, predictions: IPrediction[]) => void;
16
+ location?: ILocation;
17
+ radius?: number;
18
+ countries?: string[] | string;
19
+ placeholder?: string;
20
+ assistiveText?: string;
21
+ autoFocus?: boolean;
22
+ isClearable?: boolean;
23
+ /**
24
+ * Class name to be assigned to the component
25
+ */
26
+ className?: string;
27
+ };
28
+ declare const AddressSelect: ({ name, disabled, error, size, types, onFocus, onBlur, onChange, location, radius, countries, ...rest }: AddressSelectProps) => JSX.Element;
29
+ export default AddressSelect;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _react = _interopRequireWildcard(require("react"));
8
+ var _reactComponents = require("@dfds-ui/react-components");
9
+ var _lodash = _interopRequireDefault(require("lodash.debounce"));
10
+ var _GooglePlaces = require("./GooglePlaces");
11
+ var _react2 = require("@emotion/react");
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
14
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
15
+ function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
16
+ const AddressSelect = ({
17
+ name,
18
+ disabled,
19
+ error,
20
+ size = 'medium',
21
+ types,
22
+ onFocus,
23
+ onBlur,
24
+ onChange,
25
+ location,
26
+ radius,
27
+ countries = [],
28
+ ...rest
29
+ }) => {
30
+ const [predictions, setPredictions] = (0, _react.useState)([]);
31
+ const {
32
+ available,
33
+ getPlacePredictions
34
+ } = (0, _GooglePlaces.useAddressPredictions)('', {
35
+ types,
36
+ location,
37
+ radius,
38
+ components: {
39
+ countries
40
+ }
41
+ });
42
+ const loadOptions = async (input, callback) => {
43
+ const placePredictions = await getPlacePredictions(input);
44
+ setPredictions(placePredictions);
45
+ const options = placePredictions.map(prediction => ({
46
+ value: prediction.description,
47
+ label: prediction.description,
48
+ prediction
49
+ }));
50
+ callback(options);
51
+ };
52
+ const handleChange = value => {
53
+ if (onChange) {
54
+ onChange(value, predictions);
55
+ }
56
+ };
57
+ return (0, _react2.jsx)(_reactComponents.AsyncSearchableSelect, _extends({
58
+ disabled: disabled || !available,
59
+ name: name,
60
+ error: error,
61
+ size: size,
62
+ onChange: handleChange,
63
+ loadOptions: (0, _lodash.default)(loadOptions, 500),
64
+ onFocus: onFocus,
65
+ onBlur: onBlur
66
+ }, rest));
67
+ };
68
+ var _default = AddressSelect;
69
+ exports.default = _default;
@@ -0,0 +1,54 @@
1
+ import React from 'react';
2
+ export declare const GooglePlacesAPIContext: React.Context<{
3
+ available: boolean;
4
+ }>;
5
+ export interface ILocation {
6
+ lat: number;
7
+ lng: number;
8
+ }
9
+ interface IPredictionsOptions {
10
+ types?: string[] | undefined;
11
+ location?: ILocation | undefined;
12
+ radius?: number | undefined;
13
+ components: {
14
+ countries: string | string[] | undefined;
15
+ };
16
+ }
17
+ interface IPredictionSubstring {
18
+ length: number;
19
+ offset: number;
20
+ }
21
+ interface IAutocompleteStructuredFormatting {
22
+ main_text: string;
23
+ main_text_matched_substrings: IPredictionSubstring[];
24
+ secondary_text: string;
25
+ }
26
+ interface IPredictionTerm {
27
+ offset: number;
28
+ value: string;
29
+ }
30
+ export interface IPrediction {
31
+ description: string;
32
+ matched_substrings: IPredictionSubstring[];
33
+ place_id: string;
34
+ reference: string;
35
+ structured_formatting: IAutocompleteStructuredFormatting;
36
+ terms: IPredictionTerm[];
37
+ types: string[];
38
+ }
39
+ export interface IGooglePlacesAPIProviderProps {
40
+ children: React.ReactNode;
41
+ apiKey: string;
42
+ language?: string;
43
+ libraries?: string;
44
+ }
45
+ export declare const GooglePlacesAPIProvider: ({ children, apiKey, language, libraries, }: IGooglePlacesAPIProviderProps) => JSX.Element;
46
+ export declare const useGooglePlacesAPI: () => {
47
+ available: boolean;
48
+ };
49
+ export declare const useAddressPredictions: (input: string, { types, location, radius, components }: IPredictionsOptions) => {
50
+ available: boolean;
51
+ predictions: IPrediction[];
52
+ getPlacePredictions: (input: string) => Promise<IPrediction[]>;
53
+ };
54
+ export {};
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useGooglePlacesAPI = exports.useAddressPredictions = exports.GooglePlacesAPIProvider = exports.GooglePlacesAPIContext = void 0;
7
+ var _react = _interopRequireWildcard(require("react"));
8
+ var _hooks = require("@dfds-ui/hooks");
9
+ var _react2 = require("@emotion/react");
10
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
11
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
12
+ /// <reference types="@types/googlemaps" />
13
+
14
+ const GooglePlacesAPIContext = /*#__PURE__*/(0, _react.createContext)({
15
+ available: false
16
+ });
17
+ exports.GooglePlacesAPIContext = GooglePlacesAPIContext;
18
+ const GooglePlacesAPIProvider = ({
19
+ children,
20
+ apiKey,
21
+ language,
22
+ libraries = 'places'
23
+ }) => {
24
+ // On SSR window does not exist.
25
+ const hasWindow = typeof window !== 'undefined';
26
+
27
+ // We want to prevent the google maps api to be loaded more than once
28
+ const isGoogleMapsDefined = hasWindow && Boolean(window?.google?.maps);
29
+ const languageParam = language ? `&language=${language}` : '';
30
+ // NOTE: Google Maps API requires a callback when ran asynchronously. See https://developers.google.com/maps/documentation/javascript/url-params#required_parameters
31
+ // Dummy callback to satisfy Google Maps API.
32
+ const dummyCallback = () => {
33
+ return;
34
+ };
35
+ // @ts-expect-error dummyCallback does not exist on window. A callback is required by Google Maps API.
36
+ if (hasWindow) window.dummyCallback = dummyCallback;
37
+ const callback = hasWindow ? `&callback=dummyCallback` : '';
38
+ const scriptUrl = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=${libraries}${languageParam}${callback}`;
39
+ const [loaded, error] = (0, _hooks.useScript)(scriptUrl, isGoogleMapsDefined);
40
+ const [available, setAvailable] = (0, _react.useState)(false);
41
+ (0, _react.useEffect)(() => {
42
+ setAvailable(loaded && !error);
43
+ if (error) {
44
+ throw new Error('Google Places API script failed to load');
45
+ }
46
+ }, [loaded, error]);
47
+ return (0, _react2.jsx)(GooglePlacesAPIContext.Provider, {
48
+ value: {
49
+ available
50
+ }
51
+ }, children);
52
+ };
53
+ exports.GooglePlacesAPIProvider = GooglePlacesAPIProvider;
54
+ const useGooglePlacesAPI = () => {
55
+ const context = (0, _react.useContext)(GooglePlacesAPIContext);
56
+ if (context === undefined) {
57
+ throw new Error('useGooglePlaces must be used inside of GooglePlacesAPIProvider');
58
+ }
59
+ return context;
60
+ };
61
+ exports.useGooglePlacesAPI = useGooglePlacesAPI;
62
+ const useAddressPredictions = (input, {
63
+ types,
64
+ location,
65
+ radius,
66
+ components
67
+ }) => {
68
+ const [predictions, setPredictions] = (0, _react.useState)([]);
69
+ const {
70
+ available
71
+ } = useGooglePlacesAPI();
72
+ const autocomplete = (0, _react.useRef)();
73
+ if (!autocomplete.current && available && typeof window !== 'undefined') {
74
+ autocomplete.current = new google.maps.places.AutocompleteService();
75
+ }
76
+ function getPlacePredictions(input) {
77
+ return new Promise(resolve => {
78
+ autocomplete.current.getPlacePredictions({
79
+ input,
80
+ types,
81
+ radius,
82
+ location: location !== undefined ? {
83
+ lat: () => location !== undefined ? location.lat : undefined,
84
+ lng: () => location !== undefined ? location.lng : undefined
85
+ } : undefined,
86
+ componentRestrictions: {
87
+ country: components.countries
88
+ }
89
+ }, predictions => {
90
+ predictions = predictions ?? [];
91
+ setPredictions(predictions);
92
+ resolve(predictions);
93
+ });
94
+ });
95
+ }
96
+ (0, _react.useEffect)(() => {
97
+ if (input !== '') {
98
+ void getPlacePredictions(input);
99
+ }
100
+ // eslint-disable-next-line react-hooks/exhaustive-deps
101
+ }, [input]);
102
+ return {
103
+ available,
104
+ predictions,
105
+ getPlacePredictions
106
+ };
107
+ };
108
+ exports.useAddressPredictions = useAddressPredictions;
package/cjs/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './GooglePlaces';
2
+ export { default as AddressSelect } from './AddressSelect';
3
+ export * from './AddressSelect';
package/cjs/index.js ADDED
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _exportNames = {
7
+ AddressSelect: true
8
+ };
9
+ Object.defineProperty(exports, "AddressSelect", {
10
+ enumerable: true,
11
+ get: function () {
12
+ return _AddressSelect.default;
13
+ }
14
+ });
15
+ var _GooglePlaces = require("./GooglePlaces");
16
+ Object.keys(_GooglePlaces).forEach(function (key) {
17
+ if (key === "default" || key === "__esModule") return;
18
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
19
+ if (key in exports && exports[key] === _GooglePlaces[key]) return;
20
+ Object.defineProperty(exports, key, {
21
+ enumerable: true,
22
+ get: function () {
23
+ return _GooglePlaces[key];
24
+ }
25
+ });
26
+ });
27
+ var _AddressSelect = _interopRequireWildcard(require("./AddressSelect"));
28
+ Object.keys(_AddressSelect).forEach(function (key) {
29
+ if (key === "default" || key === "__esModule") return;
30
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
31
+ if (key in exports && exports[key] === _AddressSelect[key]) return;
32
+ Object.defineProperty(exports, key, {
33
+ enumerable: true,
34
+ get: function () {
35
+ return _AddressSelect[key];
36
+ }
37
+ });
38
+ });
39
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
40
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
@@ -0,0 +1 @@
1
+ "use strict";
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './GooglePlaces';
2
+ export { default as AddressSelect } from './AddressSelect';
3
+ export * from './AddressSelect';
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './GooglePlaces';
2
+ export { default as AddressSelect } from './AddressSelect';
3
+ export * from './AddressSelect';
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Components using Google places",
4
4
  "license": "MIT",
5
5
  "private": false,
6
- "version": "2.2.0-alpha.8d87a90d",
6
+ "version": "2.2.0-alpha.e74a6756",
7
7
  "sideEffects": false,
8
8
  "main": "./cjs/index.js",
9
9
  "module": "./index.js",
@@ -14,15 +14,15 @@
14
14
  "react-dom": ">= 17.0.2"
15
15
  },
16
16
  "dependencies": {
17
- "@dfds-ui/colors": "2.2.0-alpha.8d87a90d",
18
- "@dfds-ui/hooks": "2.2.0-alpha.8d87a90d",
19
- "@dfds-ui/icons": "2.2.0-alpha.8d87a90d",
20
- "@dfds-ui/react-components": "2.2.0-alpha.8d87a90d",
17
+ "@dfds-ui/colors": "2.2.0-alpha.e74a6756",
18
+ "@dfds-ui/hooks": "2.2.0-alpha.e74a6756",
19
+ "@dfds-ui/icons": "2.2.0-alpha.e74a6756",
20
+ "@dfds-ui/react-components": "2.2.0-alpha.e74a6756",
21
21
  "@types/googlemaps": "3.43.3",
22
22
  "@types/lodash.debounce": "^4.0.7",
23
23
  "lodash.debounce": "^4.0.8"
24
24
  },
25
- "gitHead": "8d87a90d4501dae81cac37ab3b4d9f13a68e2ab3",
25
+ "gitHead": "e74a675673c3e4bff9fc9d248fb133b1a6667383",
26
26
  "publishConfig": {
27
27
  "access": "public"
28
28
  }
package/typings.d.js ADDED
File without changes