@ttoss/google-maps 1.25.22 → 2.0.1

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/dist/esm/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import * as React from "react";
5
5
  import { useScript } from "@ttoss/react-hooks";
6
6
  import { jsx } from "react/jsx-runtime";
7
- var GoogleMapsContext = /*#__PURE__*/React.createContext({
7
+ var GoogleMapsContext = React.createContext({
8
8
  status: "idle",
9
9
  googleMaps: null
10
10
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ttoss/google-maps",
3
- "version": "1.25.22",
3
+ "version": "2.0.1",
4
4
  "author": "ttoss",
5
5
  "contributors": [
6
6
  "Pedro Arantes <pedro@arantespp.com> (https://arantespp.com/contact)",
@@ -11,10 +11,10 @@
11
11
  "url": "https://github.com/ttoss/ttoss.git",
12
12
  "directory": "packages/google-maps"
13
13
  },
14
+ "type": "module",
14
15
  "exports": {
15
16
  ".": {
16
17
  "import": "./dist/esm/index.js",
17
- "require": "./dist/index.js",
18
18
  "types": "./dist/index.d.ts"
19
19
  }
20
20
  },
@@ -25,20 +25,25 @@
25
25
  "dependencies": {
26
26
  "@types/google.maps": "^3.54.10",
27
27
  "use-callback-ref": "^1.3.0",
28
- "@ttoss/react-hooks": "^1.25.15"
28
+ "@ttoss/react-hooks": "^2.0.1"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "react": ">=16.8.0",
32
32
  "react-dom": ">=16.8.0"
33
33
  },
34
34
  "devDependencies": {
35
- "@types/react": "^18.3.3",
35
+ "@types/react": "^18.3.7",
36
36
  "jest": "^29.7.0",
37
37
  "react": "^18.3.1",
38
- "tsup": "^8.2.4",
39
- "@ttoss/config": "^1.32.9",
40
- "@ttoss/test-utils": "^2.1.13"
38
+ "tsup": "^8.3.0",
39
+ "@ttoss/config": "^1.32.10",
40
+ "@ttoss/test-utils": "^2.1.14"
41
41
  },
42
+ "keywords": [
43
+ "Google",
44
+ "Maps",
45
+ "React"
46
+ ],
42
47
  "publishConfig": {
43
48
  "access": "public",
44
49
  "provenance": true
@@ -46,6 +51,6 @@
46
51
  "gitHead": "2a911f70d465d6bffdd6589a62d17701f1026f01",
47
52
  "scripts": {
48
53
  "build": "tsup",
49
- "test": "jest"
54
+ "test": "jest --projects tests/unit"
50
55
  }
51
56
  }
package/dist/index.d.mts DELETED
@@ -1,78 +0,0 @@
1
- import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import * as React from 'react';
3
- import { ScriptStatus } from '@ttoss/react-hooks';
4
-
5
- type Extends<T, U extends T> = U;
6
- type GoogleMaps = typeof google.maps;
7
- type LoadedMapsStatus = Extends<ScriptStatus, 'ready'>;
8
- type NotLoadedMapStatus = Extends<ScriptStatus, 'idle' | 'error' | 'loading'>;
9
- type Libraries = 'places' | 'visualization' | 'drawing' | 'geometry';
10
- declare const GoogleMapsProvider: ({ children, apiKey, libraries, language, }: {
11
- children: React.ReactNode;
12
- apiKey: string;
13
- libraries?: Libraries[];
14
- /**
15
- * https://developers.google.com/maps/faq#languagesupport
16
- */
17
- language?: string;
18
- }) => react_jsx_runtime.JSX.Element;
19
- /**
20
- *
21
- * @returns param.googleMaps: GoogleMaps - returns the google maps object which
22
- * provides access to the [Google Maps API](https://developers.google.com/maps/documentation/javascript/overview).
23
- */
24
- declare const useGoogleMaps: () => {
25
- status: LoadedMapsStatus;
26
- googleMaps: GoogleMaps;
27
- } | {
28
- status: NotLoadedMapStatus;
29
- googleMaps: null;
30
- };
31
-
32
- declare const useGeocoder: () => {
33
- geocoder: google.maps.Geocoder | null;
34
- isGeocoderInitialized: boolean;
35
- };
36
-
37
- declare const useMap: (options?: google.maps.MapOptions) => {
38
- /**
39
- * asss
40
- */
41
- map: google.maps.Map | null;
42
- /**
43
- * hhhh
44
- */
45
- ref: React.MutableRefObject<HTMLDivElement | null>;
46
- };
47
-
48
- interface HookArgs {
49
- requestOptions?: Omit<google.maps.places.AutocompletionRequest, 'input'>;
50
- debounce?: number;
51
- cache?: number | false;
52
- cacheKey?: string;
53
- callbackName?: string;
54
- defaultValue?: string;
55
- initOnMount?: boolean;
56
- }
57
- type Suggestion = google.maps.places.AutocompletePrediction;
58
- type Status = `${google.maps.places.PlacesServiceStatus}` | '';
59
- interface Suggestions {
60
- readonly loading: boolean;
61
- readonly status: Status;
62
- data: Suggestion[];
63
- }
64
- interface SetValue {
65
- (val: string, shouldFetchData?: boolean): void;
66
- }
67
- interface HookReturn {
68
- ready: boolean;
69
- value: string;
70
- suggestions: Suggestions;
71
- setValue: SetValue;
72
- clearSuggestions: () => void;
73
- clearCache: () => void;
74
- init: () => void;
75
- }
76
- declare const usePlacesAutocomplete: ({ requestOptions, debounce, cache, cacheKey, callbackName, defaultValue, initOnMount, }?: HookArgs) => HookReturn;
77
-
78
- export { GoogleMapsProvider, useGeocoder, useGoogleMaps, useMap, usePlacesAutocomplete };
package/dist/index.js DELETED
@@ -1,319 +0,0 @@
1
- /** Powered by @ttoss/config. https://ttoss.dev/docs/modules/packages/config/ */
2
- "use strict";
3
-
4
- var __create = Object.create;
5
- var __defProp = Object.defineProperty;
6
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getProtoOf = Object.getPrototypeOf;
9
- var __hasOwnProp = Object.prototype.hasOwnProperty;
10
- var __export = (target, all) => {
11
- for (var name in all) __defProp(target, name, {
12
- get: all[name],
13
- enumerable: true
14
- });
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
19
- get: () => from[key],
20
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
21
- });
22
- }
23
- return to;
24
- };
25
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
- // If the importer is in node compatibility mode or this is not an ESM
27
- // file that has been converted to a CommonJS file using a Babel-
28
- // compatible transform (i.e. "__esModule" has not been set), then set
29
- // "default" to the CommonJS "module.exports" for node compatibility.
30
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
31
- value: mod,
32
- enumerable: true
33
- }) : target, mod));
34
- var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
35
- value: true
36
- }), mod);
37
-
38
- // src/index.ts
39
- var src_exports = {};
40
- __export(src_exports, {
41
- GoogleMapsProvider: () => GoogleMapsProvider,
42
- useGeocoder: () => useGeocoder,
43
- useGoogleMaps: () => useGoogleMaps,
44
- useMap: () => useMap,
45
- usePlacesAutocomplete: () => usePlacesAutocomplete
46
- });
47
- module.exports = __toCommonJS(src_exports);
48
-
49
- // src/GoogleMapsProvider.tsx
50
- var React = __toESM(require("react"));
51
- var import_react_hooks = require("@ttoss/react-hooks");
52
- var import_jsx_runtime = require("react/jsx-runtime");
53
- var GoogleMapsContext = React.createContext({
54
- status: "idle",
55
- googleMaps: null
56
- });
57
- var GoogleMapsProvider = ({
58
- children,
59
- apiKey,
60
- libraries,
61
- language
62
- }) => {
63
- const src = (() => {
64
- let srcTemp = `https://maps.googleapis.com/maps/api/js?key=${apiKey}`;
65
- if (libraries) {
66
- srcTemp = srcTemp + `&libraries=${libraries.join(",")}`;
67
- }
68
- if (language) {
69
- srcTemp = srcTemp + `&language=${language}`;
70
- }
71
- return srcTemp;
72
- })();
73
- const {
74
- status
75
- } = (0, import_react_hooks.useScript)(src);
76
- const googleMaps = React.useMemo(() => {
77
- if (status === "ready" && window.google.maps) {
78
- return window.google.maps;
79
- }
80
- return null;
81
- }, [status]);
82
- const value = React.useMemo(() => {
83
- if (status === "ready" && googleMaps) {
84
- return {
85
- status,
86
- googleMaps
87
- };
88
- }
89
- return {
90
- status,
91
- googleMaps: null
92
- };
93
- }, [googleMaps, status]);
94
- return /* @__PURE__ */(0, import_jsx_runtime.jsx)(GoogleMapsContext.Provider, {
95
- value,
96
- children
97
- });
98
- };
99
- var useGoogleMaps = () => {
100
- return React.useContext(GoogleMapsContext);
101
- };
102
-
103
- // src/useGeocoder.ts
104
- var React2 = __toESM(require("react"));
105
- var useGeocoder = () => {
106
- const {
107
- googleMaps
108
- } = useGoogleMaps();
109
- const [isGeocoderInitialized, setIsGeocoderInitialized] = React2.useState(false);
110
- const geocoder = React2.useMemo(() => {
111
- if (googleMaps) {
112
- const googleMapsGeocoder = new googleMaps.Geocoder();
113
- setIsGeocoderInitialized(true);
114
- return googleMapsGeocoder;
115
- }
116
- return null;
117
- }, [googleMaps]);
118
- return {
119
- geocoder,
120
- isGeocoderInitialized
121
- };
122
- };
123
-
124
- // src/useMap.ts
125
- var React3 = __toESM(require("react"));
126
- var import_use_callback_ref = require("use-callback-ref");
127
- var useMap = (options = {}) => {
128
- const [, forceUpdate] = React3.useState(0);
129
- const ref = (0, import_use_callback_ref.useCallbackRef)(null, () => {
130
- return forceUpdate(n => {
131
- return n + 1;
132
- });
133
- });
134
- const {
135
- googleMaps
136
- } = useGoogleMaps();
137
- const map = React3.useMemo(() => {
138
- if (googleMaps && ref.current) {
139
- return new googleMaps.Map(ref.current, options);
140
- }
141
- return null;
142
- }, [googleMaps, ref.current]);
143
- const optionsStringify = JSON.stringify(options);
144
- React3.useEffect(() => {
145
- if (map) {
146
- const parsedOptions = JSON.parse(optionsStringify);
147
- map.setOptions(parsedOptions);
148
- }
149
- }, [optionsStringify, map]);
150
- return {
151
- /**
152
- * asss
153
- */
154
- map,
155
- /**
156
- * hhhh
157
- */
158
- ref
159
- };
160
- };
161
-
162
- // src/usePlacesAutocomplete/index.ts
163
- var import_react2 = require("react");
164
-
165
- // src/usePlacesAutocomplete/debounce.ts
166
- var debounce = (fn, delay) => {
167
- let timer;
168
- function debounceFn(...args) {
169
- if (timer !== null) {
170
- clearTimeout(timer);
171
- timer = null;
172
- }
173
- timer = setTimeout(() => fn.apply(this, args), delay);
174
- }
175
- return debounceFn;
176
- };
177
- var debounce_default = debounce;
178
-
179
- // src/usePlacesAutocomplete/useLatest.ts
180
- var import_react = require("react");
181
- var useLatest_default = val => {
182
- const ref = (0, import_react.useRef)(val);
183
- ref.current = val;
184
- return ref;
185
- };
186
-
187
- // src/usePlacesAutocomplete/index.ts
188
- var usePlacesAutocomplete = ({
189
- requestOptions,
190
- debounce: debounce2 = 200,
191
- cache = 24 * 60 * 60,
192
- cacheKey,
193
- callbackName,
194
- defaultValue = "",
195
- initOnMount = true
196
- } = {}) => {
197
- const [ready, setReady] = (0, import_react2.useState)(false);
198
- const [value, setVal] = (0, import_react2.useState)(defaultValue);
199
- const [suggestions, setSuggestions] = (0, import_react2.useState)({
200
- loading: false,
201
- status: "",
202
- data: []
203
- });
204
- const asRef = (0, import_react2.useRef)(null);
205
- const requestOptionsRef = useLatest_default(requestOptions);
206
- const {
207
- googleMaps
208
- } = useGoogleMaps();
209
- const googleMapsRef = useLatest_default(googleMaps);
210
- const upaCacheKey = cacheKey ? `upa-${cacheKey}` : "upa";
211
- const init = (0, import_react2.useCallback)(() => {
212
- if (asRef.current) return;
213
- if (!googleMaps) {
214
- return;
215
- }
216
- const {
217
- current: gMaps
218
- } = googleMapsRef;
219
- const placesLib = gMaps?.places || googleMaps.places;
220
- if (!placesLib) {
221
- return;
222
- }
223
- asRef.current = new placesLib.AutocompleteService();
224
- setReady(true);
225
- }, [googleMaps]);
226
- const clearSuggestions = (0, import_react2.useCallback)(() => {
227
- setSuggestions({
228
- loading: false,
229
- status: "",
230
- data: []
231
- });
232
- }, []);
233
- const clearCache = (0, import_react2.useCallback)(() => {
234
- try {
235
- sessionStorage.removeItem(upaCacheKey);
236
- } catch (error) {}
237
- }, []);
238
- const fetchPredictions = (0, import_react2.useCallback)(debounce_default(val => {
239
- if (!val) {
240
- clearSuggestions();
241
- return;
242
- }
243
- setSuggestions(prevState => ({
244
- ...prevState,
245
- loading: true
246
- }));
247
- let cachedData = {};
248
- try {
249
- cachedData = JSON.parse(sessionStorage.getItem(upaCacheKey) || "{}");
250
- } catch (error) {}
251
- if (cache) {
252
- cachedData = Object.keys(cachedData).reduce((acc, key) => {
253
- if (cachedData[key].maxAge - Date.now() >= 0) acc[key] = cachedData[key];
254
- return acc;
255
- }, {});
256
- if (cachedData[val]) {
257
- setSuggestions({
258
- loading: false,
259
- status: "OK",
260
- data: cachedData[val].data
261
- });
262
- return;
263
- }
264
- }
265
- asRef?.current?.getPlacePredictions({
266
- ...requestOptionsRef.current,
267
- input: val
268
- }, (data, status) => {
269
- setSuggestions({
270
- loading: false,
271
- status,
272
- data: data || []
273
- });
274
- if (cache && status === "OK") {
275
- cachedData[val] = {
276
- data,
277
- maxAge: Date.now() + cache * 1e3
278
- };
279
- try {
280
- sessionStorage.setItem(upaCacheKey, JSON.stringify(cachedData));
281
- } catch (error) {}
282
- }
283
- });
284
- }, debounce2), [debounce2, clearSuggestions]);
285
- const setValue = (0, import_react2.useCallback)((val, shouldFetchData = true) => {
286
- setVal(val);
287
- if (asRef.current && shouldFetchData) fetchPredictions(val);
288
- }, [fetchPredictions]);
289
- (0, import_react2.useEffect)(() => {
290
- if (!initOnMount) {
291
- return () => null;
292
- }
293
- if (!googleMapsRef.current && !googleMaps && callbackName) {
294
- window[callbackName] = init;
295
- } else {
296
- init();
297
- }
298
- return () => {
299
- if (window[callbackName]) delete window[callbackName];
300
- };
301
- }, [callbackName, init]);
302
- return {
303
- ready,
304
- value,
305
- suggestions,
306
- setValue,
307
- clearSuggestions,
308
- clearCache,
309
- init
310
- };
311
- };
312
- // Annotate the CommonJS export names for ESM import in node:
313
- 0 && (module.exports = {
314
- GoogleMapsProvider,
315
- useGeocoder,
316
- useGoogleMaps,
317
- useMap,
318
- usePlacesAutocomplete
319
- });
@@ -1,83 +0,0 @@
1
- // import { renderHook, act } from '@testing-library/react-hooks';
2
- // import { useGoogleMaps } from '..';
3
-
4
- // const mapObject = { map: 'object' };
5
- // const googleMock = {
6
- // maps: {
7
- // Map: jest.fn().mockImplementation(() => mapObject),
8
- // },
9
- // };
10
-
11
- import { GoogleMapsProvider, useGoogleMaps } from './';
12
- import { act, render, screen } from '@ttoss/test-utils';
13
-
14
- const mapObject = { map: 'object' };
15
- const googleMock = {
16
- maps: {
17
- Map: jest.fn().mockImplementation(() => {
18
- return mapObject;
19
- }),
20
- },
21
- };
22
-
23
- beforeAll(() => {
24
- (global.google as unknown) = googleMock;
25
- });
26
-
27
- beforeEach(() => {
28
- document.querySelectorAll('script')[0]?.remove();
29
- });
30
-
31
- const RenderStatus = () => {
32
- const { status } = useGoogleMaps();
33
- return (
34
- <div>
35
- <span>{status}</span>
36
- </div>
37
- );
38
- };
39
-
40
- const loadEvent = new Event('load');
41
-
42
- const apiKey = 'apiKey';
43
-
44
- test('should display correct status', () => {
45
- render(
46
- <GoogleMapsProvider apiKey={apiKey}>
47
- <RenderStatus />
48
- </GoogleMapsProvider>
49
- );
50
-
51
- expect(screen.getByText('loading')).toBeInTheDocument();
52
-
53
- act(() => {
54
- document.querySelectorAll('script')[0].dispatchEvent(loadEvent);
55
- });
56
-
57
- expect(screen.getByText('ready')).toBeInTheDocument();
58
- });
59
-
60
- test.each([
61
- [{ apiKey }, `https://maps.googleapis.com/maps/api/js?key=${apiKey}`],
62
- [
63
- { apiKey, language: 'pt-BR' },
64
- `https://maps.googleapis.com/maps/api/js?key=${apiKey}&language=pt-BR`,
65
- ],
66
- [
67
- { apiKey, language: 'pt-BR', libraries: ['places'] },
68
- `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places&language=pt-BR`,
69
- ],
70
- [
71
- { apiKey, language: 'pt-BR', libraries: ['places', 'geometry'] },
72
- `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places,geometry&language=pt-BR`,
73
- ],
74
- ])('Google Maps API src %#', (props, src) => {
75
- render(
76
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
- <GoogleMapsProvider {...(props as any)}>
78
- <RenderStatus />
79
- </GoogleMapsProvider>
80
- );
81
-
82
- expect(document.querySelectorAll('script')[0].src).toEqual(src);
83
- });
package/src/index.spec.ts DELETED
@@ -1,9 +0,0 @@
1
- import * as googleMaps from './index';
2
-
3
- test('should export all methods', () => {
4
- expect(googleMaps.GoogleMapsProvider).toBeDefined();
5
- expect(googleMaps.useGeocoder).toBeDefined();
6
- expect(googleMaps.useGoogleMaps).toBeDefined();
7
- expect(googleMaps.useMap).toBeDefined();
8
- expect(googleMaps.usePlacesAutocomplete).toBeDefined();
9
- });