@pega/cosmos-react-core 9.0.0-build.7.4 → 9.0.0-build.8.0
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.
- package/lib/components/ListToolbar/ListToolbar.types.d.ts +5 -1
- package/lib/components/ListToolbar/ListToolbar.types.d.ts.map +1 -1
- package/lib/components/ListToolbar/ListToolbar.types.js.map +1 -1
- package/lib/components/Location/CurrentLocationButton.d.ts.map +1 -1
- package/lib/components/Location/CurrentLocationButton.js +4 -2
- package/lib/components/Location/CurrentLocationButton.js.map +1 -1
- package/lib/components/Location/GoogleMapsAPI.d.ts +43 -0
- package/lib/components/Location/GoogleMapsAPI.d.ts.map +1 -0
- package/lib/components/Location/GoogleMapsAPI.js +244 -0
- package/lib/components/Location/GoogleMapsAPI.js.map +1 -0
- package/lib/components/Location/Location.types.d.ts +3 -2
- package/lib/components/Location/Location.types.d.ts.map +1 -1
- package/lib/components/Location/Location.types.js.map +1 -1
- package/lib/components/Location/LocationAPI.types.d.ts +23 -0
- package/lib/components/Location/LocationAPI.types.d.ts.map +1 -0
- package/lib/components/Location/LocationAPI.types.js +2 -0
- package/lib/components/Location/LocationAPI.types.js.map +1 -0
- package/lib/components/Location/LocationDisplay.d.ts.map +1 -1
- package/lib/components/Location/LocationDisplay.js +5 -3
- package/lib/components/Location/LocationDisplay.js.map +1 -1
- package/lib/components/Location/LocationInput.d.ts.map +1 -1
- package/lib/components/Location/LocationInput.js +23 -20
- package/lib/components/Location/LocationInput.js.map +1 -1
- package/lib/components/Location/LocationView.d.ts.map +1 -1
- package/lib/components/Location/LocationView.js +8 -5
- package/lib/components/Location/LocationView.js.map +1 -1
- package/lib/components/Location/index.d.ts +2 -1
- package/lib/components/Location/index.d.ts.map +1 -1
- package/lib/components/Location/index.js +2 -1
- package/lib/components/Location/index.js.map +1 -1
- package/lib/components/Location/utils.d.ts +3 -19
- package/lib/components/Location/utils.d.ts.map +1 -1
- package/lib/components/Location/utils.js +7 -161
- package/lib/components/Location/utils.js.map +1 -1
- package/lib/styles/GlobalStyle.d.ts.map +1 -1
- package/lib/styles/GlobalStyle.js +3 -0
- package/lib/styles/GlobalStyle.js.map +1 -1
- package/package.json +2 -2
|
@@ -10,7 +10,7 @@ import { defaultThemeProp } from '../../theme';
|
|
|
10
10
|
import PoweredByGoogleImage from './PoweredByGoogleImage';
|
|
11
11
|
import CurrentLocationButton from './CurrentLocationButton';
|
|
12
12
|
import MapsContext from './MapsContext';
|
|
13
|
-
import {
|
|
13
|
+
import { getNavigatorPosition, isValueACoordinate, loadMapsAPI } from './utils';
|
|
14
14
|
import LocationView from './LocationView';
|
|
15
15
|
import { StyledLocationView } from './LocationView.styles';
|
|
16
16
|
import { getLocationInputTestIds } from './Location.test-ids';
|
|
@@ -38,9 +38,9 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
|
|
|
38
38
|
(async () => {
|
|
39
39
|
if (defaultToCurrentLocation) {
|
|
40
40
|
setMapLoading(true);
|
|
41
|
-
await loadMapsAPI(name, providerOpts);
|
|
41
|
+
const mapAPIObj = await loadMapsAPI(name, providerOpts);
|
|
42
42
|
const navigatorPosition = await getNavigatorPosition();
|
|
43
|
-
const currentLocationAddress = await getAddress(navigatorPosition);
|
|
43
|
+
const currentLocationAddress = await mapAPIObj.getAddress(navigatorPosition);
|
|
44
44
|
setMapLoading(false);
|
|
45
45
|
onSelect?.(currentLocationAddress);
|
|
46
46
|
}
|
|
@@ -49,10 +49,10 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
|
|
|
49
49
|
useEffect(() => {
|
|
50
50
|
(async () => {
|
|
51
51
|
try {
|
|
52
|
-
await loadMapsAPI(name, providerOpts);
|
|
52
|
+
const mapAPIObj = await loadMapsAPI(name, providerOpts);
|
|
53
53
|
if (filterValue) {
|
|
54
54
|
if (onlyCoordinates) {
|
|
55
|
-
const { latitude, longitude } = await getCoords(filterValue);
|
|
55
|
+
const { latitude, longitude } = await mapAPIObj.getCoords(filterValue);
|
|
56
56
|
setPlacePredictionMenuItems([
|
|
57
57
|
{
|
|
58
58
|
primary: t('exact_location'),
|
|
@@ -67,8 +67,11 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
|
|
|
67
67
|
}
|
|
68
68
|
else {
|
|
69
69
|
if (isValueACoordinate(filterValue)) {
|
|
70
|
-
const { latitude, longitude } = await getCoords(filterValue);
|
|
71
|
-
const { name: addressName, address } = await getAddress({
|
|
70
|
+
const { latitude, longitude } = await mapAPIObj.getCoords(filterValue);
|
|
71
|
+
const { name: addressName, address } = await mapAPIObj.getAddress({
|
|
72
|
+
latitude,
|
|
73
|
+
longitude
|
|
74
|
+
});
|
|
72
75
|
const menuItems = [
|
|
73
76
|
{
|
|
74
77
|
primary: t('exact_location'),
|
|
@@ -95,15 +98,15 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
|
|
|
95
98
|
setPlacePredictionMenuItems(menuItems);
|
|
96
99
|
return;
|
|
97
100
|
}
|
|
98
|
-
const {
|
|
99
|
-
if (
|
|
100
|
-
const exactLocation = await getPlaceById(
|
|
101
|
-
const menuItems =
|
|
102
|
-
id: item.
|
|
103
|
-
primary: item.
|
|
104
|
-
secondary: [item.
|
|
101
|
+
const { placeSuggestions, token } = await mapAPIObj.getPlacePredictions(filterValue, bias);
|
|
102
|
+
if (placeSuggestions.length === 1) {
|
|
103
|
+
const exactLocation = await mapAPIObj.getPlaceById(placeSuggestions[0].placeId, token);
|
|
104
|
+
const menuItems = placeSuggestions.map(item => ({
|
|
105
|
+
id: item.placeId,
|
|
106
|
+
primary: item.mainText,
|
|
107
|
+
secondary: [item.secondaryText],
|
|
105
108
|
onClick: (menuItemId) => {
|
|
106
|
-
getPlaceById(menuItemId, token).then(menuItemLocation => {
|
|
109
|
+
mapAPIObj.getPlaceById(menuItemId, token).then(menuItemLocation => {
|
|
107
110
|
setFilterValue('');
|
|
108
111
|
onSelect?.(menuItemLocation);
|
|
109
112
|
});
|
|
@@ -126,12 +129,12 @@ const LocationInput = forwardRef(function LocationInput(props, ref) {
|
|
|
126
129
|
setPlacePredictionMenuItems(menuItems);
|
|
127
130
|
}
|
|
128
131
|
else {
|
|
129
|
-
setPlacePredictionMenuItems(
|
|
130
|
-
id: item.
|
|
131
|
-
primary: item.
|
|
132
|
-
secondary: [item.
|
|
132
|
+
setPlacePredictionMenuItems(placeSuggestions.map(item => ({
|
|
133
|
+
id: item.placeId,
|
|
134
|
+
primary: item.mainText,
|
|
135
|
+
secondary: [item.secondaryText],
|
|
133
136
|
onClick: (menuItemId) => {
|
|
134
|
-
getPlaceById(menuItemId, token).then(menuItemLocation => {
|
|
137
|
+
mapAPIObj.getPlaceById(menuItemId, token).then(menuItemLocation => {
|
|
135
138
|
setFilterValue('');
|
|
136
139
|
onSelect?.(menuItemLocation);
|
|
137
140
|
});
|
|
@@ -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,eAAe,EAAE,MAAM,aAAa,CAAC;AACtE,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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,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, createClassName } 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 from './LocationView';\nimport { StyledLocationView } from './LocationView.styles';\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 className,\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 className={createClassName('location-input', className, { status })}\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,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,eAAe,EAAE,MAAM,aAAa,CAAC;AACtE,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,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAEhF,OAAO,YAAY,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAiD9D,MAAM,mBAAmB,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;;CAE3C,CAAC;AAEF,mBAAmB,CAAC,YAAY,GAAG,gBAAgB,CAAC;AAEpD,MAAM,iBA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B,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,EACb,SAAS,EAAE,eAAe,CAAC,gBAAgB,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,CAAC,GACnE,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, createClassName } 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 { getNavigatorPosition, isValueACoordinate, loadMapsAPI } from './utils';\nimport type { Bias, LatLng } from './Location.types';\nimport LocationView from './LocationView';\nimport { StyledLocationView } from './LocationView.styles';\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 className,\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 const mapAPIObj = await loadMapsAPI(name, providerOpts);\n\n const navigatorPosition = await getNavigatorPosition();\n const currentLocationAddress = await mapAPIObj.getAddress(navigatorPosition);\n setMapLoading(false);\n onSelect?.(currentLocationAddress);\n }\n })();\n }, []);\n\n useEffect(() => {\n (async () => {\n try {\n const mapAPIObj = await loadMapsAPI(name, providerOpts);\n\n if (filterValue) {\n if (onlyCoordinates) {\n const { latitude, longitude } = await mapAPIObj.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 mapAPIObj.getCoords(filterValue);\n const { name: addressName, address } = await mapAPIObj.getAddress({\n latitude,\n longitude\n });\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 { placeSuggestions, token } = await mapAPIObj.getPlacePredictions(\n filterValue,\n bias\n );\n if (placeSuggestions.length === 1) {\n const exactLocation = await mapAPIObj.getPlaceById(\n placeSuggestions[0].placeId,\n token\n );\n const menuItems = placeSuggestions.map(item => ({\n id: item.placeId,\n primary: item.mainText,\n secondary: [item.secondaryText],\n onClick: (menuItemId: MenuItemProps['id']) => {\n mapAPIObj.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 placeSuggestions.map(item => ({\n id: item.placeId,\n primary: item.mainText,\n secondary: [item.secondaryText],\n onClick: (menuItemId: MenuItemProps['id']) => {\n mapAPIObj.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 className={createClassName('location-input', className, { status })}\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LocationView.d.ts","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,aAAa,CAAC;AAK9D,OAAO,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"LocationView.d.ts","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,aAAa,CAAC;AAK9D,OAAO,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAKpD,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;AAqBF,QAAA,MAAM,YAAY,2HA2OjB,CAAC;AAEF,eAAe,YAAY,CAAC"}
|
|
@@ -6,7 +6,7 @@ import { createUID } from '../../utils';
|
|
|
6
6
|
import Progress from '../Progress';
|
|
7
7
|
import { StyledLocationError, StyledLocationView, StyledMap } from './LocationView.styles';
|
|
8
8
|
import MapsContext from './MapsContext';
|
|
9
|
-
import {
|
|
9
|
+
import { isLatLngObject, loadMapsAPI, toGoogleLatLng } from './utils';
|
|
10
10
|
var LoadStatus;
|
|
11
11
|
(function (LoadStatus) {
|
|
12
12
|
LoadStatus["Init"] = "init";
|
|
@@ -29,6 +29,7 @@ const LocationView = forwardRef(function LocationView(props, ref) {
|
|
|
29
29
|
const [status, setStatus] = useState(LoadStatus.Init);
|
|
30
30
|
const [eMessage, setEMessage] = useState('');
|
|
31
31
|
const [selectedPinIndex, setSelectedPinIndex] = useState(undefined);
|
|
32
|
+
const [mapAPIObj, setmapAPIObj] = useState();
|
|
32
33
|
const mapElemRef = useRef();
|
|
33
34
|
const map = useRef();
|
|
34
35
|
const markers = useRef([]);
|
|
@@ -37,10 +38,10 @@ const LocationView = forwardRef(function LocationView(props, ref) {
|
|
|
37
38
|
const infoWindowContent = useRef(document.createElement('div'));
|
|
38
39
|
const theme = useTheme();
|
|
39
40
|
const onMapClick = (e) => {
|
|
40
|
-
if (!isLatLngObject(e.latLng))
|
|
41
|
+
if (!isLatLngObject(e.latLng) || !mapAPIObj)
|
|
41
42
|
return;
|
|
42
43
|
if (hasPlaceId(e)) {
|
|
43
|
-
getPlaceById(e.placeId).then(placeInfo => {
|
|
44
|
+
mapAPIObj.getPlaceById(e.placeId).then(placeInfo => {
|
|
44
45
|
onClick?.({
|
|
45
46
|
...placeInfo,
|
|
46
47
|
latitude: e.latLng.lat(),
|
|
@@ -49,7 +50,8 @@ const LocationView = forwardRef(function LocationView(props, ref) {
|
|
|
49
50
|
});
|
|
50
51
|
}
|
|
51
52
|
else {
|
|
52
|
-
|
|
53
|
+
mapAPIObj
|
|
54
|
+
.getAddress({
|
|
53
55
|
latitude: e.latLng.lat(),
|
|
54
56
|
longitude: e.latLng.lng()
|
|
55
57
|
})
|
|
@@ -97,7 +99,8 @@ const LocationView = forwardRef(function LocationView(props, ref) {
|
|
|
97
99
|
useEffect(() => {
|
|
98
100
|
let mounted = true;
|
|
99
101
|
loadMapsAPI(name, providerOpts)
|
|
100
|
-
.then(
|
|
102
|
+
.then(APIObj => {
|
|
103
|
+
setmapAPIObj(APIObj);
|
|
101
104
|
if (mounted) {
|
|
102
105
|
initialize();
|
|
103
106
|
setStatus(LoadStatus.Ready);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LocationView.js","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACzF,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEhD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,QAAQ,MAAM,aAAa,CAAC;AAEnC,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAE3F,OAAO,WAAW,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,cAAc,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAoDhG,IAAK,UAIJ;AAJD,WAAK,UAAU;IACb,2BAAa,CAAA;IACb,6BAAe,CAAA;IACf,6BAAe,CAAA;AACjB,CAAC,EAJI,UAAU,KAAV,UAAU,QAId;AAED,MAAM,UAAU,GAAG,CAAC,GAAY,EAA2D,EAAE;IAC3F,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,CAAC,CAAC,GAAG;QACL,SAAS,IAAI,GAAG;QAChB,CAAC,CAAC,GAAG,CAAC,OAAO;QACb,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ,CAChC,CAAC;AACJ,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,UAAU,CAAC,KAAK,IAAI,QAAQ,IAAI,CAC1C,KAAC,mBAAmB,kBAAa,QAAQ,EAAE,OAAO,EAAC,MAAM,YACtD,QAAQ,GACW,CACvB,EACA,gBAAgB,KAAK,SAAS,IAAI,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,OAAO,IAAI,CACrE,4BAAG,YAAY,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,OAAO,EAAE,iBAAiB,CAAC,OAAO,CAAC,GAAI,CAC/E,IACkB,CACtB,CAAC;AACJ,CAAC,CACF,CAAC;AAEF,eAAe,YAAY,CAAC","sourcesContent":["import type { PropsWithoutRef, Ref } from 'react';\nimport { forwardRef, useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { useI18n, useTheme } from '../../hooks';\nimport type { RefElement, WithAttributes } from '../../types';\nimport { createUID } from '../../utils';\nimport Progress from '../Progress';\n\nimport { StyledLocationError, StyledLocationView, StyledMap } from './LocationView.styles';\nimport type { LatLng, Pin } from './Location.types';\nimport MapsContext from './MapsContext';\nimport { getAddress, getPlaceById, isLatLngObject, loadMapsAPI, toGoogleLatLng } from './utils';\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: unknown): obj is google.maps.IconMouseEvent & { placeId: string } => {\n return (\n typeof obj === 'object' &&\n !!obj &&\n 'placeId' in obj &&\n !!obj.placeId &&\n typeof obj.placeId === 'string'\n );\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 t = useI18n();\n const { name, ...providerOpts } = useContext(MapsContext);\n const [status, setStatus] = useState<LoadStatus>(LoadStatus.Init);\n const [eMessage, setEMessage] = useState('');\n const [selectedPinIndex, setSelectedPinIndex] = useState<number | undefined>(undefined);\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 infoWindowContent = useRef<HTMLDivElement>(document.createElement('div'));\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 centerMap = useCallback((coords: LatLng[]) => {\n if (!map.current || coords.length === 0) return;\n\n if (coords.length === 1) {\n map.current.setCenter(toGoogleLatLng(coords[0]));\n map.current.setZoom(zoomLevel);\n } else {\n const bounds = new google.maps.LatLngBounds();\n coords.forEach(({ latitude, longitude }) => {\n bounds.extend(toGoogleLatLng({ latitude, longitude }));\n });\n map.current.fitBounds(bounds);\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 centerMap(pins);\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 infoWindow = new google.maps.InfoWindow();\n\n try {\n markers.current = pins.map(({ latitude, longitude, title, content, selected }, index) => {\n const gCoords = toGoogleLatLng({ latitude, longitude });\n\n const contentConfig: google.maps.marker.PinElementOptions = {\n glyphColor: theme.base.colors.white\n };\n const label = markerLabels[index % markerLabels.length];\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 = label;\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 pin = 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: pin.element\n });\n if (content) {\n marker.addListener('click', () => {\n setSelectedPinIndex(index);\n infoWindow.setOptions({\n ariaLabel: `${t('location_info')} - ${title ?? label}`,\n headerContent: title ?? label\n });\n infoWindow.setContent(infoWindowContent.current);\n infoWindow.open({\n anchor: marker,\n map: map.current\n });\n });\n }\n return marker;\n });\n } catch {\n markers.current = [];\n }\n\n if (centerMapOnChange) {\n centerMap(pins);\n }\n\n return () => {\n markers.current.forEach(m => {\n m.map = null;\n });\n dr.current?.setMap(null);\n };\n }, [\n JSON.stringify(pins, ['title', 'selected', 'latitude', 'longitude']),\n status,\n zoomLevel,\n disabled,\n drawRoute,\n centerMapOnChange,\n onError\n ]);\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 {selectedPinIndex !== undefined && !!pins[selectedPinIndex].content && (\n <>{createPortal(pins[selectedPinIndex].content, infoWindowContent.current)}</>\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":";AACA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACzF,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEhD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,QAAQ,MAAM,aAAa,CAAC;AAEnC,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAE3F,OAAO,WAAW,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAqDtE,IAAK,UAIJ;AAJD,WAAK,UAAU;IACb,2BAAa,CAAA;IACb,6BAAe,CAAA;IACf,6BAAe,CAAA;AACjB,CAAC,EAJI,UAAU,KAAV,UAAU,QAId;AAED,MAAM,UAAU,GAAG,CAAC,GAAY,EAA2D,EAAE;IAC3F,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,CAAC,CAAC,GAAG;QACL,SAAS,IAAI,GAAG;QAChB,CAAC,CAAC,GAAG,CAAC,OAAO;QACb,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ,CAChC,CAAC;AACJ,CAAC,CAAC;AAEF,+CAA+C;AAC/C,MAAM,YAAY,GAAG,2BAA2B,CAAC;AAEjD,MAAM,YAAY,GAAG,UAAU,CAC7B,SAAS,YAAY,CAAC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C,OAAO,GAAG,EACzE,MAAM,KAAK,UAAU,CAAC,KAAK,IAAI,QAAQ,IAAI,CAC1C,KAAC,mBAAmB,kBAAa,QAAQ,EAAE,OAAO,EAAC,MAAM,YACtD,QAAQ,GACW,CACvB,EACA,gBAAgB,KAAK,SAAS,IAAI,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,OAAO,IAAI,CACrE,4BAAG,YAAY,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,OAAO,EAAE,iBAAiB,CAAC,OAAO,CAAC,GAAI,CAC/E,IACkB,CACtB,CAAC;AACJ,CAAC,CACF,CAAC;AAEF,eAAe,YAAY,CAAC","sourcesContent":["import type { PropsWithoutRef, Ref } from 'react';\nimport { forwardRef, useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { useI18n, useTheme } from '../../hooks';\nimport type { RefElement, WithAttributes } from '../../types';\nimport { createUID } from '../../utils';\nimport Progress from '../Progress';\n\nimport { StyledLocationError, StyledLocationView, StyledMap } from './LocationView.styles';\nimport type { LatLng, Pin } from './Location.types';\nimport MapsContext from './MapsContext';\nimport { isLatLngObject, loadMapsAPI, toGoogleLatLng } from './utils';\nimport type { LocationAPI } from './LocationAPI.types';\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: unknown): obj is google.maps.IconMouseEvent & { placeId: string } => {\n return (\n typeof obj === 'object' &&\n !!obj &&\n 'placeId' in obj &&\n !!obj.placeId &&\n typeof obj.placeId === 'string'\n );\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 t = useI18n();\n const { name, ...providerOpts } = useContext(MapsContext);\n const [status, setStatus] = useState<LoadStatus>(LoadStatus.Init);\n const [eMessage, setEMessage] = useState('');\n const [selectedPinIndex, setSelectedPinIndex] = useState<number | undefined>(undefined);\n const [mapAPIObj, setmapAPIObj] = useState<LocationAPI>();\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 infoWindowContent = useRef<HTMLDivElement>(document.createElement('div'));\n const theme = useTheme();\n\n const onMapClick = (e: google.maps.MapMouseEvent) => {\n if (!isLatLngObject(e.latLng) || !mapAPIObj) return;\n\n if (hasPlaceId(e)) {\n mapAPIObj.getPlaceById(e.placeId).then(placeInfo => {\n onClick?.({\n ...placeInfo,\n latitude: e.latLng!.lat(),\n longitude: e.latLng!.lng()\n });\n });\n } else {\n mapAPIObj\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 centerMap = useCallback((coords: LatLng[]) => {\n if (!map.current || coords.length === 0) return;\n\n if (coords.length === 1) {\n map.current.setCenter(toGoogleLatLng(coords[0]));\n map.current.setZoom(zoomLevel);\n } else {\n const bounds = new google.maps.LatLngBounds();\n coords.forEach(({ latitude, longitude }) => {\n bounds.extend(toGoogleLatLng({ latitude, longitude }));\n });\n map.current.fitBounds(bounds);\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 centerMap(pins);\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(APIObj => {\n setmapAPIObj(APIObj);\n\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 infoWindow = new google.maps.InfoWindow();\n\n try {\n markers.current = pins.map(({ latitude, longitude, title, content, selected }, index) => {\n const gCoords = toGoogleLatLng({ latitude, longitude });\n\n const contentConfig: google.maps.marker.PinElementOptions = {\n glyphColor: theme.base.colors.white\n };\n const label = markerLabels[index % markerLabels.length];\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 = label;\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 pin = 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: pin.element\n });\n if (content) {\n marker.addListener('click', () => {\n setSelectedPinIndex(index);\n infoWindow.setOptions({\n ariaLabel: `${t('location_info')} - ${title ?? label}`,\n headerContent: title ?? label\n });\n infoWindow.setContent(infoWindowContent.current);\n infoWindow.open({\n anchor: marker,\n map: map.current\n });\n });\n }\n return marker;\n });\n } catch {\n markers.current = [];\n }\n\n if (centerMapOnChange) {\n centerMap(pins);\n }\n\n return () => {\n markers.current.forEach(m => {\n m.map = null;\n });\n dr.current?.setMap(null);\n };\n }, [\n JSON.stringify(pins, ['title', 'selected', 'latitude', 'longitude']),\n status,\n zoomLevel,\n disabled,\n drawRoute,\n centerMapOnChange,\n onError\n ]);\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 {selectedPinIndex !== undefined && !!pins[selectedPinIndex].content && (\n <>{createPortal(pins[selectedPinIndex].content, infoWindowContent.current)}</>\n )}\n </StyledLocationView>\n );\n }\n);\n\nexport default LocationView;\n"]}
|
|
@@ -6,5 +6,6 @@ export { default as MapsContext } from './MapsContext';
|
|
|
6
6
|
export { default as LocationDisplay } from './LocationDisplay';
|
|
7
7
|
export type { LocationDisplayProps } from './LocationDisplay';
|
|
8
8
|
export type { LatLng, Pin, Location } from './Location.types';
|
|
9
|
-
export { isValueACoordinate,
|
|
9
|
+
export { isValueACoordinate, getGoogleMapsDirHref } from './utils';
|
|
10
|
+
export { default as GoogleMapsAPI } from './GoogleMapsAPI';
|
|
10
11
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/components/Location/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC3D,YAAY,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACzD,YAAY,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC/D,YAAY,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,YAAY,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/components/Location/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC3D,YAAY,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACzD,YAAY,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC/D,YAAY,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,YAAY,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AACnE,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAC"}
|
|
@@ -2,5 +2,6 @@ export { default as LocationInput } from './LocationInput';
|
|
|
2
2
|
export { default as LocationView } from './LocationView';
|
|
3
3
|
export { default as MapsContext } from './MapsContext';
|
|
4
4
|
export { default as LocationDisplay } from './LocationDisplay';
|
|
5
|
-
export { isValueACoordinate,
|
|
5
|
+
export { isValueACoordinate, getGoogleMapsDirHref } from './utils';
|
|
6
|
+
export { default as GoogleMapsAPI } from './GoogleMapsAPI';
|
|
6
7
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/components/Location/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEzD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAG/D,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/components/Location/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEzD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAG/D,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AACnE,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAC","sourcesContent":["export { default as LocationInput } from './LocationInput';\nexport type { LocationInputProps } from './LocationInput';\nexport { default as LocationView } from './LocationView';\nexport type { LocationViewProps } from './LocationView';\nexport { default as MapsContext } from './MapsContext';\nexport { default as LocationDisplay } from './LocationDisplay';\nexport type { LocationDisplayProps } from './LocationDisplay';\nexport type { LatLng, Pin, Location } from './Location.types';\nexport { isValueACoordinate, getGoogleMapsDirHref } from './utils';\nexport { default as GoogleMapsAPI } from './GoogleMapsAPI';\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/// <reference types="google.maps" preserve="true" />
|
|
2
|
-
import type {
|
|
3
|
-
|
|
2
|
+
import type { LatLng, ProviderOpts } from './Location.types';
|
|
3
|
+
import type { LocationAPI } from './LocationAPI.types';
|
|
4
|
+
export declare function loadMapsAPI(name?: string, opts?: ProviderOpts): Promise<LocationAPI>;
|
|
4
5
|
/**
|
|
5
6
|
* Identifies coordinates in degree format
|
|
6
7
|
* eg. 45.78°N 9.11°E
|
|
@@ -27,23 +28,6 @@ export declare function isValueACoordinate(value: string): boolean;
|
|
|
27
28
|
export declare function parseDMS(input: string): number[];
|
|
28
29
|
export declare function getNavigatorPosition(): Promise<LatLng>;
|
|
29
30
|
export declare function toGoogleLatLng(coords: LatLng): google.maps.LatLng;
|
|
30
|
-
/** Returns an array of place prediction objects ('place' can be an establishment, geographic location, or prominent point of interest)
|
|
31
|
-
* and session token (valid for multiple queries, followed by one place selection).
|
|
32
|
-
*/
|
|
33
|
-
export declare function getPlacePredictions(location: string, bias?: Bias): Promise<{
|
|
34
|
-
placePredictions: google.maps.places.AutocompletePrediction[];
|
|
35
|
-
token: google.maps.places.AutocompleteSessionToken;
|
|
36
|
-
}>;
|
|
37
|
-
export declare function getPlace(location: string, mapElement?: HTMLDivElement): Promise<LatLng>;
|
|
38
|
-
export declare function getPlaceById(placeId: string, sessionToken?: google.maps.places.AutocompleteSessionToken, mapElement?: HTMLDivElement): Promise<Location>;
|
|
39
|
-
/** Returns coordinations for given input: either coords, address or current position. */
|
|
40
|
-
export declare function getCoords(coords: string | 'current' | LatLng, mapElement?: HTMLDivElement): Promise<LatLng>;
|
|
41
|
-
export declare function getAddress(coords: LatLng): Promise<{
|
|
42
|
-
name: string;
|
|
43
|
-
address?: string;
|
|
44
|
-
latitude: number;
|
|
45
|
-
longitude: number;
|
|
46
|
-
}>;
|
|
47
31
|
export declare const isLatLngObject: (obj: unknown) => obj is google.maps.LatLng;
|
|
48
32
|
export declare const getGoogleMapsDirHref: (destination: string, waypoints: string[], travelMode?: string) => string;
|
|
49
33
|
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/components/Location/utils.ts"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/components/Location/utils.ts"],"names":[],"mappings":";AAUA,OAAO,KAAK,EAAE,MAAM,EAAgB,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AA2HvD,wBAAsB,WAAW,CAAC,IAAI,GAAE,MAAW,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,CAoB9F;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEpE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE1D;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE3D;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAOzD;AA6BD;;GAEG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAmChD;AAED,wBAAsB,oBAAoB,IAAI,OAAO,CAAC,MAAM,CAAC,CAc5D;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAEjE;AAED,eAAO,MAAM,cAAc,GAAI,KAAK,OAAO,KAAG,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,MAShE,CAAC;AAEF,eAAO,MAAM,oBAAoB,GAC/B,aAAa,MAAM,EACnB,WAAW,MAAM,EAAE,EACnB,aAAY,MAAkB,WAS/B,CAAC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/// <reference types="google.maps" preserve="true" />
|
|
2
2
|
import { Loader } from '@googlemaps/js-api-loader';
|
|
3
|
-
import {
|
|
3
|
+
import { GeolocationUnsupportedError, GoogleMapsAPINotFoundError, IsNotAnObjectError, ProviderNotSupportedError } from './Location.types';
|
|
4
|
+
import GoogleMapsAPI from './GoogleMapsAPI';
|
|
4
5
|
const DegreeRegexChunks = [
|
|
5
6
|
/^[-+]?/,
|
|
6
7
|
// latitude degrees
|
|
@@ -93,7 +94,7 @@ const providers = {
|
|
|
93
94
|
language: opts.language,
|
|
94
95
|
libraries: ['places', 'marker']
|
|
95
96
|
});
|
|
96
|
-
return loader.load().then(() =>
|
|
97
|
+
return loader.load().then(() => new GoogleMapsAPI(), () => {
|
|
97
98
|
throw new Error(GoogleMapsAPINotFoundError);
|
|
98
99
|
});
|
|
99
100
|
}
|
|
@@ -113,11 +114,13 @@ export async function loadMapsAPI(name = '', opts) {
|
|
|
113
114
|
if (!provider.loadedPromise) {
|
|
114
115
|
provider.loadedPromise = provider
|
|
115
116
|
.loadAPI(opts)
|
|
116
|
-
.then(
|
|
117
|
+
.then(ApiObj => {
|
|
117
118
|
provider.loadedApiKey = opts?.apiKey ?? '';
|
|
119
|
+
return ApiObj;
|
|
118
120
|
})
|
|
119
|
-
.catch(
|
|
121
|
+
.catch(err => {
|
|
120
122
|
provider.loadedPromise = null;
|
|
123
|
+
throw new Error(err);
|
|
121
124
|
});
|
|
122
125
|
}
|
|
123
126
|
return provider.loadedPromise;
|
|
@@ -219,163 +222,6 @@ export async function getNavigatorPosition() {
|
|
|
219
222
|
export function toGoogleLatLng(coords) {
|
|
220
223
|
return new google.maps.LatLng(coords.latitude, coords.longitude);
|
|
221
224
|
}
|
|
222
|
-
/** Returns an array of place prediction objects ('place' can be an establishment, geographic location, or prominent point of interest)
|
|
223
|
-
* and session token (valid for multiple queries, followed by one place selection).
|
|
224
|
-
*/
|
|
225
|
-
export async function getPlacePredictions(location, bias = {}) {
|
|
226
|
-
const autocompleteService = new google.maps.places.AutocompleteService();
|
|
227
|
-
const optionalParams = {};
|
|
228
|
-
if (bias?.location) {
|
|
229
|
-
if (bias?.location.center === 'current') {
|
|
230
|
-
await getNavigatorPosition()
|
|
231
|
-
.then(coords => {
|
|
232
|
-
optionalParams.location = toGoogleLatLng(coords);
|
|
233
|
-
optionalParams.radius = bias.location.radius;
|
|
234
|
-
})
|
|
235
|
-
// no-op user didn't allow location
|
|
236
|
-
.catch(() => { });
|
|
237
|
-
}
|
|
238
|
-
else {
|
|
239
|
-
optionalParams.location = toGoogleLatLng(bias.location.center);
|
|
240
|
-
optionalParams.radius = bias.location.radius;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
if (bias?.bounds) {
|
|
244
|
-
const [sw, ne] = bias.bounds;
|
|
245
|
-
optionalParams.bounds = new google.maps.LatLngBounds(toGoogleLatLng(sw), toGoogleLatLng(ne));
|
|
246
|
-
}
|
|
247
|
-
return new Promise((resolve, reject) => {
|
|
248
|
-
const token = new google.maps.places.AutocompleteSessionToken();
|
|
249
|
-
autocompleteService.getPlacePredictions({
|
|
250
|
-
input: location,
|
|
251
|
-
types: QUERY_TYPES,
|
|
252
|
-
sessionToken: token,
|
|
253
|
-
...optionalParams
|
|
254
|
-
}, (placePredictions, status) => {
|
|
255
|
-
if (status === google.maps.places.PlacesServiceStatus.OK) {
|
|
256
|
-
resolve({ placePredictions: placePredictions ?? [], token });
|
|
257
|
-
}
|
|
258
|
-
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));
|
|
281
|
-
}
|
|
282
|
-
});
|
|
283
|
-
});
|
|
284
|
-
}
|
|
285
|
-
export async function getPlaceById(placeId, sessionToken = new google.maps.places.AutocompleteSessionToken(), mapElement = document.createElement('div')) {
|
|
286
|
-
const placesService = new google.maps.places.PlacesService(mapElement);
|
|
287
|
-
return new Promise((resolve, reject) => {
|
|
288
|
-
placesService.getDetails({ placeId, fields: QUERY_FIELDS, sessionToken }, (place, pStatus) => {
|
|
289
|
-
if (pStatus === google.maps.places.PlacesServiceStatus.OK) {
|
|
290
|
-
resolve({
|
|
291
|
-
name: place?.name,
|
|
292
|
-
address: place?.formatted_address,
|
|
293
|
-
latitude: place?.geometry?.location?.lat(),
|
|
294
|
-
longitude: place?.geometry?.location?.lng()
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
else {
|
|
298
|
-
reject(new Error(LocationNotFoundError));
|
|
299
|
-
}
|
|
300
|
-
});
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
/** Returns coordinations for given input: either coords, address or current position. */
|
|
304
|
-
export async function getCoords(coords, mapElement) {
|
|
305
|
-
if (coords === '' || coords === undefined)
|
|
306
|
-
throw new Error();
|
|
307
|
-
if (coords === 'current')
|
|
308
|
-
return getNavigatorPosition();
|
|
309
|
-
let location;
|
|
310
|
-
if (typeof coords === 'string') {
|
|
311
|
-
let latLng = [];
|
|
312
|
-
if (isValueDMSCoordinate(coords) ||
|
|
313
|
-
isValueDMCoordinate(coords) ||
|
|
314
|
-
isValueDegreeFormatCoordinate(coords)) {
|
|
315
|
-
latLng = parseDMS(coords);
|
|
316
|
-
}
|
|
317
|
-
else {
|
|
318
|
-
let splitter;
|
|
319
|
-
if (coords.includes(', ')) {
|
|
320
|
-
splitter = ', ';
|
|
321
|
-
}
|
|
322
|
-
else if (coords.includes(',')) {
|
|
323
|
-
splitter = ',';
|
|
324
|
-
}
|
|
325
|
-
else if (coords.includes(' ')) {
|
|
326
|
-
splitter = ' ';
|
|
327
|
-
}
|
|
328
|
-
else {
|
|
329
|
-
splitter = ', ';
|
|
330
|
-
}
|
|
331
|
-
latLng = coords.split(splitter).map(Number);
|
|
332
|
-
}
|
|
333
|
-
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 };
|
|
337
|
-
}
|
|
338
|
-
else {
|
|
339
|
-
location = coords;
|
|
340
|
-
}
|
|
341
|
-
if (Number.isFinite(location.latitude) && Number.isFinite(location.longitude))
|
|
342
|
-
return location;
|
|
343
|
-
throw new Error(CoordsCannotBeParsedError);
|
|
344
|
-
}
|
|
345
|
-
export async function getAddress(coords) {
|
|
346
|
-
const location = {
|
|
347
|
-
lat: coords.latitude,
|
|
348
|
-
lng: coords.longitude
|
|
349
|
-
};
|
|
350
|
-
const geocoder = new google.maps.Geocoder();
|
|
351
|
-
return new Promise((resolve, reject) => {
|
|
352
|
-
geocoder.geocode({ location }, (results, status) => {
|
|
353
|
-
if (status === 'OK') {
|
|
354
|
-
const [result] = results ?? [];
|
|
355
|
-
if (result) {
|
|
356
|
-
resolve({
|
|
357
|
-
name: result.formatted_address,
|
|
358
|
-
address: result.formatted_address,
|
|
359
|
-
...(result.geometry && {
|
|
360
|
-
latitude: result.geometry.location.lat(),
|
|
361
|
-
longitude: result.geometry.location.lng()
|
|
362
|
-
})
|
|
363
|
-
});
|
|
364
|
-
}
|
|
365
|
-
else {
|
|
366
|
-
resolve({
|
|
367
|
-
name: `${coords.latitude}, ${coords.longitude}`,
|
|
368
|
-
latitude: coords.latitude,
|
|
369
|
-
longitude: coords.longitude
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
else {
|
|
374
|
-
reject(new Error(`${GeocoderFailedError}: ${status}`));
|
|
375
|
-
}
|
|
376
|
-
});
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
225
|
export const isLatLngObject = (obj) => {
|
|
380
226
|
return (!!obj &&
|
|
381
227
|
typeof obj === 'object' &&
|