@ttoss/google-maps 1.16.0 → 1.20.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ttoss/google-maps",
3
- "version": "1.16.0",
3
+ "version": "1.20.0",
4
4
  "author": "ttoss",
5
5
  "contributors": [
6
6
  {
@@ -31,13 +31,17 @@
31
31
  "build": "tsup"
32
32
  },
33
33
  "dependencies": {
34
- "@ttoss/hooks": "^1.16.0",
34
+ "@ttoss/hooks": "^1.20.0",
35
35
  "@types/google.maps": "^3.48.6",
36
36
  "use-callback-ref": "^1.3.0"
37
37
  },
38
+ "devDependencies": {
39
+ "@ttoss/config": "^1.17.0",
40
+ "@ttoss/test-utils": "^1.16.6"
41
+ },
38
42
  "peerDependencies": {
39
43
  "react": ">=16.8.0",
40
44
  "react-dom": ">=16.8.0"
41
45
  },
42
- "gitHead": "0412266ba0223a5b42904254a13d96473006e0a3"
46
+ "gitHead": "bea31ace95128d57607156807e402a793b0c46e4"
43
47
  }
package/src/index.spec.ts CHANGED
@@ -5,4 +5,5 @@ test('should export all methods', () => {
5
5
  expect(googleMaps.useGeocoder).toBeDefined();
6
6
  expect(googleMaps.useGoogleMaps).toBeDefined();
7
7
  expect(googleMaps.useMap).toBeDefined();
8
+ expect(googleMaps.usePlacesAutocomplete).toBeDefined();
8
9
  });
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { GoogleMapsProvider, useGoogleMaps } from './GoogleMapsProvider';
2
2
  export { useGeocoder } from './useGeocoder';
3
3
  export { useMap } from './useMap';
4
+ export { usePlacesAutocomplete } from './usePlacesAutocomplete';
@@ -0,0 +1,20 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ const debounce = <F extends (...args: any[]) => void>(
3
+ fn: F,
4
+ delay: number
5
+ ): ((this: ThisParameterType<F>, ...args: Parameters<F>) => void) => {
6
+ let timer: ReturnType<typeof setTimeout> | null;
7
+
8
+ function debounceFn(this: ThisParameterType<F>, ...args: Parameters<F>) {
9
+ if (timer !== null) {
10
+ clearTimeout(timer);
11
+ timer = null;
12
+ }
13
+
14
+ timer = setTimeout(() => fn.apply(this, args), delay);
15
+ }
16
+
17
+ return debounceFn;
18
+ };
19
+
20
+ export default debounce;
@@ -0,0 +1,192 @@
1
+ /* eslint-disable react-hooks/exhaustive-deps */
2
+ import { useGoogleMaps } from './../GoogleMapsProvider';
3
+
4
+ import { useCallback, useEffect, useRef, useState } from 'react';
5
+
6
+ import _debounce from './debounce';
7
+ import useLatest from './useLatest';
8
+
9
+ export interface HookArgs {
10
+ requestOptions?: Omit<google.maps.places.AutocompletionRequest, 'input'>;
11
+ debounce?: number;
12
+ cache?: number | false;
13
+ cacheKey?: string;
14
+ callbackName?: string;
15
+ defaultValue?: string;
16
+ initOnMount?: boolean;
17
+ }
18
+
19
+ type Suggestion = google.maps.places.AutocompletePrediction;
20
+
21
+ type Status = `${google.maps.places.PlacesServiceStatus}` | '';
22
+
23
+ interface Suggestions {
24
+ readonly loading: boolean;
25
+ readonly status: Status;
26
+ data: Suggestion[];
27
+ }
28
+
29
+ interface SetValue {
30
+ (val: string, shouldFetchData?: boolean): void;
31
+ }
32
+
33
+ interface HookReturn {
34
+ ready: boolean;
35
+ value: string;
36
+ suggestions: Suggestions;
37
+ setValue: SetValue;
38
+ clearSuggestions: () => void;
39
+ clearCache: () => void;
40
+ init: () => void;
41
+ }
42
+
43
+ export const loadApiErr = '💡 Google Maps Places API library must be loaded.';
44
+
45
+ export const usePlacesAutocomplete = ({
46
+ requestOptions,
47
+ debounce = 200,
48
+ cache = 24 * 60 * 60,
49
+ cacheKey,
50
+ callbackName,
51
+ defaultValue = '',
52
+ initOnMount = true,
53
+ }: HookArgs = {}): HookReturn => {
54
+ const [ready, setReady] = useState(false);
55
+ const [value, setVal] = useState(defaultValue);
56
+ const [suggestions, setSuggestions] = useState<Suggestions>({
57
+ loading: false,
58
+ status: '',
59
+ data: [],
60
+ });
61
+ const asRef = useRef<any>(null);
62
+ const requestOptionsRef = useLatest(requestOptions);
63
+ const { googleMaps } = useGoogleMaps();
64
+
65
+ const googleMapsRef = useLatest(googleMaps);
66
+
67
+ const upaCacheKey = cacheKey ? `upa-${cacheKey}` : 'upa';
68
+
69
+ const init = useCallback(() => {
70
+ if (asRef.current) return;
71
+
72
+ if (!googleMaps) {
73
+ return;
74
+ }
75
+
76
+ const { current: gMaps } = googleMapsRef;
77
+ const placesLib = gMaps?.places || googleMaps.places;
78
+
79
+ if (!placesLib) {
80
+ return;
81
+ }
82
+
83
+ asRef.current = new placesLib.AutocompleteService();
84
+ setReady(true);
85
+ }, [googleMaps]);
86
+
87
+ const clearSuggestions = useCallback(() => {
88
+ setSuggestions({ loading: false, status: '', data: [] });
89
+ }, []);
90
+
91
+ const clearCache = useCallback(() => {
92
+ try {
93
+ sessionStorage.removeItem(upaCacheKey);
94
+ } catch (error) {
95
+ // Skip exception
96
+ }
97
+ }, []);
98
+
99
+ const fetchPredictions = useCallback(
100
+ _debounce((val: string) => {
101
+ if (!val) {
102
+ clearSuggestions();
103
+ return;
104
+ }
105
+
106
+ setSuggestions((prevState) => ({ ...prevState, loading: true }));
107
+
108
+ let cachedData: Record<string, { data: Suggestion[]; maxAge: number }> =
109
+ {};
110
+
111
+ try {
112
+ cachedData = JSON.parse(sessionStorage.getItem(upaCacheKey) || '{}');
113
+ } catch (error) {
114
+ // Skip exception
115
+ }
116
+
117
+ if (cache) {
118
+ cachedData = Object.keys(cachedData).reduce(
119
+ (acc: typeof cachedData, key) => {
120
+ if (cachedData[key].maxAge - Date.now() >= 0)
121
+ acc[key] = cachedData[key];
122
+ return acc;
123
+ },
124
+ {}
125
+ );
126
+
127
+ if (cachedData[val]) {
128
+ setSuggestions({
129
+ loading: false,
130
+ status: 'OK',
131
+ data: cachedData[val].data,
132
+ });
133
+ return;
134
+ }
135
+ }
136
+
137
+ asRef?.current?.getPlacePredictions(
138
+ { ...requestOptionsRef.current, input: val },
139
+ (data: Suggestion[] | null, status: Status) => {
140
+ setSuggestions({ loading: false, status, data: data || [] });
141
+
142
+ if (cache && status === 'OK') {
143
+ cachedData[val] = {
144
+ data: data as Suggestion[],
145
+ maxAge: Date.now() + cache * 1000,
146
+ };
147
+
148
+ try {
149
+ sessionStorage.setItem(upaCacheKey, JSON.stringify(cachedData));
150
+ } catch (error) {
151
+ // Skip exception
152
+ }
153
+ }
154
+ }
155
+ );
156
+ }, debounce),
157
+ [debounce, clearSuggestions]
158
+ );
159
+
160
+ const setValue: SetValue = useCallback(
161
+ (val, shouldFetchData = true) => {
162
+ setVal(val);
163
+ if (asRef.current && shouldFetchData) fetchPredictions(val);
164
+ },
165
+ [fetchPredictions]
166
+ );
167
+
168
+ useEffect(() => {
169
+ if (!initOnMount) return () => null;
170
+
171
+ if (!googleMapsRef.current && !googleMaps && callbackName) {
172
+ (window as any)[callbackName] = init;
173
+ } else {
174
+ init();
175
+ }
176
+
177
+ return () => {
178
+ if ((window as any)[callbackName as string])
179
+ delete (window as any)[callbackName as string];
180
+ };
181
+ }, [callbackName, init]);
182
+
183
+ return {
184
+ ready,
185
+ value,
186
+ suggestions,
187
+ setValue,
188
+ clearSuggestions,
189
+ clearCache,
190
+ init,
191
+ };
192
+ };
@@ -0,0 +1,7 @@
1
+ import { RefObject, useRef } from 'react';
2
+
3
+ export default <T>(val: T): RefObject<T> => {
4
+ const ref = useRef(val);
5
+ ref.current = val;
6
+ return ref;
7
+ };
package/dist/esm/index.js DELETED
@@ -1,98 +0,0 @@
1
- // tsup.inject.js
2
- import * as React from "react";
3
-
4
- // src/GoogleMapsProvider.tsx
5
- import * as React2 from "react";
6
- import { useScript } from "@ttoss/hooks";
7
- var GoogleMapsContext = React2.createContext({
8
- status: "idle",
9
- googleMaps: null
10
- });
11
- var GoogleMapsProvider = ({
12
- children,
13
- apiKey,
14
- libraries,
15
- language
16
- }) => {
17
- const src = (() => {
18
- let srcTemp = `https://maps.googleapis.com/maps/api/js?key=${apiKey}`;
19
- if (libraries) {
20
- srcTemp = srcTemp + `&libraries=${libraries.join(",")}`;
21
- }
22
- if (language) {
23
- srcTemp = srcTemp + `&language=${language}`;
24
- }
25
- return srcTemp;
26
- })();
27
- const { status } = useScript(src);
28
- const googleMaps = React2.useMemo(() => {
29
- if (status === "ready" && window.google.maps) {
30
- return window.google.maps;
31
- }
32
- return null;
33
- }, [status]);
34
- const value = React2.useMemo(() => {
35
- if (status === "ready" && googleMaps) {
36
- return {
37
- status,
38
- googleMaps
39
- };
40
- }
41
- return {
42
- status,
43
- googleMaps: null
44
- };
45
- }, [googleMaps, status]);
46
- return /* @__PURE__ */ React2.createElement(GoogleMapsContext.Provider, {
47
- value
48
- }, children);
49
- };
50
- var useGoogleMaps = () => React2.useContext(GoogleMapsContext);
51
-
52
- // src/useGeocoder.ts
53
- import * as React3 from "react";
54
- var useGeocoder = () => {
55
- const { googleMaps } = useGoogleMaps();
56
- const [isGeocoderInitialized, setIsGeocoderInitialized] = React3.useState(false);
57
- const geocoder = React3.useMemo(() => {
58
- if (googleMaps) {
59
- const googleMapsGeocoder = new googleMaps.Geocoder();
60
- setIsGeocoderInitialized(true);
61
- return googleMapsGeocoder;
62
- }
63
- return null;
64
- }, [googleMaps]);
65
- return { geocoder, isGeocoderInitialized };
66
- };
67
-
68
- // src/useMap.ts
69
- import * as React4 from "react";
70
- import { useCallbackRef } from "use-callback-ref";
71
- var useMap = (options = {}) => {
72
- const [, forceUpdate] = React4.useState(0);
73
- const ref = useCallbackRef(null, () => forceUpdate((n) => n + 1));
74
- const { googleMaps } = useGoogleMaps();
75
- const map = React4.useMemo(() => {
76
- if (googleMaps && ref.current) {
77
- return new googleMaps.Map(ref.current, options);
78
- }
79
- return null;
80
- }, [googleMaps, ref.current]);
81
- const optionsStringify = JSON.stringify(options);
82
- React4.useEffect(() => {
83
- if (map) {
84
- const parsedOptions = JSON.parse(optionsStringify);
85
- map.setOptions(parsedOptions);
86
- }
87
- }, [optionsStringify, map]);
88
- return {
89
- map,
90
- ref
91
- };
92
- };
93
- export {
94
- GoogleMapsProvider,
95
- useGeocoder,
96
- useGoogleMaps,
97
- useMap
98
- };
package/dist/index.d.ts DELETED
@@ -1,47 +0,0 @@
1
- import * as React from 'react';
2
- import { ScriptStatus } from '@ttoss/hooks';
3
-
4
- declare type Extends<T, U extends T> = U;
5
- declare type GoogleMaps = typeof google.maps;
6
- declare type LoadedMapsStatus = Extends<ScriptStatus, 'ready'>;
7
- declare type NotLoadedMapStatus = Extends<ScriptStatus, 'idle' | 'error' | 'loading'>;
8
- declare type Libraries = 'places' | 'visualization' | 'drawing' | 'geometry';
9
- declare const GoogleMapsProvider: ({ children, apiKey, libraries, language, }: {
10
- children: React.ReactNode;
11
- apiKey: string;
12
- libraries?: Libraries[] | undefined;
13
- /**
14
- * https://developers.google.com/maps/faq#languagesupport
15
- */
16
- language?: string | undefined;
17
- }) => JSX.Element;
18
- /**
19
- *
20
- * @returns param.googleMaps: GoogleMaps - returns the google maps object which
21
- * provides access to the [Google Maps API](https://developers.google.com/maps/documentation/javascript/overview).
22
- */
23
- declare const useGoogleMaps: () => {
24
- status: LoadedMapsStatus;
25
- googleMaps: GoogleMaps;
26
- } | {
27
- status: NotLoadedMapStatus;
28
- googleMaps: null;
29
- };
30
-
31
- declare const useGeocoder: () => {
32
- geocoder: google.maps.Geocoder | null;
33
- isGeocoderInitialized: boolean;
34
- };
35
-
36
- declare const useMap: (options?: google.maps.MapOptions) => {
37
- /**
38
- * asss
39
- */
40
- map: google.maps.Map | null;
41
- /**
42
- * hhhh
43
- */
44
- ref: React.MutableRefObject<HTMLDivElement | null>;
45
- };
46
-
47
- export { GoogleMapsProvider, useGeocoder, useGoogleMaps, useMap };
package/dist/index.js DELETED
@@ -1,130 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
20
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
-
22
- // src/index.ts
23
- var src_exports = {};
24
- __export(src_exports, {
25
- GoogleMapsProvider: () => GoogleMapsProvider,
26
- useGeocoder: () => useGeocoder,
27
- useGoogleMaps: () => useGoogleMaps,
28
- useMap: () => useMap
29
- });
30
- module.exports = __toCommonJS(src_exports);
31
-
32
- // tsup.inject.js
33
- var React = __toESM(require("react"));
34
-
35
- // src/GoogleMapsProvider.tsx
36
- var React2 = __toESM(require("react"));
37
- var import_hooks = require("@ttoss/hooks");
38
- var GoogleMapsContext = React2.createContext({
39
- status: "idle",
40
- googleMaps: null
41
- });
42
- var GoogleMapsProvider = ({
43
- children,
44
- apiKey,
45
- libraries,
46
- language
47
- }) => {
48
- const src = (() => {
49
- let srcTemp = `https://maps.googleapis.com/maps/api/js?key=${apiKey}`;
50
- if (libraries) {
51
- srcTemp = srcTemp + `&libraries=${libraries.join(",")}`;
52
- }
53
- if (language) {
54
- srcTemp = srcTemp + `&language=${language}`;
55
- }
56
- return srcTemp;
57
- })();
58
- const { status } = (0, import_hooks.useScript)(src);
59
- const googleMaps = React2.useMemo(() => {
60
- if (status === "ready" && window.google.maps) {
61
- return window.google.maps;
62
- }
63
- return null;
64
- }, [status]);
65
- const value = React2.useMemo(() => {
66
- if (status === "ready" && googleMaps) {
67
- return {
68
- status,
69
- googleMaps
70
- };
71
- }
72
- return {
73
- status,
74
- googleMaps: null
75
- };
76
- }, [googleMaps, status]);
77
- return /* @__PURE__ */ React2.createElement(GoogleMapsContext.Provider, {
78
- value
79
- }, children);
80
- };
81
- var useGoogleMaps = () => React2.useContext(GoogleMapsContext);
82
-
83
- // src/useGeocoder.ts
84
- var React3 = __toESM(require("react"));
85
- var useGeocoder = () => {
86
- const { googleMaps } = useGoogleMaps();
87
- const [isGeocoderInitialized, setIsGeocoderInitialized] = React3.useState(false);
88
- const geocoder = React3.useMemo(() => {
89
- if (googleMaps) {
90
- const googleMapsGeocoder = new googleMaps.Geocoder();
91
- setIsGeocoderInitialized(true);
92
- return googleMapsGeocoder;
93
- }
94
- return null;
95
- }, [googleMaps]);
96
- return { geocoder, isGeocoderInitialized };
97
- };
98
-
99
- // src/useMap.ts
100
- var React4 = __toESM(require("react"));
101
- var import_use_callback_ref = require("use-callback-ref");
102
- var useMap = (options = {}) => {
103
- const [, forceUpdate] = React4.useState(0);
104
- const ref = (0, import_use_callback_ref.useCallbackRef)(null, () => forceUpdate((n) => n + 1));
105
- const { googleMaps } = useGoogleMaps();
106
- const map = React4.useMemo(() => {
107
- if (googleMaps && ref.current) {
108
- return new googleMaps.Map(ref.current, options);
109
- }
110
- return null;
111
- }, [googleMaps, ref.current]);
112
- const optionsStringify = JSON.stringify(options);
113
- React4.useEffect(() => {
114
- if (map) {
115
- const parsedOptions = JSON.parse(optionsStringify);
116
- map.setOptions(parsedOptions);
117
- }
118
- }, [optionsStringify, map]);
119
- return {
120
- map,
121
- ref
122
- };
123
- };
124
- // Annotate the CommonJS export names for ESM import in node:
125
- 0 && (module.exports = {
126
- GoogleMapsProvider,
127
- useGeocoder,
128
- useGoogleMaps,
129
- useMap
130
- });