@pega/cosmos-react-core 7.16.2 → 7.16.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"LocationInput.d.ts","sourceRoot":"","sources":["../../../src/components/Location/LocationInput.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAe,EAAE,EAAwB,MAAM,OAAO,CAAC;AAQnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAgBvE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAGxD,MAAM,WAAW,kBAAmB,SAAQ,SAAS,EAAE,gBAAgB,EAAE,UAAU;IACjF;;;OAGG;IACH,wBAAwB,CAAC,EAAE,OAAO,CAAC;IACnC,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC;;;OAGG;IACH,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,yGAAyG;IACzG,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE;QACjB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,KAAK,IAAI,CAAC;IACX;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,8DAA8D;IAC9D,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ;;;OAGG;IACH,GAAG,CAAC,EAAE;QACJ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C;QAClB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,KAAK,IAAI,CAAC;IACX;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,8DAA8D;IAC9D,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ;;;OAGG;IACH,GAAG,CAAC,EAAE;QACJ,kDAAkD;QAClD,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE,iBAAiB,CAAC,QAAQ,CAAC,CAAC;QACpC,SAAS,CAAC,EAAE,iBAAiB,CAAC,WAAW,CAAC,CAAC;QAC3C,OAAO,CAAC,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAC;KACxC,CAAC;IACF,sGAAsG;IACtG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;;;;AA0UD,wBAAmE"}
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { forwardRef, useCallback, useContext, useEffect, useState } from 'react';
2
+ import { forwardRef, useCallback, useContext, useEffect, useRef, useState } from 'react';
3
3
  import styled from 'styled-components';
4
4
  import ComboBox from '../ComboBox';
5
5
  import { useI18n, useTestIds, useUID } from '../../hooks';
@@ -13,6 +13,8 @@ import MapsContext from './MapsContext';
13
13
  import { getAddress, getCoords, getNavigatorPosition, getPlaceById, getPlacePredictions, isValueACoordinate, loadMapsAPI } from './utils';
14
14
  import LocationView, { StyledLocationView } from './LocationView';
15
15
  import { getLocationInputTestIds } from './Location.test-ids';
16
+ // Session token timeout in milliseconds for single user interaction.
17
+ const sessionTokenTimeout = 120000;
16
18
  const StyledLocationInput = styled(ComboBox) `
17
19
  z-index: 1;
18
20
  `;
@@ -32,7 +34,26 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
32
34
  const t = useI18n();
33
35
  const [placePredictionMenuItems, setPlacePredictionMenuItems] = useState([]);
34
36
  const [filterValue, setFilterValue] = useState('');
37
+ const [debouncedFilterValue, setDebouncedFilterValue] = useState('');
35
38
  const [mapLoading, setMapLoading] = useState(false);
39
+ const sessionTokenRef = useRef();
40
+ const interactionTimerRef = useRef();
41
+ const clearInteractionTimer = useCallback(() => {
42
+ if (interactionTimerRef.current !== undefined) {
43
+ window.clearTimeout(interactionTimerRef.current);
44
+ interactionTimerRef.current = undefined;
45
+ }
46
+ }, []);
47
+ const startInteractionTimer = useCallback(() => {
48
+ if (interactionTimerRef.current !== undefined)
49
+ return;
50
+ interactionTimerRef.current = window.setTimeout(() => {
51
+ sessionTokenRef.current = undefined;
52
+ interactionTimerRef.current = undefined;
53
+ }, sessionTokenTimeout);
54
+ }, []);
55
+ useEffect(() => clearInteractionTimer, [clearInteractionTimer]);
56
+ const getSessionToken = useCallback(() => sessionTokenRef.current, []);
36
57
  useEffect(() => {
37
58
  (async () => {
38
59
  if (defaultToCurrentLocation) {
@@ -46,12 +67,23 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
46
67
  })();
47
68
  }, []);
48
69
  useEffect(() => {
70
+ if (!filterValue) {
71
+ setDebouncedFilterValue('');
72
+ return;
73
+ }
74
+ const timer = window.setTimeout(() => setDebouncedFilterValue(filterValue), 500);
75
+ return () => window.clearTimeout(timer);
76
+ }, [filterValue]);
77
+ useEffect(() => {
78
+ let isCurrent = true;
49
79
  (async () => {
50
80
  try {
51
81
  await loadMapsAPI(name, providerOpts);
52
- if (filterValue) {
82
+ if (debouncedFilterValue) {
53
83
  if (onlyCoordinates) {
54
- const { latitude, longitude } = await getCoords(filterValue);
84
+ const { latitude, longitude } = await getCoords(debouncedFilterValue);
85
+ if (!isCurrent)
86
+ return;
55
87
  setPlacePredictionMenuItems([
56
88
  {
57
89
  primary: t('exact_location'),
@@ -65,9 +97,14 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
65
97
  ]);
66
98
  }
67
99
  else {
68
- if (isValueACoordinate(filterValue)) {
69
- const { latitude, longitude } = await getCoords(filterValue);
70
- const { name: addressName, address } = await getAddress({ latitude, longitude });
100
+ if (isValueACoordinate(debouncedFilterValue)) {
101
+ const { latitude, longitude } = await getCoords(debouncedFilterValue);
102
+ const { name: addressName, address } = await getAddress({
103
+ latitude,
104
+ longitude
105
+ });
106
+ if (!isCurrent)
107
+ return;
71
108
  const menuItems = [
72
109
  {
73
110
  primary: t('exact_location'),
@@ -94,49 +131,32 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
94
131
  setPlacePredictionMenuItems(menuItems);
95
132
  return;
96
133
  }
97
- const { placePredictions, token } = await getPlacePredictions(filterValue, bias);
98
- if (placePredictions.length === 1) {
99
- const exactLocation = await getPlaceById(placePredictions[0].place_id, token);
100
- const menuItems = placePredictions.map(item => ({
101
- id: item.place_id,
102
- primary: item.structured_formatting.main_text,
103
- secondary: [item.structured_formatting.secondary_text],
104
- onClick: (menuItemId) => {
105
- getPlaceById(menuItemId, token).then(menuItemLocation => {
106
- setFilterValue('');
107
- onSelect?.(menuItemLocation);
108
- });
109
- }
110
- }));
111
- if (exactLocation) {
112
- menuItems.push({
113
- primary: t('exact_location'),
114
- secondary: [`${exactLocation.latitude}, ${exactLocation.longitude}`],
115
- id: createUID(),
116
- onClick: () => {
117
- setFilterValue('');
118
- onSelect?.({
119
- latitude: exactLocation.latitude,
120
- longitude: exactLocation.longitude
121
- });
122
- }
134
+ if (!sessionTokenRef.current) {
135
+ sessionTokenRef.current = new google.maps.places.AutocompleteSessionToken();
136
+ }
137
+ const activeToken = sessionTokenRef.current;
138
+ const { placePredictions } = await getPlacePredictions(debouncedFilterValue, bias, activeToken);
139
+ if (!isCurrent)
140
+ return;
141
+ startInteractionTimer();
142
+ setPlacePredictionMenuItems(placePredictions.map(item => ({
143
+ id: item.place_id,
144
+ primary: item.structured_formatting.main_text,
145
+ secondary: [item.structured_formatting.secondary_text],
146
+ onClick: (menuItemId) => {
147
+ getPlaceById(menuItemId, activeToken).then(menuItemLocation => {
148
+ sessionTokenRef.current = undefined;
149
+ clearInteractionTimer();
150
+ setFilterValue('');
151
+ onSelect?.(menuItemLocation);
152
+ }, e => {
153
+ sessionTokenRef.current = undefined;
154
+ clearInteractionTimer();
155
+ setFilterValue('');
156
+ onError?.(e instanceof Error ? e : new Error(String(e)));
123
157
  });
124
158
  }
125
- setPlacePredictionMenuItems(menuItems);
126
- }
127
- else {
128
- setPlacePredictionMenuItems(placePredictions.map(item => ({
129
- id: item.place_id,
130
- primary: item.structured_formatting.main_text,
131
- secondary: [item.structured_formatting.secondary_text],
132
- onClick: (menuItemId) => {
133
- getPlaceById(menuItemId, token).then(menuItemLocation => {
134
- setFilterValue('');
135
- onSelect?.(menuItemLocation);
136
- });
137
- }
138
- })));
139
- }
159
+ })));
140
160
  }
141
161
  }
142
162
  else {
@@ -144,11 +164,16 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
144
164
  }
145
165
  }
146
166
  catch (e) {
167
+ if (!isCurrent)
168
+ return;
147
169
  setPlacePredictionMenuItems([]);
148
170
  onError?.(e);
149
171
  }
150
172
  })();
151
- }, [filterValue, bias, onError, onSelect, onlyCoordinates]);
173
+ return () => {
174
+ isCurrent = false;
175
+ };
176
+ }, [debouncedFilterValue, bias, onError, onSelect, onlyCoordinates]);
152
177
  const onInputChange = useCallback((e) => {
153
178
  setFilterValue(e.target.value.trim());
154
179
  onChange?.(e.target.value);
@@ -156,6 +181,8 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
156
181
  const onMapClick = useCallback((placeInfo) => {
157
182
  if (readOnly)
158
183
  return;
184
+ sessionTokenRef.current = undefined;
185
+ clearInteractionTimer();
159
186
  if (onlyCoordinates) {
160
187
  const coords = {
161
188
  latitude: placeInfo.latitude,
@@ -196,7 +223,7 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
196
223
  } })), onChange: onInputChange, onBlur: () => {
197
224
  setFilterValue('');
198
225
  onBlur?.(value);
199
- }, value: value, required: required, disabled: disabled, readOnly: readOnly, status: status, ...restProps }), map && (_jsx(StyledLocationMap, { children: _jsx(LocationView, { ...map, pins: map.location ? [{ ...map.location }] : [], onClick: onMapClick, onError: onError, disabled: disabled, loading: mapLoading, centerMapOnChange: true }) }))] }));
226
+ }, value: value, required: required, disabled: disabled, readOnly: readOnly, status: status, ...restProps }), map && (_jsx(StyledLocationMap, { children: _jsx(LocationView, { ...map, pins: map.location ? [{ ...map.location }] : [], onClick: onMapClick, onError: onError, disabled: disabled, loading: mapLoading, centerMapOnChange: true, getSessionToken: getSessionToken }) }))] }));
200
227
  return label ? (_jsx(FormField, { testId: testIds, label: label, labelHidden: labelHidden, id: id, info: info, readOnly: readOnly, status: status, ref: ref, required: required, disabled: disabled, additionalInfo: additionalInfo, children: Comp })) : (Comp);
201
228
  });
202
229
  export default withTestIds(LocationInput, getLocationInputTestIds);
@@ -1 +1 @@
1
- {"version":3,"file":"LocationInput.js","sourceRoot":"","sources":["../../../src/components/Location/LocationInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEjF,OAAO,MAAM,MAAM,mBAAmB,CAAC;AAEvC,OAAO,QAAQ,MAAM,aAAa,CAAC;AAEnC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,SAAS,MAAM,cAAc,CAAC;AAGrC,OAAO,IAAI,MAAM,SAAS,CAAC;AAC3B,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,oBAAoB,MAAM,wBAAwB,CAAC;AAC1D,OAAO,qBAAqB,MAAM,yBAAyB,CAAC;AAC5D,OAAO,WAAW,MAAM,eAAe,CAAC;AACxC,OAAO,EACL,UAAU,EACV,SAAS,EACT,oBAAoB,EACpB,YAAY,EACZ,mBAAmB,EACnB,kBAAkB,EAClB,WAAW,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EAAE,CAAC,CAAC;oBACnB,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;gBAClB,CAAC,EACD,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,MAAM,KACV,SAAS,GACb,EACD,GAAG,IAAI,CACN,KAAC,iBAAiB,cAChB,KAAC,YAAY,OACP,GAAG,EACP,IAAI,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAC/C,OAAO,EAAE,UAAU,EACnB,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,UAAU,EACnB,iBAAiB,SACjB,GACgB,CACrB,IACA,CACJ,CAAC;IAEF,OAAO,KAAK,CAAC,CAAC,CAAC,CACb,KAAC,SAAS,IACR,MAAM,EAAE,OAAO,EACf,KAAK,EAAE,KAAK,EACZ,WAAW,EAAE,WAAW,EACxB,EAAE,EAAE,EAAE,EACN,IAAI,EAAE,IAAI,EACV,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,GAAG,EACR,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,QAAQ,EAClB,cAAc,EAAE,cAAc,YAE7B,IAAI,GACK,CACb,CAAC,CAAC,CAAC,CACF,IAAI,CACL,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,eAAe,WAAW,CAAC,aAAa,EAAE,uBAAuB,CAAC,CAAC","sourcesContent":["import { forwardRef, useCallback, useContext, useEffect, useState } from 'react';\nimport type { ChangeEvent, FC, PropsWithoutRef, Ref } from 'react';\nimport styled from 'styled-components';\n\nimport ComboBox from '../ComboBox';\nimport type { MenuItemProps, MenuProps } from '../Menu';\nimport { useI18n, useTestIds, useUID } from '../../hooks';\nimport { createUID, withTestIds } from '../../utils';\nimport FormField from '../FormField';\nimport type { FormControlProps } from '../FormControl';\nimport type { BaseProps, ForwardProps, TestIdProp } from '../../types';\nimport Flex from '../Flex';\nimport { defaultThemeProp } from '../../theme';\n\nimport PoweredByGoogleImage from './PoweredByGoogleImage';\nimport CurrentLocationButton from './CurrentLocationButton';\nimport MapsContext from './MapsContext';\nimport {\n getAddress,\n getCoords,\n getNavigatorPosition,\n getPlaceById,\n getPlacePredictions,\n isValueACoordinate,\n loadMapsAPI\n} from './utils';\nimport type { Bias, LatLng } from './Location.types';\nimport LocationView, { StyledLocationView } from './LocationView';\nimport type { LocationViewProps } from './LocationView';\nimport { getLocationInputTestIds } from './Location.test-ids';\n\nexport interface LocationInputProps extends BaseProps, FormControlProps, TestIdProp {\n /**\n * Get user current location on component first render.\n * @default false\n */\n defaultToCurrentLocation?: boolean;\n /** The value of the location field. */\n value?: string;\n /**\n * Callback fired on every change of the location input.\n * The argument passed back is the component's value prop.\n */\n onChange?: (value: string) => void;\n /**\n * Callback fired when the control's input loses focus.\n * The argument passed back is the component's value prop.\n */\n onBlur?: (value: string) => void;\n /** Callback fired when user chooses location from the dropdown of suggestions or submits input value. */\n onSelect?: (value: {\n name?: string;\n address?: string;\n latitude?: number;\n longitude?: number;\n }) => void;\n /**\n * Only select coordinates on map clicks.\n * @default false\n */\n onlyCoordinates?: boolean;\n /** Biasing query results towards user location/preference. */\n bias?: Bias;\n /**\n * Set to true renders the map view below input.\n * @default false\n */\n map?: {\n /** Location coordinates used for the map view. */\n location?: LatLng;\n height: LocationViewProps['height'];\n zoomLevel?: LocationViewProps['zoomLevel'];\n onClick?: LocationViewProps['onClick'];\n };\n /** Callback fired when an error occurs. This function gets called with one argument of type Error. */\n onError?: (error: Error) => void;\n}\n\nconst StyledLocationInput = styled(ComboBox)`\n z-index: 1;\n`;\n\nStyledLocationInput.defaultProps = defaultThemeProp;\n\nconst StyledLocationMap = styled.div`\n ${StyledLocationView} {\n border-top-left-radius: 0;\n border-top-right-radius: 0;\n }\n`;\n\nStyledLocationMap.defaultProps = defaultThemeProp;\n\nconst LocationInput: FC<LocationInputProps & ForwardProps> = forwardRef(function LocationInput(\n props: PropsWithoutRef<LocationInputProps>,\n ref: Ref<HTMLInputElement>\n) {\n const uid = useUID();\n const {\n testId,\n label,\n labelHidden,\n id = uid,\n value = '',\n info,\n status,\n required,\n readOnly,\n disabled,\n additionalInfo,\n onSelect,\n onError,\n onChange,\n onBlur,\n bias,\n defaultToCurrentLocation,\n onlyCoordinates = false,\n map,\n ...restProps\n } = props;\n\n const testIds = useTestIds(testId, getLocationInputTestIds);\n\n const { name, ...providerOpts } = useContext(MapsContext);\n const t = useI18n();\n const [placePredictionMenuItems, setPlacePredictionMenuItems] = useState<MenuProps['items']>([]);\n const [filterValue, setFilterValue] = useState('');\n const [mapLoading, setMapLoading] = useState(false);\n\n useEffect(() => {\n (async () => {\n if (defaultToCurrentLocation) {\n setMapLoading(true);\n await loadMapsAPI(name, providerOpts);\n const navigatorPosition = await getNavigatorPosition();\n const currentLocationAddress = await getAddress(navigatorPosition);\n setMapLoading(false);\n onSelect?.(currentLocationAddress);\n }\n })();\n }, []);\n\n useEffect(() => {\n (async () => {\n try {\n await loadMapsAPI(name, providerOpts);\n if (filterValue) {\n if (onlyCoordinates) {\n const { latitude, longitude } = await getCoords(filterValue);\n setPlacePredictionMenuItems([\n {\n primary: t('exact_location'),\n secondary: [`${latitude}, ${longitude}`],\n id: createUID(),\n onClick: () => {\n setFilterValue('');\n onSelect?.({ latitude, longitude });\n }\n }\n ]);\n } else {\n if (isValueACoordinate(filterValue)) {\n const { latitude, longitude } = await getCoords(filterValue);\n const { name: addressName, address } = await getAddress({ latitude, longitude });\n const menuItems = [\n {\n primary: t('exact_location'),\n secondary: [`${latitude}, ${longitude}`],\n id: createUID(),\n onClick: () => {\n setFilterValue('');\n onSelect?.({\n latitude,\n longitude\n });\n }\n },\n {\n primary: addressName,\n secondary: [address],\n id: createUID(),\n onClick: () => {\n setFilterValue('');\n onSelect?.({ name: addressName, address, latitude, longitude });\n }\n }\n ];\n\n setPlacePredictionMenuItems(menuItems);\n return;\n }\n const { placePredictions, token } = await getPlacePredictions(filterValue, bias);\n if (placePredictions.length === 1) {\n const exactLocation = await getPlaceById(placePredictions[0].place_id, token);\n const menuItems = placePredictions.map(item => ({\n id: item.place_id,\n primary: item.structured_formatting.main_text,\n secondary: [item.structured_formatting.secondary_text],\n onClick: (menuItemId: MenuItemProps['id']) => {\n getPlaceById(menuItemId, token).then(menuItemLocation => {\n setFilterValue('');\n onSelect?.(menuItemLocation);\n });\n }\n }));\n if (exactLocation) {\n menuItems.push({\n primary: t('exact_location'),\n secondary: [`${exactLocation.latitude}, ${exactLocation.longitude}`],\n id: createUID(),\n onClick: () => {\n setFilterValue('');\n onSelect?.({\n latitude: exactLocation.latitude,\n longitude: exactLocation.longitude\n });\n }\n });\n }\n setPlacePredictionMenuItems(menuItems);\n } else {\n setPlacePredictionMenuItems(\n placePredictions.map(item => ({\n id: item.place_id,\n primary: item.structured_formatting.main_text,\n secondary: [item.structured_formatting.secondary_text],\n onClick: (menuItemId: MenuItemProps['id']) => {\n getPlaceById(menuItemId, token).then(menuItemLocation => {\n setFilterValue('');\n onSelect?.(menuItemLocation);\n });\n }\n }))\n );\n }\n }\n } else {\n setPlacePredictionMenuItems([]);\n }\n } catch (e: any) {\n setPlacePredictionMenuItems([]);\n onError?.(e);\n }\n })();\n }, [filterValue, bias, onError, onSelect, onlyCoordinates]);\n\n const onInputChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n setFilterValue(e.target.value.trim());\n onChange?.(e.target.value);\n },\n [onChange]\n );\n\n const onMapClick = useCallback(\n (placeInfo: { latitude: number; longitude: number; name?: string; address?: string }) => {\n if (readOnly) return;\n\n if (onlyCoordinates) {\n const coords = {\n latitude: placeInfo.latitude,\n longitude: placeInfo.longitude\n };\n onSelect?.(coords);\n map?.onClick?.(coords);\n } else {\n onSelect?.(placeInfo);\n map?.onClick?.(placeInfo);\n }\n },\n [readOnly, onSelect, map?.onClick, onlyCoordinates]\n );\n\n const Comp = (\n <>\n <StyledLocationInput\n id={id}\n info={info}\n data-testid={testIds.control}\n placeholder={t('location_input_placeholder')}\n menu={\n filterValue\n ? {\n items: placePredictionMenuItems.concat([\n {\n id: createUID(),\n primary: t('use_input_value', [filterValue]),\n onClick: () => {\n setFilterValue('');\n onSelect?.({ name: filterValue });\n }\n }\n ]),\n emptyText: t('location_not_found_text'),\n mode: 'action',\n footer: !map && (\n <Flex container={{ justify: 'end' }}>\n <PoweredByGoogleImage />\n </Flex>\n )\n }\n : undefined\n }\n actions={\n !disabled &&\n !readOnly && (\n <CurrentLocationButton\n onError={onError}\n onResolve={resolved => {\n if (onlyCoordinates) {\n onSelect?.({ latitude: resolved.latitude, longitude: resolved.longitude });\n } else {\n onSelect?.(resolved);\n }\n }}\n />\n )\n }\n onChange={onInputChange}\n onBlur={() => {\n setFilterValue('');\n onBlur?.(value);\n }}\n value={value}\n required={required}\n disabled={disabled}\n readOnly={readOnly}\n status={status}\n {...restProps}\n />\n {map && (\n <StyledLocationMap>\n <LocationView\n {...map}\n pins={map.location ? [{ ...map.location }] : []}\n onClick={onMapClick}\n onError={onError}\n disabled={disabled}\n loading={mapLoading}\n centerMapOnChange\n />\n </StyledLocationMap>\n )}\n </>\n );\n\n return label ? (\n <FormField\n testId={testIds}\n label={label}\n labelHidden={labelHidden}\n id={id}\n info={info}\n readOnly={readOnly}\n status={status}\n ref={ref}\n required={required}\n disabled={disabled}\n additionalInfo={additionalInfo}\n >\n {Comp}\n </FormField>\n ) : (\n Comp\n );\n});\n\nexport default withTestIds(LocationInput, getLocationInputTestIds);\n"]}
1
+ {"version":3,"file":"LocationInput.js","sourceRoot":"","sources":["../../../src/components/Location/LocationInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAA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MAAM,EACd,GAAG,EAAE,GAAG,EACR,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,QAAQ,EAClB,cAAc,EAAE,cAAc,YAE7B,IAAI,GACK,CACb,CAAC,CAAC,CAAC,CACF,IAAI,CACL,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,eAAe,WAAW,CAAC,aAAa,EAAE,uBAAuB,CAAC,CAAC","sourcesContent":["import { forwardRef, useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport type { ChangeEvent, FC, PropsWithoutRef, Ref } from 'react';\nimport styled from 'styled-components';\n\nimport ComboBox from '../ComboBox';\nimport type { MenuItemProps, MenuProps } from '../Menu';\nimport { useI18n, useTestIds, useUID } from '../../hooks';\nimport { createUID, withTestIds } from '../../utils';\nimport FormField from '../FormField';\nimport type { FormControlProps } from '../FormControl';\nimport type { BaseProps, ForwardProps, TestIdProp } from '../../types';\nimport Flex from '../Flex';\nimport { defaultThemeProp } from '../../theme';\n\nimport PoweredByGoogleImage from './PoweredByGoogleImage';\nimport CurrentLocationButton from './CurrentLocationButton';\nimport MapsContext from './MapsContext';\nimport {\n getAddress,\n getCoords,\n getNavigatorPosition,\n getPlaceById,\n getPlacePredictions,\n isValueACoordinate,\n loadMapsAPI\n} from './utils';\nimport type { Bias, LatLng } from './Location.types';\nimport LocationView, { StyledLocationView } from './LocationView';\nimport type { LocationViewProps } from './LocationView';\nimport { getLocationInputTestIds } from './Location.test-ids';\n\n// Session token timeout in milliseconds for single user interaction.\nconst sessionTokenTimeout = 120_000;\n\nexport interface LocationInputProps extends BaseProps, FormControlProps, TestIdProp {\n /**\n * Get user current location on component first render.\n * @default false\n */\n defaultToCurrentLocation?: boolean;\n /** The value of the location field. */\n value?: string;\n /**\n * Callback fired on every change of the location input.\n * The argument passed back is the component's value prop.\n */\n onChange?: (value: string) => void;\n /**\n * Callback fired when the control's input loses focus.\n * The argument passed back is the component's value prop.\n */\n onBlur?: (value: string) => void;\n /** Callback fired when user chooses location from the dropdown of suggestions or submits input value. */\n onSelect?: (value: {\n name?: string;\n address?: string;\n latitude?: number;\n longitude?: number;\n }) => void;\n /**\n * Only select coordinates on map clicks.\n * @default false\n */\n onlyCoordinates?: boolean;\n /** Biasing query results towards user location/preference. */\n bias?: Bias;\n /**\n * Set to true renders the map view below input.\n * @default false\n */\n map?: {\n /** Location coordinates used for the map view. */\n location?: LatLng;\n height: LocationViewProps['height'];\n zoomLevel?: LocationViewProps['zoomLevel'];\n onClick?: LocationViewProps['onClick'];\n };\n /** Callback fired when an error occurs. This function gets called with one argument of type Error. */\n onError?: (error: Error) => void;\n}\n\nconst StyledLocationInput = styled(ComboBox)`\n z-index: 1;\n`;\n\nStyledLocationInput.defaultProps = defaultThemeProp;\n\nconst StyledLocationMap = styled.div`\n ${StyledLocationView} {\n border-top-left-radius: 0;\n border-top-right-radius: 0;\n }\n`;\n\nStyledLocationMap.defaultProps = defaultThemeProp;\n\nconst LocationInput: FC<LocationInputProps & ForwardProps> = forwardRef(function LocationInput(\n props: PropsWithoutRef<LocationInputProps>,\n ref: Ref<HTMLInputElement>\n) {\n const uid = useUID();\n const {\n testId,\n label,\n labelHidden,\n id = uid,\n value = '',\n info,\n status,\n required,\n readOnly,\n disabled,\n additionalInfo,\n onSelect,\n onError,\n onChange,\n onBlur,\n bias,\n defaultToCurrentLocation,\n onlyCoordinates = false,\n map,\n ...restProps\n } = props;\n\n const testIds = useTestIds(testId, getLocationInputTestIds);\n\n const { name, ...providerOpts } = useContext(MapsContext);\n const t = useI18n();\n const [placePredictionMenuItems, setPlacePredictionMenuItems] = useState<MenuProps['items']>([]);\n const [filterValue, setFilterValue] = useState('');\n const [debouncedFilterValue, setDebouncedFilterValue] = useState('');\n const [mapLoading, setMapLoading] = useState(false);\n const sessionTokenRef = useRef<google.maps.places.AutocompleteSessionToken | undefined>();\n const interactionTimerRef = useRef<number | undefined>();\n\n const clearInteractionTimer = useCallback(() => {\n if (interactionTimerRef.current !== undefined) {\n window.clearTimeout(interactionTimerRef.current);\n interactionTimerRef.current = undefined;\n }\n }, []);\n\n const startInteractionTimer = useCallback(() => {\n if (interactionTimerRef.current !== undefined) return;\n interactionTimerRef.current = window.setTimeout(() => {\n sessionTokenRef.current = undefined;\n interactionTimerRef.current = undefined;\n }, sessionTokenTimeout);\n }, []);\n\n useEffect(() => clearInteractionTimer, [clearInteractionTimer]);\n\n const getSessionToken = useCallback(() => sessionTokenRef.current, []);\n\n useEffect(() => {\n (async () => {\n if (defaultToCurrentLocation) {\n setMapLoading(true);\n await loadMapsAPI(name, providerOpts);\n const navigatorPosition = await getNavigatorPosition();\n const currentLocationAddress = await getAddress(navigatorPosition);\n setMapLoading(false);\n onSelect?.(currentLocationAddress);\n }\n })();\n }, []);\n\n useEffect(() => {\n if (!filterValue) {\n setDebouncedFilterValue('');\n return;\n }\n const timer = window.setTimeout(() => setDebouncedFilterValue(filterValue), 500);\n return () => window.clearTimeout(timer);\n }, [filterValue]);\n\n useEffect(() => {\n let isCurrent = true;\n\n (async () => {\n try {\n await loadMapsAPI(name, providerOpts);\n\n if (debouncedFilterValue) {\n if (onlyCoordinates) {\n const { latitude, longitude } = await getCoords(debouncedFilterValue);\n if (!isCurrent) return;\n setPlacePredictionMenuItems([\n {\n primary: t('exact_location'),\n secondary: [`${latitude}, ${longitude}`],\n id: createUID(),\n onClick: () => {\n setFilterValue('');\n onSelect?.({ latitude, longitude });\n }\n }\n ]);\n } else {\n if (isValueACoordinate(debouncedFilterValue)) {\n const { latitude, longitude } = await getCoords(debouncedFilterValue);\n const { name: addressName, address } = await getAddress({\n latitude,\n longitude\n });\n if (!isCurrent) return;\n const menuItems = [\n {\n primary: t('exact_location'),\n secondary: [`${latitude}, ${longitude}`],\n id: createUID(),\n onClick: () => {\n setFilterValue('');\n onSelect?.({\n latitude,\n longitude\n });\n }\n },\n {\n primary: addressName,\n secondary: [address],\n id: createUID(),\n onClick: () => {\n setFilterValue('');\n onSelect?.({ name: addressName, address, latitude, longitude });\n }\n }\n ];\n\n setPlacePredictionMenuItems(menuItems);\n return;\n }\n if (!sessionTokenRef.current) {\n sessionTokenRef.current = new google.maps.places.AutocompleteSessionToken();\n }\n const activeToken = sessionTokenRef.current;\n const { placePredictions } = await getPlacePredictions(\n debouncedFilterValue,\n bias,\n activeToken\n );\n if (!isCurrent) return;\n startInteractionTimer();\n\n setPlacePredictionMenuItems(\n placePredictions.map(item => ({\n id: item.place_id,\n primary: item.structured_formatting.main_text,\n secondary: [item.structured_formatting.secondary_text],\n onClick: (menuItemId: MenuItemProps['id']) => {\n getPlaceById(menuItemId, activeToken).then(\n menuItemLocation => {\n sessionTokenRef.current = undefined;\n clearInteractionTimer();\n setFilterValue('');\n onSelect?.(menuItemLocation);\n },\n e => {\n sessionTokenRef.current = undefined;\n clearInteractionTimer();\n setFilterValue('');\n onError?.(e instanceof Error ? e : new Error(String(e)));\n }\n );\n }\n }))\n );\n }\n } else {\n setPlacePredictionMenuItems([]);\n }\n } catch (e: any) {\n if (!isCurrent) return;\n setPlacePredictionMenuItems([]);\n onError?.(e);\n }\n })();\n\n return () => {\n isCurrent = false;\n };\n }, [debouncedFilterValue, bias, onError, onSelect, onlyCoordinates]);\n\n const onInputChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n setFilterValue(e.target.value.trim());\n onChange?.(e.target.value);\n },\n [onChange]\n );\n\n const onMapClick = useCallback(\n (placeInfo: { latitude: number; longitude: number; name?: string; address?: string }) => {\n if (readOnly) return;\n\n sessionTokenRef.current = undefined;\n clearInteractionTimer();\n\n if (onlyCoordinates) {\n const coords = {\n latitude: placeInfo.latitude,\n longitude: placeInfo.longitude\n };\n onSelect?.(coords);\n map?.onClick?.(coords);\n } else {\n onSelect?.(placeInfo);\n map?.onClick?.(placeInfo);\n }\n },\n [readOnly, onSelect, map?.onClick, onlyCoordinates]\n );\n\n const Comp = (\n <>\n <StyledLocationInput\n id={id}\n info={info}\n data-testid={testIds.control}\n placeholder={t('location_input_placeholder')}\n menu={\n filterValue\n ? {\n items: placePredictionMenuItems.concat([\n {\n id: createUID(),\n primary: t('use_input_value', [filterValue]),\n onClick: () => {\n setFilterValue('');\n onSelect?.({ name: filterValue });\n }\n }\n ]),\n emptyText: t('location_not_found_text'),\n mode: 'action',\n footer: !map && (\n <Flex container={{ justify: 'end' }}>\n <PoweredByGoogleImage />\n </Flex>\n )\n }\n : undefined\n }\n actions={\n !disabled &&\n !readOnly && (\n <CurrentLocationButton\n onError={onError}\n onResolve={resolved => {\n if (onlyCoordinates) {\n onSelect?.({ latitude: resolved.latitude, longitude: resolved.longitude });\n } else {\n onSelect?.(resolved);\n }\n }}\n />\n )\n }\n onChange={onInputChange}\n onBlur={() => {\n setFilterValue('');\n onBlur?.(value);\n }}\n value={value}\n required={required}\n disabled={disabled}\n readOnly={readOnly}\n status={status}\n {...restProps}\n />\n {map && (\n <StyledLocationMap>\n <LocationView\n {...map}\n pins={map.location ? [{ ...map.location }] : []}\n onClick={onMapClick}\n onError={onError}\n disabled={disabled}\n loading={mapLoading}\n centerMapOnChange\n getSessionToken={getSessionToken}\n />\n </StyledLocationMap>\n )}\n </>\n );\n\n return label ? (\n <FormField\n testId={testIds}\n label={label}\n labelHidden={labelHidden}\n id={id}\n info={info}\n readOnly={readOnly}\n status={status}\n ref={ref}\n required={required}\n disabled={disabled}\n additionalInfo={additionalInfo}\n >\n {Comp}\n </FormField>\n ) : (\n Comp\n );\n});\n\nexport default withTestIds(LocationInput, getLocationInputTestIds);\n"]}
@@ -1,3 +1,4 @@
1
+ /// <reference types="google.maps" />
1
2
  import type { WithAttributes } from '../../types';
2
3
  import type { LatLng, Pin } from './Location.types';
3
4
  export declare const StyledLocationError: import("styled-components").StyledComponent<import("react").ForwardRefExoticComponent<Omit<import("../Badges").StatusProps, "ref"> & import("react").RefAttributes<HTMLSpanElement>> & {
@@ -48,6 +49,8 @@ export type LocationViewProps = WithAttributes<'div', {
48
49
  drawRoute?: boolean;
49
50
  /** Callback fired when an error occurs. This function gets called with one argument of type Error. */
50
51
  onError?: (error: Error) => void;
52
+ /** Function that returns the current autocomplete session token. */
53
+ getSessionToken?: () => google.maps.places.AutocompleteSessionToken | undefined;
51
54
  }>;
52
55
  declare const LocationView: import("react").ForwardRefExoticComponent<Omit<LocationViewProps, "ref"> & import("react").RefAttributes<HTMLDivElement>>;
53
56
  export default LocationView;
@@ -1 +1 @@
1
- {"version":3,"file":"LocationView.d.ts","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,aAAa,CAAC;AAQ9D,OAAO,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAIpD,eAAO,MAAM,mBAAmB;;uDAK/B,CAAC;AAIF,eAAO,MAAM,kBAAkB;;SAY9B,CAAC;AAgCF,MAAM,MAAM,iBAAiB,GAAG,cAAc,CAC5C,KAAK,EACL;IACE;;;OAGG;IACH,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACb;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,+IAA+I;IAC/I,OAAO,CAAC,EAAE,CACR,YAAY,EAAE,MAAM,GAAG;QACrB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,KACE,IAAI,CAAC;IACV;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,sGAAsG;IACtG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC,CACF,CAAC;AAeF,QAAA,MAAM,YAAY,2HA4LjB,CAAC;AAEF,eAAe,YAAY,CAAC"}
1
+ {"version":3,"file":"LocationView.d.ts","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":";AAIA,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,aAAa,CAAC;AAQ9D,OAAO,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAIpD,eAAO,MAAM,mBAAmB;;uDAK/B,CAAC;AAIF,eAAO,MAAM,kBAAkB;;SAY9B,CAAC;AAgCF,MAAM,MAAM,iBAAiB,GAAG,cAAc,CAC5C,KAAK,EACL;IACE;;;OAGG;IACH,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACb;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,+IAA+I;IAC/I,OAAO,CAAC,EAAE,CACR,YAAY,EAAE,MAAM,GAAG;QACrB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,KACE,IAAI,CAAC;IACV;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,sGAAsG;IACtG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,GAAG,SAAS,CAAC;CACjF,CACF,CAAC;AAeF,QAAA,MAAM,YAAY,2HA6LjB,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -55,7 +55,7 @@ const hasPlaceId = (obj) => {
55
55
  /* cSpell:ignore 'ABCDEFGHIJKLMNOPQRSTUVWYZ' */
56
56
  const markerLabels = 'ABCDEFGHIJKLMNOPQRSTUVWYZ';
57
57
  const LocationView = forwardRef(function LocationView(props, ref) {
58
- const { pins = [], zoomLevel = 13, height = '25rem', centerMapOnChange = false, onClick, onError, disabled = false, loading = false, drawRoute = false, ...restProps } = props;
58
+ const { pins = [], zoomLevel = 13, height = '25rem', centerMapOnChange = false, onClick, onError, disabled = false, loading = false, drawRoute = false, getSessionToken, ...restProps } = props;
59
59
  const { name, ...providerOpts } = useContext(MapsContext);
60
60
  const [status, setStatus] = useState(LoadStatus.Init);
61
61
  const [eMessage, setEMessage] = useState('');
@@ -69,7 +69,7 @@ const LocationView = forwardRef(function LocationView(props, ref) {
69
69
  if (!isLatLngObject(e.latLng))
70
70
  return;
71
71
  if (hasPlaceId(e)) {
72
- getPlaceById(e.placeId).then(placeInfo => {
72
+ getPlaceById(e.placeId, getSessionToken?.()).then(placeInfo => {
73
73
  onClick?.({
74
74
  ...placeInfo,
75
75
  latitude: e.latLng.lat(),
@@ -106,7 +106,7 @@ const LocationView = forwardRef(function LocationView(props, ref) {
106
106
  return;
107
107
  const l = map.current.addListener('click', onMapClick);
108
108
  return () => google.maps.event.removeListener(l);
109
- }, [onClick, map.current]);
109
+ }, [onClick, map.current, getSessionToken]);
110
110
  useEffect(() => {
111
111
  let mounted = true;
112
112
  loadMapsAPI(name, providerOpts)
@@ -1 +1 @@
1
- {"version":3,"file":"LocationView.js","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAE5E,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,QAAQ,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,C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AC1C,KAAC,mBAAmB,kBAAa,QAAQ,EAAE,OAAO,EAAC,MAAM,YACtD,QAAQ,GACW,CACvB,IACkB,CACtB,CAAC;AACJ,CAAC,CACF,CAAC;AAEF,eAAe,YAAY,CAAC","sourcesContent":["import { useContext, useRef, useState, useEffect, forwardRef } from 'react';\nimport type { PropsWithoutRef, Ref } from 'react';\nimport styled, { css } from 'styled-components';\n\nimport type { RefElement, WithAttributes } from '../../types';\nimport { defaultThemeProp } from '../../theme';\nimport Progress from '../Progress';\nimport { Status } from '../Badges';\nimport { createUID } from '../../utils';\nimport useTheme from '../../hooks/useTheme';\nimport { omitProps } from '../../styles';\n\nimport type { LatLng, Pin } from './Location.types';\nimport { loadMapsAPI, toGoogleLatLng, getPlaceById, isLatLngObject, getAddress } from './utils';\nimport MapsContext from './MapsContext';\n\nexport const StyledLocationError = styled(Status)`\n position: absolute;\n top: 40%;\n left: 50%;\n transform: translate(-50%, -50%);\n`;\n\nStyledLocationError.defaultProps = defaultThemeProp;\n\nexport const StyledLocationView = styled.div.withConfig<{ height?: string }>(omitProps('height'))(\n ({ height, theme }) => {\n return css`\n min-height: inherit;\n height: ${height};\n position: relative;\n flex: auto;\n border-radius: ${theme.base['border-radius']};\n mask-image: radial-gradient(white, black);\n -webkit-mask-image: radial-gradient(white, black);\n `;\n }\n);\n\nStyledLocationView.defaultProps = defaultThemeProp;\n\nconst StyledMap = styled.div<{\n status: string;\n disabled: boolean;\n}>(\n ({\n disabled,\n status,\n theme: {\n base: { 'disabled-opacity': disabledOpacity }\n }\n }) => {\n return css`\n position: absolute;\n inset: 0;\n ${disabled &&\n css`\n opacity: ${disabledOpacity};\n `}\n ${status === 'error' &&\n css`\n opacity: ${disabledOpacity};\n `}\n `;\n }\n);\n\nStyledMap.defaultProps = defaultThemeProp;\n\nexport type LocationViewProps = WithAttributes<\n 'div',\n {\n /**\n * Array of location objects.\n * @default []\n */\n pins?: Pin[];\n /**\n * Set to true to always center the map when the selected location changes. Toggling this from false to true will re-center map on the last pinned location.\n * @default false\n */\n centerMapOnChange?: boolean;\n /**\n * Height of the map container.\n * @default '25rem'\n */\n height?: string;\n /**\n * How much the map should zoom.\n * @default 13\n */\n zoomLevel?: number;\n /** Callback fired when user clicks on a location on the map. This function will be passed the coordinates of the location that was clicked. */\n onClick?: (\n locationData: LatLng & {\n name?: string;\n address?: string;\n }\n ) => void;\n /**\n * Renders loading indicator when true. Informs the user location resolution is in progress.\n */\n loading?: boolean;\n /**\n * Disables dragging and clicking when true.\n * @default false\n */\n disabled?: boolean;\n /**\n * Indicates if route between pins should be rendered.\n * @default false\n */\n drawRoute?: boolean;\n\n /** Callback fired when an error occurs. This function gets called with one argument of type Error. */\n onError?: (error: Error) => void;\n }\n>;\n\nenum LoadStatus {\n Init = 'init',\n Ready = 'ready',\n Error = 'error'\n}\n\nconst hasPlaceId = (obj: any): obj is google.maps.IconMouseEvent & { placeId: string } => {\n return typeof obj === 'object' && obj.placeId && typeof obj.placeId === 'string';\n};\n\n/* cSpell:ignore 'ABCDEFGHIJKLMNOPQRSTUVWYZ' */\nconst markerLabels = 'ABCDEFGHIJKLMNOPQRSTUVWYZ';\n\nconst LocationView = forwardRef<RefElement<LocationViewProps>, PropsWithoutRef<LocationViewProps>>(\n function LocationView(props, ref) {\n const {\n pins = [],\n zoomLevel = 13,\n height = '25rem',\n centerMapOnChange = false,\n onClick,\n onError,\n disabled = false,\n loading = false,\n drawRoute = false,\n ...restProps\n } = props;\n const { name, ...providerOpts } = useContext(MapsContext);\n const [status, setStatus] = useState<LoadStatus>(LoadStatus.Init);\n const [eMessage, setEMessage] = useState('');\n const mapElemRef = useRef<HTMLDivElement>();\n const map = useRef<google.maps.Map>();\n const markers = useRef<google.maps.marker.AdvancedMarkerElement[]>([]);\n const ds = useRef<google.maps.DirectionsService>();\n const dr = useRef<google.maps.DirectionsRenderer>();\n const theme = useTheme();\n\n const onMapClick = (e: google.maps.MapMouseEvent) => {\n if (!isLatLngObject(e.latLng)) return;\n\n if (hasPlaceId(e)) {\n getPlaceById(e.placeId).then(placeInfo => {\n onClick?.({\n ...placeInfo,\n latitude: e.latLng!.lat(),\n longitude: e.latLng!.lng()\n });\n });\n } else {\n getAddress({\n latitude: e.latLng.lat(),\n longitude: e.latLng.lng()\n })\n .then(onClick)\n .catch(err => onError?.(err));\n }\n };\n\n const initialize = () => {\n if (mapElemRef.current) {\n const position = toGoogleLatLng({ latitude: 0, longitude: 0 });\n map.current = new google.maps.Map(mapElemRef.current, {\n mapId: createUID(),\n center: position,\n zoom: 2,\n draggable: !disabled,\n draggableCursor: 'auto',\n draggingCursor: 'move'\n });\n ds.current = new google.maps.DirectionsService();\n dr.current = new google.maps.DirectionsRenderer({ suppressMarkers: true });\n }\n };\n\n useEffect(() => {\n if (!onClick || !map.current) return;\n\n const l = map.current.addListener('click', onMapClick);\n return () => google.maps.event.removeListener(l);\n }, [onClick, map.current]);\n\n useEffect(() => {\n let mounted = true;\n loadMapsAPI(name, providerOpts)\n .then(() => {\n if (mounted) {\n initialize();\n setStatus(LoadStatus.Ready);\n }\n })\n .catch((error: Error) => {\n setStatus(LoadStatus.Error);\n setEMessage(error.message);\n onError?.(error);\n });\n\n return () => {\n mounted = false;\n if (map.current) google.maps.event.clearInstanceListeners(map.current);\n };\n }, []);\n\n useEffect(() => {\n if (\n status !== LoadStatus.Ready ||\n !map.current ||\n !dr.current ||\n !ds.current ||\n // FIXME: Workaround for marker library not being imported\n !google.maps.marker\n )\n return;\n\n if (drawRoute && pins.length > 1) {\n dr.current.setMap(map.current);\n const request: google.maps.DirectionsRequest = {\n origin: toGoogleLatLng({ latitude: pins[0].latitude, longitude: pins[0].longitude }),\n destination: toGoogleLatLng({\n latitude: pins[pins.length - 1].latitude,\n longitude: pins[pins.length - 1].longitude\n }),\n waypoints: pins.slice(1, pins.length - 1).map(l => {\n return {\n stopover: true,\n location: toGoogleLatLng({\n latitude: l.latitude,\n longitude: l.longitude\n })\n };\n }),\n travelMode: google.maps.TravelMode.DRIVING\n };\n\n ds.current.route(request).then(dr.current.setDirections.bind(dr.current), onError);\n }\n\n const bounds = new google.maps.LatLngBounds();\n\n markers.current = pins.map(({ latitude, longitude, title, selected }, index) => {\n const gCoords = toGoogleLatLng({ latitude, longitude });\n\n const contentConfig: google.maps.marker.PinElementOptions = {\n glyphColor: theme.base.colors.white\n };\n if (pins.length > 1) {\n const glyphWrapper = document.createElement('span');\n glyphWrapper.style.fontSize = '0.9rem';\n glyphWrapper.style.paddingTop = '0.1rem';\n glyphWrapper.innerHTML = markerLabels[index % markerLabels.length];\n contentConfig.glyph = glyphWrapper;\n }\n if (selected) {\n contentConfig.background = theme.base.colors.red.dark;\n contentConfig.borderColor = theme.base.colors.red.dark;\n contentConfig.scale = 1.15;\n }\n const content = new google.maps.marker.PinElement(contentConfig);\n const marker = new google.maps.marker.AdvancedMarkerElement({\n map: map.current,\n position: gCoords,\n title,\n content: content.element\n });\n bounds.extend(gCoords);\n return marker;\n });\n\n if (centerMapOnChange) {\n if (pins.length === 1) {\n map.current.setCenter(toGoogleLatLng(pins[0]));\n map.current.setZoom(zoomLevel);\n } else if (pins.length > 1) {\n map.current.fitBounds(bounds);\n }\n }\n\n return () => {\n markers.current.forEach(m => {\n m.map = null;\n });\n dr.current?.setMap(null);\n };\n }, [JSON.stringify(pins), status, zoomLevel, disabled, drawRoute, centerMapOnChange, onError]);\n\n return (\n <StyledLocationView height={height} ref={ref}>\n <StyledMap\n ref={mapElemRef as Ref<HTMLDivElement>}\n disabled={disabled}\n status={status}\n {...restProps}\n />\n {(status === LoadStatus.Init || loading) && <Progress placement='local' />}\n {status === LoadStatus.Error && eMessage && (\n <StyledLocationError aria-label={eMessage} variant='info'>\n {eMessage}\n </StyledLocationError>\n )}\n </StyledLocationView>\n );\n }\n);\n\nexport default LocationView;\n"]}
1
+ {"version":3,"file":"LocationView.js","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,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M,EAAE,GAAG,EAAE,GAAG,aAC1C,KAAC,SAAS,IACR,GAAG,EAAE,UAAiC,EACtC,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,MAAM,KACV,SAAS,GACb,EACD,CAAC,MAAM,KAAK,UAAU,CAAC,IAAI,IAAI,OAAO,CAAC,IAAI,KAAC,QAAQ,IAAC,SAAS,EAAC,OAAO,GAAG,EACzE,MAAM,KAAK,UAAU,CAAC,KAAK,IAAI,QAAQ,IAAI,CAC1C,KAAC,mBAAmB,kBAAa,QAAQ,EAAE,OAAO,EAAC,MAAM,YACtD,QAAQ,GACW,CACvB,IACkB,CACtB,CAAC;AACJ,CAAC,CACF,CAAC;AAEF,eAAe,YAAY,CAAC","sourcesContent":["import { useContext, useRef, useState, useEffect, forwardRef } from 'react';\nimport type { PropsWithoutRef, Ref } from 'react';\nimport styled, { css } from 'styled-components';\n\nimport type { RefElement, WithAttributes } from '../../types';\nimport { defaultThemeProp } from '../../theme';\nimport Progress from '../Progress';\nimport { Status } from '../Badges';\nimport { createUID } from '../../utils';\nimport useTheme from '../../hooks/useTheme';\nimport { omitProps } from '../../styles';\n\nimport type { LatLng, Pin } from './Location.types';\nimport { loadMapsAPI, toGoogleLatLng, getPlaceById, isLatLngObject, getAddress } from './utils';\nimport MapsContext from './MapsContext';\n\nexport const StyledLocationError = styled(Status)`\n position: absolute;\n top: 40%;\n left: 50%;\n transform: translate(-50%, -50%);\n`;\n\nStyledLocationError.defaultProps = defaultThemeProp;\n\nexport const StyledLocationView = styled.div.withConfig<{ height?: string }>(omitProps('height'))(\n ({ height, theme }) => {\n return css`\n min-height: inherit;\n height: ${height};\n position: relative;\n flex: auto;\n border-radius: ${theme.base['border-radius']};\n mask-image: radial-gradient(white, black);\n -webkit-mask-image: radial-gradient(white, black);\n `;\n }\n);\n\nStyledLocationView.defaultProps = defaultThemeProp;\n\nconst StyledMap = styled.div<{\n status: string;\n disabled: boolean;\n}>(\n ({\n disabled,\n status,\n theme: {\n base: { 'disabled-opacity': disabledOpacity }\n }\n }) => {\n return css`\n position: absolute;\n inset: 0;\n ${disabled &&\n css`\n opacity: ${disabledOpacity};\n `}\n ${status === 'error' &&\n css`\n opacity: ${disabledOpacity};\n `}\n `;\n }\n);\n\nStyledMap.defaultProps = defaultThemeProp;\n\nexport type LocationViewProps = WithAttributes<\n 'div',\n {\n /**\n * Array of location objects.\n * @default []\n */\n pins?: Pin[];\n /**\n * Set to true to always center the map when the selected location changes. Toggling this from false to true will re-center map on the last pinned location.\n * @default false\n */\n centerMapOnChange?: boolean;\n /**\n * Height of the map container.\n * @default '25rem'\n */\n height?: string;\n /**\n * How much the map should zoom.\n * @default 13\n */\n zoomLevel?: number;\n /** Callback fired when user clicks on a location on the map. This function will be passed the coordinates of the location that was clicked. */\n onClick?: (\n locationData: LatLng & {\n name?: string;\n address?: string;\n }\n ) => void;\n /**\n * Renders loading indicator when true. Informs the user location resolution is in progress.\n */\n loading?: boolean;\n /**\n * Disables dragging and clicking when true.\n * @default false\n */\n disabled?: boolean;\n /**\n * Indicates if route between pins should be rendered.\n * @default false\n */\n drawRoute?: boolean;\n\n /** Callback fired when an error occurs. This function gets called with one argument of type Error. */\n onError?: (error: Error) => void;\n /** Function that returns the current autocomplete session token. */\n getSessionToken?: () => google.maps.places.AutocompleteSessionToken | undefined;\n }\n>;\n\nenum LoadStatus {\n Init = 'init',\n Ready = 'ready',\n Error = 'error'\n}\n\nconst hasPlaceId = (obj: any): obj is google.maps.IconMouseEvent & { placeId: string } => {\n return typeof obj === 'object' && obj.placeId && typeof obj.placeId === 'string';\n};\n\n/* cSpell:ignore 'ABCDEFGHIJKLMNOPQRSTUVWYZ' */\nconst markerLabels = 'ABCDEFGHIJKLMNOPQRSTUVWYZ';\n\nconst LocationView = forwardRef<RefElement<LocationViewProps>, PropsWithoutRef<LocationViewProps>>(\n function LocationView(props, ref) {\n const {\n pins = [],\n zoomLevel = 13,\n height = '25rem',\n centerMapOnChange = false,\n onClick,\n onError,\n disabled = false,\n loading = false,\n drawRoute = false,\n getSessionToken,\n ...restProps\n } = props;\n const { name, ...providerOpts } = useContext(MapsContext);\n const [status, setStatus] = useState<LoadStatus>(LoadStatus.Init);\n const [eMessage, setEMessage] = useState('');\n const mapElemRef = useRef<HTMLDivElement>();\n const map = useRef<google.maps.Map>();\n const markers = useRef<google.maps.marker.AdvancedMarkerElement[]>([]);\n const ds = useRef<google.maps.DirectionsService>();\n const dr = useRef<google.maps.DirectionsRenderer>();\n const theme = useTheme();\n\n const onMapClick = (e: google.maps.MapMouseEvent) => {\n if (!isLatLngObject(e.latLng)) return;\n\n if (hasPlaceId(e)) {\n getPlaceById(e.placeId, getSessionToken?.()).then(placeInfo => {\n onClick?.({\n ...placeInfo,\n latitude: e.latLng!.lat(),\n longitude: e.latLng!.lng()\n });\n });\n } else {\n getAddress({\n latitude: e.latLng.lat(),\n longitude: e.latLng.lng()\n })\n .then(onClick)\n .catch(err => onError?.(err));\n }\n };\n\n const initialize = () => {\n if (mapElemRef.current) {\n const position = toGoogleLatLng({ latitude: 0, longitude: 0 });\n map.current = new google.maps.Map(mapElemRef.current, {\n mapId: createUID(),\n center: position,\n zoom: 2,\n draggable: !disabled,\n draggableCursor: 'auto',\n draggingCursor: 'move'\n });\n ds.current = new google.maps.DirectionsService();\n dr.current = new google.maps.DirectionsRenderer({ suppressMarkers: true });\n }\n };\n\n useEffect(() => {\n if (!onClick || !map.current) return;\n\n const l = map.current.addListener('click', onMapClick);\n return () => google.maps.event.removeListener(l);\n }, [onClick, map.current, getSessionToken]);\n\n useEffect(() => {\n let mounted = true;\n loadMapsAPI(name, providerOpts)\n .then(() => {\n if (mounted) {\n initialize();\n setStatus(LoadStatus.Ready);\n }\n })\n .catch((error: Error) => {\n setStatus(LoadStatus.Error);\n setEMessage(error.message);\n onError?.(error);\n });\n\n return () => {\n mounted = false;\n if (map.current) google.maps.event.clearInstanceListeners(map.current);\n };\n }, []);\n\n useEffect(() => {\n if (\n status !== LoadStatus.Ready ||\n !map.current ||\n !dr.current ||\n !ds.current ||\n // FIXME: Workaround for marker library not being imported\n !google.maps.marker\n )\n return;\n\n if (drawRoute && pins.length > 1) {\n dr.current.setMap(map.current);\n const request: google.maps.DirectionsRequest = {\n origin: toGoogleLatLng({ latitude: pins[0].latitude, longitude: pins[0].longitude }),\n destination: toGoogleLatLng({\n latitude: pins[pins.length - 1].latitude,\n longitude: pins[pins.length - 1].longitude\n }),\n waypoints: pins.slice(1, pins.length - 1).map(l => {\n return {\n stopover: true,\n location: toGoogleLatLng({\n latitude: l.latitude,\n longitude: l.longitude\n })\n };\n }),\n travelMode: google.maps.TravelMode.DRIVING\n };\n\n ds.current.route(request).then(dr.current.setDirections.bind(dr.current), onError);\n }\n\n const bounds = new google.maps.LatLngBounds();\n\n markers.current = pins.map(({ latitude, longitude, title, selected }, index) => {\n const gCoords = toGoogleLatLng({ latitude, longitude });\n\n const contentConfig: google.maps.marker.PinElementOptions = {\n glyphColor: theme.base.colors.white\n };\n if (pins.length > 1) {\n const glyphWrapper = document.createElement('span');\n glyphWrapper.style.fontSize = '0.9rem';\n glyphWrapper.style.paddingTop = '0.1rem';\n glyphWrapper.innerHTML = markerLabels[index % markerLabels.length];\n contentConfig.glyph = glyphWrapper;\n }\n if (selected) {\n contentConfig.background = theme.base.colors.red.dark;\n contentConfig.borderColor = theme.base.colors.red.dark;\n contentConfig.scale = 1.15;\n }\n const content = new google.maps.marker.PinElement(contentConfig);\n const marker = new google.maps.marker.AdvancedMarkerElement({\n map: map.current,\n position: gCoords,\n title,\n content: content.element\n });\n bounds.extend(gCoords);\n return marker;\n });\n\n if (centerMapOnChange) {\n if (pins.length === 1) {\n map.current.setCenter(toGoogleLatLng(pins[0]));\n map.current.setZoom(zoomLevel);\n } else if (pins.length > 1) {\n map.current.fitBounds(bounds);\n }\n }\n\n return () => {\n markers.current.forEach(m => {\n m.map = null;\n });\n dr.current?.setMap(null);\n };\n }, [JSON.stringify(pins), status, zoomLevel, disabled, drawRoute, centerMapOnChange, onError]);\n\n return (\n <StyledLocationView height={height} ref={ref}>\n <StyledMap\n ref={mapElemRef as Ref<HTMLDivElement>}\n disabled={disabled}\n status={status}\n {...restProps}\n />\n {(status === LoadStatus.Init || loading) && <Progress placement='local' />}\n {status === LoadStatus.Error && eMessage && (\n <StyledLocationError aria-label={eMessage} variant='info'>\n {eMessage}\n </StyledLocationError>\n )}\n </StyledLocationView>\n );\n }\n);\n\nexport default LocationView;\n"]}
@@ -30,14 +30,13 @@ export declare function toGoogleLatLng(coords: LatLng): google.maps.LatLng;
30
30
  /** Returns an array of place prediction objects ('place' can be an establishment, geographic location, or prominent point of interest)
31
31
  * and session token (valid for multiple queries, followed by one place selection).
32
32
  */
33
- export declare function getPlacePredictions(location: string, bias?: Bias): Promise<{
33
+ export declare function getPlacePredictions(location: string, bias?: Bias, sessionToken?: google.maps.places.AutocompleteSessionToken): Promise<{
34
34
  placePredictions: google.maps.places.AutocompletePrediction[];
35
35
  token: google.maps.places.AutocompleteSessionToken;
36
36
  }>;
37
- export declare function getPlace(location: string, mapElement?: HTMLDivElement): Promise<LatLng>;
38
37
  export declare function getPlaceById(placeId: string, sessionToken?: google.maps.places.AutocompleteSessionToken, mapElement?: HTMLDivElement): Promise<Location>;
39
38
  /** Returns coordinations for given input: either coords, address or current position. */
40
- export declare function getCoords(coords: string | 'current' | LatLng, mapElement?: HTMLDivElement): Promise<LatLng>;
39
+ export declare function getCoords(location: string | 'current' | LatLng): Promise<LatLng>;
41
40
  export declare function getAddress(coords: LatLng): Promise<{
42
41
  name: string;
43
42
  address?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/components/Location/utils.ts"],"names":[],"mappings":";AAeA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAgB,YAAY,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AA0H3F,wBAAsB,WAAW,CAAC,IAAI,GAAE,MAAW,EAAE,IAAI,CAAC,EAAE,YAAY,GAA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AAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,GACzD,OAAO,CAAC;IACT,gBAAgB,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,sBAAsB,EAAE,CAAC;IAC9D,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC;CACpD,CAAC,CA2CD;AAED,wBAAsB,YAAY,CAChC,OAAO,EAAE,MAAM,EACf,YAAY,GAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,wBAA4E,EAC7G,UAAU,GAAE,cAA8C,GACzD,OAAO,CAAC,QAAQ,CAAC,CAgBnB;AAED,yFAAyF;AACzF,wBAAsB,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAyDtF;AAED,wBAAsB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IACxD,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC,CA+BD;AAED,eAAO,MAAM,cAAc,QAAS,GAAG,8BAStC,CAAC"}
@@ -222,7 +222,7 @@ export function toGoogleLatLng(coords) {
222
222
  /** Returns an array of place prediction objects ('place' can be an establishment, geographic location, or prominent point of interest)
223
223
  * and session token (valid for multiple queries, followed by one place selection).
224
224
  */
225
- export async function getPlacePredictions(location, bias = {}) {
225
+ export async function getPlacePredictions(location, bias = {}, sessionToken) {
226
226
  const autocompleteService = new google.maps.places.AutocompleteService();
227
227
  const optionalParams = {};
228
228
  if (bias?.location) {
@@ -245,39 +245,19 @@ export async function getPlacePredictions(location, bias = {}) {
245
245
  optionalParams.bounds = new google.maps.LatLngBounds(toGoogleLatLng(sw), toGoogleLatLng(ne));
246
246
  }
247
247
  return new Promise((resolve, reject) => {
248
- const token = new google.maps.places.AutocompleteSessionToken();
248
+ const token = sessionToken ?? new google.maps.places.AutocompleteSessionToken();
249
249
  autocompleteService.getPlacePredictions({
250
250
  input: location,
251
251
  types: QUERY_TYPES,
252
252
  sessionToken: token,
253
253
  ...optionalParams
254
254
  }, (placePredictions, status) => {
255
- if (status === google.maps.places.PlacesServiceStatus.OK) {
255
+ if (status === google.maps.places.PlacesServiceStatus.OK ||
256
+ status === google.maps.places.PlacesServiceStatus.ZERO_RESULTS) {
256
257
  resolve({ placePredictions: placePredictions ?? [], token });
257
258
  }
258
259
  else {
259
- reject(new Error(LocationNotFoundError));
260
- }
261
- });
262
- });
263
- }
264
- export async function getPlace(location, mapElement = document.createElement('div')) {
265
- const placesService = new google.maps.places.PlacesService(mapElement);
266
- const { placePredictions, token } = await getPlacePredictions(location);
267
- return new Promise((resolve, reject) => {
268
- placesService.getDetails({
269
- placeId: placePredictions[0]?.place_id,
270
- fields: QUERY_FIELDS,
271
- sessionToken: token
272
- }, (place, pStatus) => {
273
- if (pStatus === google.maps.places.PlacesServiceStatus.OK) {
274
- resolve({
275
- latitude: place?.geometry?.location?.lat() || NaN,
276
- longitude: place?.geometry?.location?.lng() || NaN
277
- });
278
- }
279
- else {
280
- reject(new Error(LocationNotFoundError));
260
+ reject(new Error(`${LocationNotFoundError}: ${status}`));
281
261
  }
282
262
  });
283
263
  });
@@ -285,61 +265,81 @@ export async function getPlace(location, mapElement = document.createElement('di
285
265
  export async function getPlaceById(placeId, sessionToken = new google.maps.places.AutocompleteSessionToken(), mapElement = document.createElement('div')) {
286
266
  const placesService = new google.maps.places.PlacesService(mapElement);
287
267
  return new Promise((resolve, reject) => {
288
- placesService.getDetails({ placeId, fields: QUERY_FIELDS, sessionToken }, (place, pStatus) => {
289
- if (pStatus === google.maps.places.PlacesServiceStatus.OK) {
268
+ placesService.getDetails({ placeId, fields: QUERY_FIELDS, sessionToken }, (place, status) => {
269
+ if (status === google.maps.places.PlacesServiceStatus.OK) {
290
270
  resolve({
291
271
  name: place?.name,
292
272
  address: place?.formatted_address,
293
- latitude: place?.geometry?.location?.lat() || NaN,
294
- longitude: place?.geometry?.location?.lng() || NaN
273
+ latitude: place?.geometry?.location?.lat() ?? NaN,
274
+ longitude: place?.geometry?.location?.lng() ?? NaN
295
275
  });
296
276
  }
297
277
  else {
298
- reject(new Error(LocationNotFoundError));
278
+ reject(new Error(`${LocationNotFoundError}: ${status}`));
299
279
  }
300
280
  });
301
281
  });
302
282
  }
303
283
  /** Returns coordinations for given input: either coords, address or current position. */
304
- export async function getCoords(coords, mapElement) {
305
- if (coords === '' || coords === undefined)
284
+ export async function getCoords(location) {
285
+ if (location === '' || location === undefined)
306
286
  throw new Error();
307
- if (coords === 'current')
287
+ if (location === 'current')
308
288
  return getNavigatorPosition();
309
- let location;
310
- if (typeof coords === 'string') {
289
+ let coords;
290
+ if (typeof location === 'string') {
311
291
  let latLng = [];
312
- if (isValueDMSCoordinate(coords) ||
313
- isValueDMCoordinate(coords) ||
314
- isValueDegreeFormatCoordinate(coords)) {
315
- latLng = parseDMS(coords);
292
+ if (isValueDMSCoordinate(location) ||
293
+ isValueDMCoordinate(location) ||
294
+ isValueDegreeFormatCoordinate(location)) {
295
+ latLng = parseDMS(location);
316
296
  }
317
297
  else {
318
298
  let splitter;
319
- if (coords.includes(', ')) {
299
+ if (location.includes(', ')) {
320
300
  splitter = ', ';
321
301
  }
322
- else if (coords.includes(',')) {
302
+ else if (location.includes(',')) {
323
303
  splitter = ',';
324
304
  }
325
- else if (coords.includes(' ')) {
305
+ else if (location.includes(' ')) {
326
306
  splitter = ' ';
327
307
  }
328
308
  else {
329
309
  splitter = ', ';
330
310
  }
331
- latLng = coords.split(splitter).map(Number);
311
+ latLng = location.split(splitter).map(Number);
332
312
  }
333
313
  const [lat, lng] = latLng;
334
- if (Number.isNaN(lat) || Number.isNaN(lng) || lat === undefined || lng === undefined)
335
- return getPlace(coords, mapElement);
336
- location = { latitude: lat, longitude: lng };
314
+ if (Number.isNaN(lat) || Number.isNaN(lng) || lat === undefined || lng === undefined) {
315
+ const geocoder = new google.maps.Geocoder();
316
+ return new Promise((resolve, reject) => {
317
+ geocoder.geocode({ address: location }, (results, status) => {
318
+ if (status === 'OK') {
319
+ const [result] = results ?? [];
320
+ if (result?.geometry?.location) {
321
+ resolve({
322
+ latitude: result.geometry.location.lat(),
323
+ longitude: result.geometry.location.lng()
324
+ });
325
+ }
326
+ else {
327
+ resolve({ latitude: NaN, longitude: NaN });
328
+ }
329
+ }
330
+ else {
331
+ reject(new Error(`${GeocoderFailedError}: ${status}`));
332
+ }
333
+ });
334
+ });
335
+ }
336
+ coords = { latitude: lat, longitude: lng };
337
337
  }
338
338
  else {
339
- location = coords;
339
+ coords = location;
340
340
  }
341
- if (Number.isFinite(location.latitude) && Number.isFinite(location.longitude))
342
- return location;
341
+ if (Number.isFinite(coords.latitude) && Number.isFinite(coords.longitude))
342
+ return coords;
343
343
  throw new Error(CoordsCannotBeParsedError);
344
344
  }
345
345
  export async function getAddress(coords) {
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/components/Location/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AAEnD,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,OAAO,EACL,yBAAyB,EACzB,mBAAmB,EACnB,2BAA2B,EAC3B,0BAA0B,EAC1B,kBAAkB,EAClB,qBAAqB,EACrB,yBAAyB,EACzB,YAAY,EACZ,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAG1B,MAAM,iBAAiB,GAAG;IACxB,QAAQ;IACR,mBAAmB;IACnB,gCAAgC;IAChC,KAAK;IACL,qBAAqB;IACrB,QAAQ;IACR,2CAA2C;IAC3C,YAAY;IACZ,OAAO;IACP,oBAAoB;IACpB,6CAA6C;IAC7C,KAAK;IACL,sBAAsB;IACtB,SAAS;CACV,CAAC;AAEF,MAAM,uBAAuB,GAAG,IAAI,MAAM,CAAC,iBA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;wBACjC,GAAG,CAAC,MAAM,CAAC,QAAQ,IAAI;4BACrB,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE;4BACxC,SAAS,EAAE,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE;yBAC1C,CAAC;qBACH,CAAC,CAAC;iBACJ;qBAAM;oBACL,OAAO,CAAC;wBACN,IAAI,EAAE,GAAG,MAAM,CAAC,QAAQ,KAAK,MAAM,CAAC,SAAS,EAAE;wBAC/C,QAAQ,EAAE,MAAM,CAAC,QAAQ;wBACzB,SAAS,EAAE,MAAM,CAAC,SAAS;qBAC5B,CAAC,CAAC;iBACJ;aACF;iBAAM;gBACL,MAAM,CAAC,IAAI,KAAK,CAAC,GAAG,mBAAmB,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC;aACxD;QACH,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,GAAQ,EAA6B,EAAE;IACpE,OAAO,CACL,CAAC,CAAC,GAAG;QACL,OAAO,GAAG,KAAK,QAAQ;QACvB,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC;QACnB,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU;QAC7B,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC;QACnB,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU,CAC9B,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { Loader } from '@googlemaps/js-api-loader';\n\nimport { hasProp } from '../../utils';\n\nimport {\n CoordsCannotBeParsedError,\n GeocoderFailedError,\n GeolocationUnsupportedError,\n GoogleMapsAPINotFoundError,\n IsNotAnObjectError,\n LocationNotFoundError,\n ProviderNotSupportedError,\n QUERY_FIELDS,\n QUERY_TYPES\n} from './Location.types';\nimport type { Bias, LatLng, MapsProvider, ProviderOpts, Location } from './Location.types';\n\nconst DegreeRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)(\\.\\d+)?°/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)(\\.\\d+)?°/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DegreeRegularExpression = new RegExp(DegreeRegexChunks.map(c => c.source).join(''));\n\nconst DMRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)°/,\n /\\s?/,\n // latitude minutes\n /([0-9]|[0-5][0-9])(\\.\\d+)?('|’)/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)°/,\n /\\s?/,\n // longitude minutes\n /([0-9]|[0-5][0-9])(\\.\\d+)?('|’)/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DMRegularExpression = new RegExp(DMRegexChunks.map(c => c.source).join(''));\nconst DMSRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)°/,\n /\\s?/,\n // latitude minutes\n /([0-9]|[0-5][0-9])('|’)/,\n /\\s?/,\n // latitude seconds\n /([0-9]|[0-5][0-9])(\\.\\d+)?(\"|″)/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)°/,\n /\\s?/,\n // longitude minutes\n /([0-9]|[0-5][0-9])('|’)/,\n /\\s?/,\n // longitude seconds\n /([0-9]|[0-5][0-9])(\\.\\d+)?(\"|″)/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DMSRegularExpression = new RegExp(DMSRegexChunks.map(c => c.source).join(''));\n\nconst decimalRegexChunks = [\n /^[-+]?/,\n /([0-9]|[1-8][0-9]|90)/,\n /(\\.\\d+)?/,\n /(,|\\s|,\\s)/,\n /[-+]?/,\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)/,\n /(\\.\\d+)?$/\n];\n\nconst decimalFormatCoordinatesRegularExpression = new RegExp(\n decimalRegexChunks.map(c => c.source).join('')\n);\n\nconst providers: {\n [key: string]: MapsProvider;\n} = {\n google: {\n name: 'Google',\n loadedPromise: null,\n loadedApiKey: '',\n loadAPI(opts) {\n const loader = new Loader({\n version: '3.55',\n apiKey: opts.apiKey,\n region: opts.region,\n language: opts.language,\n libraries: ['places', 'marker']\n });\n\n return loader.load().then(\n () => {},\n () => {\n throw new Error(GoogleMapsAPINotFoundError);\n }\n );\n }\n },\n undefined: {\n name: 'undefined',\n loadedPromise: null,\n loadedApiKey: '',\n loadAPI: data => Promise.reject(new Error(`${ProviderNotSupportedError}: ${data.name}`))\n }\n};\n\nexport async function loadMapsAPI(name: string = '', opts?: ProviderOpts): Promise<void> {\n if (typeof opts !== 'object' || !opts) {\n throw new Error(IsNotAnObjectError);\n }\n\n const provider = providers[name] ?? providers.undefined;\n\n if (!provider.loadedPromise) {\n provider.loadedPromise = provider\n .loadAPI(opts)\n .then(() => {\n provider.loadedApiKey = opts?.apiKey;\n })\n .catch(() => {\n provider.loadedPromise = null;\n });\n }\n return provider.loadedPromise;\n}\n\n/**\n * Identifies coordinates in degree format\n * eg. 45.78°N 9.11°E\n */\nexport function isValueDegreeFormatCoordinate(value: string): boolean {\n return DegreeRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in degree, minute format\n * eg. 45°45.4’N 9°23’E\n */\nexport function isValueDMCoordinate(value: string): boolean {\n return DMRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in degree, minute, second format\n * eg. 45°45’32.4″N 9°23’39.9″E\n */\nexport function isValueDMSCoordinate(value: string): boolean {\n return DMSRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in decimal format\n * eg. 14.678, -38.765\n */\nexport function isValueACoordinate(value: string): boolean {\n return (\n decimalFormatCoordinatesRegularExpression.test(value) ||\n isValueDMSCoordinate(value) ||\n isValueDMCoordinate(value) ||\n isValueDegreeFormatCoordinate(value)\n );\n}\n\ninterface DMSParts {\n degrees: number;\n minutes?: number;\n seconds?: number;\n}\n\n/**\n * Converts DMS (degree, minute, second) format latitude/longitude into decimal format.\n */\nfunction convertDMSToDD({ degrees, minutes, seconds }: DMSParts, direction?: string): number {\n let dd = degrees;\n if (minutes) {\n if (degrees > 0) dd += minutes / 60;\n if (degrees < 0) dd -= minutes / 60;\n }\n if (seconds) {\n if (degrees > 0) dd += seconds / (60 * 60);\n if (degrees < 0) dd -= seconds / (60 * 60);\n }\n\n if (degrees > 0 && (direction === 'S' || direction === 'W')) {\n dd *= -1;\n }\n\n return dd;\n}\n\n/**\n * Parses DMS (degree, minute, second) format string into decimal format coordinates.\n */\nexport function parseDMS(input: string): number[] {\n if (isValueDMSCoordinate(input)) {\n const parts = input.split(/'|’|\"\\s?|″\\s?|°|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD(\n {\n degrees: Number(parts[0]),\n minutes: Number(parts[1]),\n seconds: Number(parts[2])\n },\n parts[3]\n );\n const lng = convertDMSToDD(\n {\n degrees: Number(parts[4]),\n minutes: Number(parts[5]),\n seconds: Number(parts[6])\n },\n parts[7]\n );\n return [lat, lng];\n }\n if (isValueDMCoordinate(input)) {\n const parts = input.split(/'\\s?|’\\s?|°|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD({ degrees: Number(parts[0]), minutes: Number(parts[1]) }, parts[2]);\n const lng = convertDMSToDD({ degrees: Number(parts[3]), minutes: Number(parts[4]) }, parts[5]);\n return [lat, lng];\n }\n\n const parts = input.split(/°\\s?|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD({ degrees: Number(parts[0]) }, parts[1]);\n const lng = convertDMSToDD({ degrees: Number(parts[2]) }, parts[3]);\n return [lat, lng];\n}\n\nexport async function getNavigatorPosition(): Promise<LatLng> {\n if (!navigator.geolocation) throw new Error(GeolocationUnsupportedError);\n\n return new Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(\n currentLocation => {\n resolve({\n latitude: currentLocation.coords.latitude,\n longitude: currentLocation.coords.longitude\n });\n },\n error => reject(new Error(error.message))\n );\n });\n}\n\nexport function toGoogleLatLng(coords: LatLng): google.maps.LatLng {\n return new google.maps.LatLng(coords.latitude, coords.longitude);\n}\n\n/** Returns an array of place prediction objects ('place' can be an establishment, geographic location, or prominent point of interest)\n * and session token (valid for multiple queries, followed by one place selection).\n */\nexport async function getPlacePredictions(\n location: string,\n bias: Bias = {}\n): Promise<{\n placePredictions: google.maps.places.AutocompletePrediction[];\n token: google.maps.places.AutocompleteSessionToken;\n}> {\n const autocompleteService = new google.maps.places.AutocompleteService();\n const optionalParams: Partial<google.maps.places.AutocompletionRequest> = {};\n if (bias?.location) {\n if (bias?.location.center === 'current') {\n await getNavigatorPosition()\n .then(coords => {\n optionalParams.location = toGoogleLatLng(coords);\n optionalParams.radius = bias.location!.radius;\n })\n // no-op user didn't allow location\n .catch(() => {});\n } else {\n optionalParams.location = toGoogleLatLng(bias.location.center);\n optionalParams.radius = bias.location.radius;\n }\n }\n\n if (bias?.bounds) {\n const [sw, ne] = bias.bounds;\n optionalParams.bounds = new google.maps.LatLngBounds(toGoogleLatLng(sw), toGoogleLatLng(ne));\n }\n return new Promise((resolve, reject) => {\n const token = new google.maps.places.AutocompleteSessionToken();\n autocompleteService.getPlacePredictions(\n {\n input: location,\n types: QUERY_TYPES,\n sessionToken: token,\n ...optionalParams\n },\n (placePredictions, status) => {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n resolve({ placePredictions: placePredictions ?? [], token });\n } else {\n reject(new Error(LocationNotFoundError));\n }\n }\n );\n });\n}\n\nexport async function getPlace(\n location: string,\n mapElement: HTMLDivElement = document.createElement('div')\n): Promise<LatLng> {\n const placesService = new google.maps.places.PlacesService(mapElement);\n const { placePredictions, token } = await getPlacePredictions(location);\n return new Promise((resolve, reject) => {\n placesService.getDetails(\n {\n placeId: placePredictions[0]?.place_id,\n fields: QUERY_FIELDS,\n sessionToken: token\n },\n (place, pStatus) => {\n if (pStatus === google.maps.places.PlacesServiceStatus.OK) {\n resolve({\n latitude: place?.geometry?.location?.lat() || NaN,\n longitude: place?.geometry?.location?.lng() || NaN\n });\n } else {\n reject(new Error(LocationNotFoundError));\n }\n }\n );\n });\n}\n\nexport async function getPlaceById(\n placeId: string,\n sessionToken: google.maps.places.AutocompleteSessionToken = new google.maps.places.AutocompleteSessionToken(),\n mapElement: HTMLDivElement = document.createElement('div')\n): Promise<Location> {\n const placesService = new google.maps.places.PlacesService(mapElement);\n return new Promise((resolve, reject) => {\n placesService.getDetails({ placeId, fields: QUERY_FIELDS, sessionToken }, (place, pStatus) => {\n if (pStatus === google.maps.places.PlacesServiceStatus.OK) {\n resolve({\n name: place?.name,\n address: place?.formatted_address,\n latitude: place?.geometry?.location?.lat() || NaN,\n longitude: place?.geometry?.location?.lng() || NaN\n });\n } else {\n reject(new Error(LocationNotFoundError));\n }\n });\n });\n}\n\n/** Returns coordinations for given input: either coords, address or current position. */\nexport async function getCoords(\n coords: string | 'current' | LatLng,\n mapElement?: HTMLDivElement\n): Promise<LatLng> {\n if (coords === '' || coords === undefined) throw new Error();\n if (coords === 'current') return getNavigatorPosition();\n\n let location: LatLng;\n if (typeof coords === 'string') {\n let latLng: number[] = [];\n if (\n isValueDMSCoordinate(coords) ||\n isValueDMCoordinate(coords) ||\n isValueDegreeFormatCoordinate(coords)\n ) {\n latLng = parseDMS(coords);\n } else {\n let splitter;\n if (coords.includes(', ')) {\n splitter = ', ';\n } else if (coords.includes(',')) {\n splitter = ',';\n } else if (coords.includes(' ')) {\n splitter = ' ';\n } else {\n splitter = ', ';\n }\n\n latLng = coords.split(splitter).map(Number);\n }\n\n const [lat, lng] = latLng;\n if (Number.isNaN(lat) || Number.isNaN(lng) || lat === undefined || lng === undefined)\n return getPlace(coords, mapElement);\n location = { latitude: lat, longitude: lng };\n } else {\n location = coords;\n }\n\n if (Number.isFinite(location.latitude) && Number.isFinite(location.longitude)) return location;\n\n throw new Error(CoordsCannotBeParsedError);\n}\n\nexport async function getAddress(coords: LatLng): Promise<{\n name: string;\n address?: string;\n latitude: number;\n longitude: number;\n}> {\n const location = {\n lat: coords.latitude,\n lng: coords.longitude\n };\n const geocoder = new google.maps.Geocoder();\n return new Promise((resolve, reject) => {\n geocoder.geocode(\n { location },\n (results: google.maps.GeocoderResult[] | null, status: google.maps.GeocoderStatus) => {\n if (status === 'OK') {\n const [result] = results ?? [];\n if (result) {\n resolve({\n name: result.formatted_address,\n address: result.formatted_address,\n ...(result.geometry && {\n latitude: result.geometry.location.lat(),\n longitude: result.geometry.location.lng()\n })\n });\n } else {\n resolve({\n name: `${coords.latitude}, ${coords.longitude}`,\n latitude: coords.latitude,\n longitude: coords.longitude\n });\n }\n } else {\n reject(new Error(`${GeocoderFailedError}: ${status}`));\n }\n }\n );\n });\n}\n\nexport const isLatLngObject = (obj: any): obj is google.maps.LatLng => {\n return (\n !!obj &&\n typeof obj === 'object' &&\n hasProp(obj, 'lat') &&\n typeof obj.lat === 'function' &&\n hasProp(obj, 'lng') &&\n typeof obj.lng === 'function'\n );\n};\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/components/Location/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AAEnD,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,OAAO,EACL,yBAAyB,EACzB,mBAAmB,EACnB,2BAA2B,EAC3B,0BAA0B,EAC1B,kBAAkB,EAClB,qBAAqB,EACrB,yBAAyB,EACzB,YAAY,EACZ,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAG1B,MAAM,iBAAiB,GAAG;IACxB,QAAQ;IACR,mBAAmB;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AE;gBACnB,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,IAAI,EAAE,CAAC;gBAC/B,IAAI,MAAM,EAAE;oBACV,OAAO,CAAC;wBACN,IAAI,EAAE,MAAM,CAAC,iBAAiB;wBAC9B,OAAO,EAAE,MAAM,CAAC,iBAAiB;wBACjC,GAAG,CAAC,MAAM,CAAC,QAAQ,IAAI;4BACrB,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE;4BACxC,SAAS,EAAE,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE;yBAC1C,CAAC;qBACH,CAAC,CAAC;iBACJ;qBAAM;oBACL,OAAO,CAAC;wBACN,IAAI,EAAE,GAAG,MAAM,CAAC,QAAQ,KAAK,MAAM,CAAC,SAAS,EAAE;wBAC/C,QAAQ,EAAE,MAAM,CAAC,QAAQ;wBACzB,SAAS,EAAE,MAAM,CAAC,SAAS;qBAC5B,CAAC,CAAC;iBACJ;aACF;iBAAM;gBACL,MAAM,CAAC,IAAI,KAAK,CAAC,GAAG,mBAAmB,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC;aACxD;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,GAAQ,EAA6B,EAAE;IACpE,OAAO,CACL,CAAC,CAAC,GAAG;QACL,OAAO,GAAG,KAAK,QAAQ;QACvB,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC;QACnB,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU;QAC7B,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC;QACnB,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU,CAC9B,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { Loader } from '@googlemaps/js-api-loader';\n\nimport { hasProp } from '../../utils';\n\nimport {\n CoordsCannotBeParsedError,\n GeocoderFailedError,\n GeolocationUnsupportedError,\n GoogleMapsAPINotFoundError,\n IsNotAnObjectError,\n LocationNotFoundError,\n ProviderNotSupportedError,\n QUERY_FIELDS,\n QUERY_TYPES\n} from './Location.types';\nimport type { Bias, LatLng, MapsProvider, ProviderOpts, Location } from './Location.types';\n\nconst DegreeRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)(\\.\\d+)?°/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)(\\.\\d+)?°/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DegreeRegularExpression = new RegExp(DegreeRegexChunks.map(c => c.source).join(''));\n\nconst DMRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)°/,\n /\\s?/,\n // latitude minutes\n /([0-9]|[0-5][0-9])(\\.\\d+)?('|’)/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)°/,\n /\\s?/,\n // longitude minutes\n /([0-9]|[0-5][0-9])(\\.\\d+)?('|’)/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DMRegularExpression = new RegExp(DMRegexChunks.map(c => c.source).join(''));\nconst DMSRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)°/,\n /\\s?/,\n // latitude minutes\n /([0-9]|[0-5][0-9])('|’)/,\n /\\s?/,\n // latitude seconds\n /([0-9]|[0-5][0-9])(\\.\\d+)?(\"|″)/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)°/,\n /\\s?/,\n // longitude minutes\n /([0-9]|[0-5][0-9])('|’)/,\n /\\s?/,\n // longitude seconds\n /([0-9]|[0-5][0-9])(\\.\\d+)?(\"|″)/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DMSRegularExpression = new RegExp(DMSRegexChunks.map(c => c.source).join(''));\n\nconst decimalRegexChunks = [\n /^[-+]?/,\n /([0-9]|[1-8][0-9]|90)/,\n /(\\.\\d+)?/,\n /(,|\\s|,\\s)/,\n /[-+]?/,\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)/,\n /(\\.\\d+)?$/\n];\n\nconst decimalFormatCoordinatesRegularExpression = new RegExp(\n decimalRegexChunks.map(c => c.source).join('')\n);\n\nconst providers: {\n [key: string]: MapsProvider;\n} = {\n google: {\n name: 'Google',\n loadedPromise: null,\n loadedApiKey: '',\n loadAPI(opts) {\n const loader = new Loader({\n version: '3.55',\n apiKey: opts.apiKey,\n region: opts.region,\n language: opts.language,\n libraries: ['places', 'marker']\n });\n\n return loader.load().then(\n () => {},\n () => {\n throw new Error(GoogleMapsAPINotFoundError);\n }\n );\n }\n },\n undefined: {\n name: 'undefined',\n loadedPromise: null,\n loadedApiKey: '',\n loadAPI: data => Promise.reject(new Error(`${ProviderNotSupportedError}: ${data.name}`))\n }\n};\n\nexport async function loadMapsAPI(name: string = '', opts?: ProviderOpts): Promise<void> {\n if (typeof opts !== 'object' || !opts) {\n throw new Error(IsNotAnObjectError);\n }\n\n const provider = providers[name] ?? providers.undefined;\n\n if (!provider.loadedPromise) {\n provider.loadedPromise = provider\n .loadAPI(opts)\n .then(() => {\n provider.loadedApiKey = opts?.apiKey;\n })\n .catch(() => {\n provider.loadedPromise = null;\n });\n }\n return provider.loadedPromise;\n}\n\n/**\n * Identifies coordinates in degree format\n * eg. 45.78°N 9.11°E\n */\nexport function isValueDegreeFormatCoordinate(value: string): boolean {\n return DegreeRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in degree, minute format\n * eg. 45°45.4’N 9°23’E\n */\nexport function isValueDMCoordinate(value: string): boolean {\n return DMRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in degree, minute, second format\n * eg. 45°45’32.4″N 9°23’39.9″E\n */\nexport function isValueDMSCoordinate(value: string): boolean {\n return DMSRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in decimal format\n * eg. 14.678, -38.765\n */\nexport function isValueACoordinate(value: string): boolean {\n return (\n decimalFormatCoordinatesRegularExpression.test(value) ||\n isValueDMSCoordinate(value) ||\n isValueDMCoordinate(value) ||\n isValueDegreeFormatCoordinate(value)\n );\n}\n\ninterface DMSParts {\n degrees: number;\n minutes?: number;\n seconds?: number;\n}\n\n/**\n * Converts DMS (degree, minute, second) format latitude/longitude into decimal format.\n */\nfunction convertDMSToDD({ degrees, minutes, seconds }: DMSParts, direction?: string): number {\n let dd = degrees;\n if (minutes) {\n if (degrees > 0) dd += minutes / 60;\n if (degrees < 0) dd -= minutes / 60;\n }\n if (seconds) {\n if (degrees > 0) dd += seconds / (60 * 60);\n if (degrees < 0) dd -= seconds / (60 * 60);\n }\n\n if (degrees > 0 && (direction === 'S' || direction === 'W')) {\n dd *= -1;\n }\n\n return dd;\n}\n\n/**\n * Parses DMS (degree, minute, second) format string into decimal format coordinates.\n */\nexport function parseDMS(input: string): number[] {\n if (isValueDMSCoordinate(input)) {\n const parts = input.split(/'|’|\"\\s?|″\\s?|°|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD(\n {\n degrees: Number(parts[0]),\n minutes: Number(parts[1]),\n seconds: Number(parts[2])\n },\n parts[3]\n );\n const lng = convertDMSToDD(\n {\n degrees: Number(parts[4]),\n minutes: Number(parts[5]),\n seconds: Number(parts[6])\n },\n parts[7]\n );\n return [lat, lng];\n }\n if (isValueDMCoordinate(input)) {\n const parts = input.split(/'\\s?|’\\s?|°|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD({ degrees: Number(parts[0]), minutes: Number(parts[1]) }, parts[2]);\n const lng = convertDMSToDD({ degrees: Number(parts[3]), minutes: Number(parts[4]) }, parts[5]);\n return [lat, lng];\n }\n\n const parts = input.split(/°\\s?|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD({ degrees: Number(parts[0]) }, parts[1]);\n const lng = convertDMSToDD({ degrees: Number(parts[2]) }, parts[3]);\n return [lat, lng];\n}\n\nexport async function getNavigatorPosition(): Promise<LatLng> {\n if (!navigator.geolocation) throw new Error(GeolocationUnsupportedError);\n\n return new Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(\n currentLocation => {\n resolve({\n latitude: currentLocation.coords.latitude,\n longitude: currentLocation.coords.longitude\n });\n },\n error => reject(new Error(error.message))\n );\n });\n}\n\nexport function toGoogleLatLng(coords: LatLng): google.maps.LatLng {\n return new google.maps.LatLng(coords.latitude, coords.longitude);\n}\n\n/** Returns an array of place prediction objects ('place' can be an establishment, geographic location, or prominent point of interest)\n * and session token (valid for multiple queries, followed by one place selection).\n */\nexport async function getPlacePredictions(\n location: string,\n bias: Bias = {},\n sessionToken?: google.maps.places.AutocompleteSessionToken\n): Promise<{\n placePredictions: google.maps.places.AutocompletePrediction[];\n token: google.maps.places.AutocompleteSessionToken;\n}> {\n const autocompleteService = new google.maps.places.AutocompleteService();\n const optionalParams: Partial<google.maps.places.AutocompletionRequest> = {};\n if (bias?.location) {\n if (bias?.location.center === 'current') {\n await getNavigatorPosition()\n .then(coords => {\n optionalParams.location = toGoogleLatLng(coords);\n optionalParams.radius = bias.location!.radius;\n })\n // no-op user didn't allow location\n .catch(() => {});\n } else {\n optionalParams.location = toGoogleLatLng(bias.location.center);\n optionalParams.radius = bias.location.radius;\n }\n }\n\n if (bias?.bounds) {\n const [sw, ne] = bias.bounds;\n optionalParams.bounds = new google.maps.LatLngBounds(toGoogleLatLng(sw), toGoogleLatLng(ne));\n }\n return new Promise((resolve, reject) => {\n const token = sessionToken ?? new google.maps.places.AutocompleteSessionToken();\n autocompleteService.getPlacePredictions(\n {\n input: location,\n types: QUERY_TYPES,\n sessionToken: token,\n ...optionalParams\n },\n (placePredictions, status) => {\n if (\n status === google.maps.places.PlacesServiceStatus.OK ||\n status === google.maps.places.PlacesServiceStatus.ZERO_RESULTS\n ) {\n resolve({ placePredictions: placePredictions ?? [], token });\n } else {\n reject(new Error(`${LocationNotFoundError}: ${status}`));\n }\n }\n );\n });\n}\n\nexport async function getPlaceById(\n placeId: string,\n sessionToken: google.maps.places.AutocompleteSessionToken = new google.maps.places.AutocompleteSessionToken(),\n mapElement: HTMLDivElement = document.createElement('div')\n): Promise<Location> {\n const placesService = new google.maps.places.PlacesService(mapElement);\n return new Promise((resolve, reject) => {\n placesService.getDetails({ placeId, fields: QUERY_FIELDS, sessionToken }, (place, status) => {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n resolve({\n name: place?.name,\n address: place?.formatted_address,\n latitude: place?.geometry?.location?.lat() ?? NaN,\n longitude: place?.geometry?.location?.lng() ?? NaN\n });\n } else {\n reject(new Error(`${LocationNotFoundError}: ${status}`));\n }\n });\n });\n}\n\n/** Returns coordinations for given input: either coords, address or current position. */\nexport async function getCoords(location: string | 'current' | LatLng): Promise<LatLng> {\n if (location === '' || location === undefined) throw new Error();\n if (location === 'current') return getNavigatorPosition();\n\n let coords: LatLng;\n if (typeof location === 'string') {\n let latLng: number[] = [];\n if (\n isValueDMSCoordinate(location) ||\n isValueDMCoordinate(location) ||\n isValueDegreeFormatCoordinate(location)\n ) {\n latLng = parseDMS(location);\n } else {\n let splitter;\n if (location.includes(', ')) {\n splitter = ', ';\n } else if (location.includes(',')) {\n splitter = ',';\n } else if (location.includes(' ')) {\n splitter = ' ';\n } else {\n splitter = ', ';\n }\n\n latLng = location.split(splitter).map(Number);\n }\n\n const [lat, lng] = latLng;\n if (Number.isNaN(lat) || Number.isNaN(lng) || lat === undefined || lng === undefined) {\n const geocoder = new google.maps.Geocoder();\n return new Promise((resolve, reject) => {\n geocoder.geocode({ address: location }, (results, status) => {\n if (status === 'OK') {\n const [result] = results ?? [];\n if (result?.geometry?.location) {\n resolve({\n latitude: result.geometry.location.lat(),\n longitude: result.geometry.location.lng()\n });\n } else {\n resolve({ latitude: NaN, longitude: NaN });\n }\n } else {\n reject(new Error(`${GeocoderFailedError}: ${status}`));\n }\n });\n });\n }\n coords = { latitude: lat, longitude: lng };\n } else {\n coords = location;\n }\n\n if (Number.isFinite(coords.latitude) && Number.isFinite(coords.longitude)) return coords;\n\n throw new Error(CoordsCannotBeParsedError);\n}\n\nexport async function getAddress(coords: LatLng): Promise<{\n name: string;\n address?: string;\n latitude: number;\n longitude: number;\n}> {\n const location = {\n lat: coords.latitude,\n lng: coords.longitude\n };\n const geocoder = new google.maps.Geocoder();\n return new Promise((resolve, reject) => {\n geocoder.geocode({ location }, (results, status) => {\n if (status === 'OK') {\n const [result] = results ?? [];\n if (result) {\n resolve({\n name: result.formatted_address,\n address: result.formatted_address,\n ...(result.geometry && {\n latitude: result.geometry.location.lat(),\n longitude: result.geometry.location.lng()\n })\n });\n } else {\n resolve({\n name: `${coords.latitude}, ${coords.longitude}`,\n latitude: coords.latitude,\n longitude: coords.longitude\n });\n }\n } else {\n reject(new Error(`${GeocoderFailedError}: ${status}`));\n }\n });\n });\n}\n\nexport const isLatLngObject = (obj: any): obj is google.maps.LatLng => {\n return (\n !!obj &&\n typeof obj === 'object' &&\n hasProp(obj, 'lat') &&\n typeof obj.lat === 'function' &&\n hasProp(obj, 'lng') &&\n typeof obj.lng === 'function'\n );\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pega/cosmos-react-core",
3
- "version": "7.16.2",
3
+ "version": "7.16.3",
4
4
  "description": "Cosmos is a visual design system and UI component collection. Its goal is to empower application developers in their pursuit to create engaging and rewarding user experiences.",
5
5
  "repository": {
6
6
  "type": "git",