google-places-autocomplete-hook 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ninad Sutrave
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,135 @@
1
- # Temporary Holding Version
1
+ # google-places-autocomplete-hook
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/google-places-autocomplete-hook)](https://www.npmjs.com/package/google-places-autocomplete-hook)
4
+ [![ci](https://github.com/ninadsutrave/google-places-autocomplete-hook/actions/workflows/ci.yml/badge.svg)](https://github.com/ninadsutrave/google-places-autocomplete-hook/actions/workflows/ci.yml)
5
+ [![size](https://img.shields.io/bundlejs/size/google-places-autocomplete-hook)](https://bundlejs.com/?q=google-places-autocomplete-hook)
6
+ [![license](https://img.shields.io/npm/l/google-places-autocomplete-hook)](LICENSE)
7
+
8
+ A small React hook for Google Places Autocomplete on the **Places API (New)**.
9
+
10
+ Google moved the old Places API and `AutocompleteService` to legacy status on 1 March 2025, and since October 2026 the legacy Places API can no longer be enabled on new Google Cloud projects. Popular hooks such as `use-places-autocomplete` still depend on it, so they don't work for a new project. This package uses the new `AutocompleteSuggestion` API instead. It keeps one session token per search, so typing and the final details request are billed as a session rather than request by request. It also includes a [drop-in mode](#migrating-from-use-places-autocomplete) for `use-places-autocomplete`.
11
+
12
+ - Headless: bring your own input and list
13
+ - Session tokens handled for you
14
+ - Debounced, ignores out-of-order responses, safe to unmount mid-request
15
+ - TypeScript types without needing `@types/google.maps`
16
+ - React 16.8 to 19, works with server rendering, no dependencies
17
+
18
+ On the server, [google-maps-fetch](https://github.com/ninadsutrave/google-maps-fetch) is the companion package: a small client for Places, Routes, Geocoding and the other Maps web APIs, with a drop-in replacement for `@googlemaps/google-maps-services-js`.
19
+
20
+ ## Install
21
+
22
+ ```sh
23
+ npm install google-places-autocomplete-hook
24
+ ```
25
+
26
+ Enable **Places API (New)** for your key in Google Cloud, then load the Maps JavaScript API:
27
+
28
+ ```html
29
+ <script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&loading=async"></script>
30
+ ```
31
+
32
+ Any loader that defines `google.maps.importLibrary` works too. The hook loads the `places` library itself.
33
+
34
+ ## Usage
35
+
36
+ ```jsx
37
+ import { usePlaces } from 'google-places-autocomplete-hook'
38
+
39
+ export function PlaceSearch() {
40
+ const { ready, value, setValue, suggestions, status, clearSuggestions, getPlace } = usePlaces({
41
+ request: { includedRegionCodes: ['in'] },
42
+ })
43
+
44
+ const select = async (suggestion) => {
45
+ setValue(suggestion.text, false)
46
+ clearSuggestions()
47
+ const place = await getPlace(suggestion, ['formattedAddress', 'location'])
48
+ console.log(place.formattedAddress, place.location.lat(), place.location.lng())
49
+ }
50
+
51
+ return (
52
+ <div>
53
+ <input value={value} onChange={(e) => setValue(e.target.value)} disabled={!ready} placeholder="Search a place" />
54
+ {status === 'ok' && (
55
+ <ul>
56
+ {suggestions.map((s) => (
57
+ <li key={s.placeId} onClick={() => select(s)}>
58
+ <strong>{s.mainText}</strong> <small>{s.secondaryText}</small>
59
+ </li>
60
+ ))}
61
+ </ul>
62
+ )}
63
+ </div>
64
+ )
65
+ }
66
+ ```
67
+
68
+ ### Options
69
+
70
+ | Option | Default | |
71
+ | :------------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
72
+ | `request` | | Sent with every request: `includedRegionCodes`, `includedPrimaryTypes`, `language`, `region`, `locationBias`, `locationRestriction`, `origin`, ... ([reference](https://developers.google.com/maps/documentation/javascript/reference/autocomplete-data#AutocompleteRequest)) |
73
+ | `debounce` | `200` | Milliseconds to wait after typing |
74
+ | `minLength` | `1` | Shortest input that fetches suggestions |
75
+ | `defaultValue` | `''` | |
76
+ | `initOnMount` | `true` | Load the places library on mount |
77
+
78
+ ### Returns
79
+
80
+ | | |
81
+ | :--------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------- |
82
+ | `ready` | The places library has loaded |
83
+ | `value`, `setValue(value, shouldFetch = true)` | The input value. Pass `false` to set it without fetching, for example after a selection; that also ends the search's session |
84
+ | `suggestions` | `{ placeId, text, mainText, secondaryText, matches, mainTextMatches, types, distanceMeters, prediction }[]` |
85
+ | `status` | `'idle'`, `'ok'`, `'zero-results'` or `'error'` |
86
+ | `loading`, `error` | |
87
+ | `clearSuggestions()` | Empty the list and ignore any request in flight |
88
+ | `getPlace(suggestion, fields?)` | Fetch place details, ending the session the suggestion came from. Default fields: `id`, `formattedAddress`, `location` |
89
+ | `init()` | Load the library, if the Maps script loads after the component mounts |
90
+
91
+ ## Sessions and billing
92
+
93
+ Every request while the user types shares one session token. A suggestion remembers the session it came from, so `getPlace` ends that session whenever you call it, and `setValue(text, false)` (a selection or a reset) closes the current search so the next keystroke starts a new one. You never handle tokens yourself.
94
+
95
+ What Google charges for a session depends on how it ends ([session pricing](https://developers.google.com/maps/documentation/places/web-service/session-pricing)):
96
+
97
+ - **`getPlace` with Essentials fields only** (the default: `id`, `formattedAddress`, `location`; also `viewport`, `addressComponents`, `types`): the first 12 autocomplete requests in the session are billed per request, any beyond that are free, and the details request is billed at Essentials.
98
+ - **`getPlace` with any Pro or Enterprise field** (`displayName`, `rating`, phone numbers, website, ...): every autocomplete request is free, and the details request is billed at Enterprise + Atmosphere, whatever else you asked for.
99
+ - **No `getPlace`**, for example when you only need the suggestion's text or you geocode the address instead: every autocomplete request is billed per request.
100
+
101
+ So for a box that only needs an address and coordinates, the defaults are the cheapest option. If you need a display name or more, one details request at the top tier buys free autocomplete ([field tiers](https://developers.google.com/maps/documentation/javascript/place-class-data-fields)).
102
+
103
+ ## Migrating from use-places-autocomplete
104
+
105
+ Change the import:
106
+
107
+ ```diff
108
+ - import usePlacesAutocomplete, { getDetails, getGeocode, getLatLng, getZipCode } from 'use-places-autocomplete'
109
+ + import usePlacesAutocomplete, { getDetails, getGeocode, getLatLng, getZipCode } from 'google-places-autocomplete-hook/compat'
110
+ ```
111
+
112
+ The hook returns the same `{ ready, value, suggestions: { loading, status, data }, setValue, clearSuggestions, clearCache, init }`. Each item in `data` has the legacy prediction shape: `description`, `place_id`, `structured_formatting`, `matched_substrings`, `terms` and `types`.
113
+
114
+ Differences:
115
+
116
+ - **`requestOptions`** is converted: `componentRestrictions.country` becomes `includedRegionCodes`, `types` becomes `includedPrimaryTypes`, and `location` with `radius` or `bounds` becomes `locationBias`. Google's new API accepts a different list of types, so check yours ([supported types](https://developers.google.com/maps/documentation/places/web-service/place-types)).
117
+ - **`getDetails`** asks for `place_id`, `formatted_address`, `geometry` and `address_components` unless you pass `fields`, all in Google's cheapest tier. The old version asked for every field and was billed for all of them. Adding `name` or any other Pro or Enterprise field bills the details request at Enterprise + Atmosphere, which in return makes the session's autocomplete requests free (see [Sessions and billing](#sessions-and-billing)). For a place the hook suggested, the details are fetched through that suggestion, which ends its session; the `language` option then has no effect, since the suggestion already has the hook's language.
118
+ - **`getGeocode`** still works, but it doesn't end the autocomplete session, so those requests are billed one by one. Use `getDetails` with `geometry` and `getLatLng` if you only need coordinates.
119
+ - **`cache`, `cacheKey` and `googleMaps`** are accepted and ignored.
120
+ - **`status`** is one of `''`, `'OK'`, `'ZERO_RESULTS'` or `'UNKNOWN_ERROR'`; the type also allows the other legacy values so existing comparisons compile.
121
+ - **`types`**: `address` becomes the street-level types; `geocode` and `establishment` have no equivalent in the new API, so no type filter is applied for them.
122
+
123
+ ## Example
124
+
125
+ [`example/`](example) has an accessible search box with keyboard navigation, built with `usePlaces`.
126
+
127
+ ## Contributing
128
+
129
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Please follow the [code of conduct](CODE_OF_CONDUCT.md), and report security issues as described in [SECURITY.md](SECURITY.md).
130
+
131
+ ## License
132
+
133
+ [MIT](LICENSE)
134
+
135
+ This is an independent project, not affiliated with or endorsed by Google. Google Maps is a trademark of Google LLC.
@@ -0,0 +1,5 @@
1
+ {
2
+ "main": "../dist/compat.cjs",
3
+ "module": "../dist/compat.js",
4
+ "types": "../dist/compat.d.ts"
5
+ }
@@ -0,0 +1,154 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/places.ts
2
+ var getMaps = () => {
3
+ var _a;
4
+ return typeof window === "undefined" ? void 0 : (_a = window.google) == null ? void 0 : _a.maps;
5
+ };
6
+ var notLoaded = () => new Error("google-places-autocomplete-hook: the Google Maps JavaScript API is not loaded");
7
+ var isLoaded = () => {
8
+ var _a;
9
+ return typeof ((_a = getMaps()) == null ? void 0 : _a.importLibrary) === "function";
10
+ };
11
+ var loadLibrary = (name) => {
12
+ var _a;
13
+ const importLibrary = (_a = getMaps()) == null ? void 0 : _a.importLibrary;
14
+ return importLibrary ? importLibrary(name) : Promise.reject(notLoaded());
15
+ };
16
+ var places;
17
+ var loadPlaces = () => {
18
+ if (!isLoaded()) return Promise.reject(notLoaded());
19
+ if (!places) {
20
+ places = loadLibrary("places").catch((error) => {
21
+ places = void 0;
22
+ throw error;
23
+ });
24
+ }
25
+ return places;
26
+ };
27
+ var toSuggestion = (prediction) => {
28
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
29
+ return {
30
+ placeId: prediction.placeId,
31
+ text: prediction.text.text,
32
+ matches: (_a = prediction.text.matches) != null ? _a : [],
33
+ mainText: (_c = (_b = prediction.mainText) == null ? void 0 : _b.text) != null ? _c : prediction.text.text,
34
+ mainTextMatches: (_e = (_d = prediction.mainText) == null ? void 0 : _d.matches) != null ? _e : [],
35
+ secondaryText: (_g = (_f = prediction.secondaryText) == null ? void 0 : _f.text) != null ? _g : "",
36
+ types: (_h = prediction.types) != null ? _h : [],
37
+ distanceMeters: (_i = prediction.distanceMeters) != null ? _i : void 0,
38
+ prediction
39
+ };
40
+ };
41
+ var createSession = () => {
42
+ let token;
43
+ return {
44
+ token: (library) => token != null ? token : token = new library.AutocompleteSessionToken()
45
+ };
46
+ };
47
+ var sessionOf = /* @__PURE__ */ new WeakMap();
48
+
49
+ // src/usePlaces.ts
50
+ var _react = require('react');
51
+ var idle = { status: "idle", suggestions: [], loading: false, error: void 0 };
52
+ var useIsomorphicLayoutEffect = typeof window === "undefined" ? _react.useEffect : _react.useLayoutEffect;
53
+ var defaultFields = Object.freeze(["id", "formattedAddress", "location"]);
54
+ function usePlaces({
55
+ request,
56
+ debounce = 200,
57
+ minLength = 1,
58
+ defaultValue = "",
59
+ initOnMount = true
60
+ } = {}) {
61
+ const [ready, setReady] = _react.useState.call(void 0, false);
62
+ const [value, setValueState] = _react.useState.call(void 0, defaultValue);
63
+ const [state, setState] = _react.useState.call(void 0, idle);
64
+ const session = _react.useRef.call(void 0, null);
65
+ if (session.current == null) session.current = createSession();
66
+ const latest = _react.useRef.call(void 0, 0);
67
+ const timer = _react.useRef.call(void 0, void 0);
68
+ const mounted = _react.useRef.call(void 0, false);
69
+ const options = _react.useRef.call(void 0, request);
70
+ useIsomorphicLayoutEffect(() => {
71
+ options.current = request;
72
+ });
73
+ const init = _react.useCallback.call(void 0, () => {
74
+ if (!isLoaded()) return;
75
+ loadPlaces().then(
76
+ () => mounted.current && setReady(true),
77
+ (error) => mounted.current && setState({ ...idle, status: "error", error })
78
+ );
79
+ }, []);
80
+ _react.useEffect.call(void 0, () => {
81
+ mounted.current = true;
82
+ let poll;
83
+ if (initOnMount) {
84
+ if (isLoaded()) init();
85
+ else
86
+ poll = setInterval(() => {
87
+ if (!isLoaded()) return;
88
+ clearInterval(poll);
89
+ init();
90
+ }, 100);
91
+ }
92
+ return () => {
93
+ mounted.current = false;
94
+ clearTimeout(timer.current);
95
+ clearInterval(poll);
96
+ };
97
+ }, [init, initOnMount]);
98
+ const fetchSuggestions = _react.useCallback.call(void 0, async (input) => {
99
+ const id = ++latest.current;
100
+ const current = session.current;
101
+ setState((prev) => ({ ...prev, loading: true }));
102
+ try {
103
+ const library = await loadPlaces();
104
+ const { suggestions } = await library.AutocompleteSuggestion.fetchAutocompleteSuggestions({
105
+ ...options.current,
106
+ input,
107
+ sessionToken: current.token(library)
108
+ });
109
+ if (id !== latest.current || !mounted.current) return;
110
+ const data = suggestions.flatMap((s) => s.placePrediction ? [toSuggestion(s.placePrediction)] : []);
111
+ for (const s of data) sessionOf.set(s.prediction, current);
112
+ setReady(true);
113
+ setState({ status: data.length ? "ok" : "zero-results", suggestions: data, loading: false, error: void 0 });
114
+ } catch (error) {
115
+ if (id !== latest.current || !mounted.current) return;
116
+ setState({ ...idle, status: "error", error });
117
+ }
118
+ }, []);
119
+ const clearSuggestions = _react.useCallback.call(void 0, () => {
120
+ latest.current++;
121
+ clearTimeout(timer.current);
122
+ setState(idle);
123
+ }, []);
124
+ const setValue = _react.useCallback.call(void 0,
125
+ (next, shouldFetch = true) => {
126
+ setValueState(next);
127
+ clearTimeout(timer.current);
128
+ if (!shouldFetch) {
129
+ session.current = createSession();
130
+ return;
131
+ }
132
+ if (next.trim().length < minLength) return clearSuggestions();
133
+ timer.current = setTimeout(() => fetchSuggestions(next), debounce);
134
+ },
135
+ [debounce, minLength, fetchSuggestions, clearSuggestions]
136
+ );
137
+ const getPlace = _react.useCallback.call(void 0, async (suggestion, fields = defaultFields) => {
138
+ const owner = sessionOf.get(suggestion.prediction);
139
+ if (!owner || owner === session.current) session.current = createSession();
140
+ const place = suggestion.prediction.toPlace();
141
+ await place.fetchFields({ fields: [...fields] });
142
+ return place;
143
+ }, []);
144
+ return { ready, value, setValue, ...state, clearSuggestions, getPlace, init };
145
+ }
146
+
147
+
148
+
149
+
150
+
151
+
152
+
153
+
154
+ exports.isLoaded = isLoaded; exports.loadLibrary = loadLibrary; exports.loadPlaces = loadPlaces; exports.toSuggestion = toSuggestion; exports.defaultFields = defaultFields; exports.usePlaces = usePlaces;
@@ -0,0 +1,154 @@
1
+ // src/places.ts
2
+ var getMaps = () => {
3
+ var _a;
4
+ return typeof window === "undefined" ? void 0 : (_a = window.google) == null ? void 0 : _a.maps;
5
+ };
6
+ var notLoaded = () => new Error("google-places-autocomplete-hook: the Google Maps JavaScript API is not loaded");
7
+ var isLoaded = () => {
8
+ var _a;
9
+ return typeof ((_a = getMaps()) == null ? void 0 : _a.importLibrary) === "function";
10
+ };
11
+ var loadLibrary = (name) => {
12
+ var _a;
13
+ const importLibrary = (_a = getMaps()) == null ? void 0 : _a.importLibrary;
14
+ return importLibrary ? importLibrary(name) : Promise.reject(notLoaded());
15
+ };
16
+ var places;
17
+ var loadPlaces = () => {
18
+ if (!isLoaded()) return Promise.reject(notLoaded());
19
+ if (!places) {
20
+ places = loadLibrary("places").catch((error) => {
21
+ places = void 0;
22
+ throw error;
23
+ });
24
+ }
25
+ return places;
26
+ };
27
+ var toSuggestion = (prediction) => {
28
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
29
+ return {
30
+ placeId: prediction.placeId,
31
+ text: prediction.text.text,
32
+ matches: (_a = prediction.text.matches) != null ? _a : [],
33
+ mainText: (_c = (_b = prediction.mainText) == null ? void 0 : _b.text) != null ? _c : prediction.text.text,
34
+ mainTextMatches: (_e = (_d = prediction.mainText) == null ? void 0 : _d.matches) != null ? _e : [],
35
+ secondaryText: (_g = (_f = prediction.secondaryText) == null ? void 0 : _f.text) != null ? _g : "",
36
+ types: (_h = prediction.types) != null ? _h : [],
37
+ distanceMeters: (_i = prediction.distanceMeters) != null ? _i : void 0,
38
+ prediction
39
+ };
40
+ };
41
+ var createSession = () => {
42
+ let token;
43
+ return {
44
+ token: (library) => token != null ? token : token = new library.AutocompleteSessionToken()
45
+ };
46
+ };
47
+ var sessionOf = /* @__PURE__ */ new WeakMap();
48
+
49
+ // src/usePlaces.ts
50
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
51
+ var idle = { status: "idle", suggestions: [], loading: false, error: void 0 };
52
+ var useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
53
+ var defaultFields = Object.freeze(["id", "formattedAddress", "location"]);
54
+ function usePlaces({
55
+ request,
56
+ debounce = 200,
57
+ minLength = 1,
58
+ defaultValue = "",
59
+ initOnMount = true
60
+ } = {}) {
61
+ const [ready, setReady] = useState(false);
62
+ const [value, setValueState] = useState(defaultValue);
63
+ const [state, setState] = useState(idle);
64
+ const session = useRef(null);
65
+ if (session.current == null) session.current = createSession();
66
+ const latest = useRef(0);
67
+ const timer = useRef(void 0);
68
+ const mounted = useRef(false);
69
+ const options = useRef(request);
70
+ useIsomorphicLayoutEffect(() => {
71
+ options.current = request;
72
+ });
73
+ const init = useCallback(() => {
74
+ if (!isLoaded()) return;
75
+ loadPlaces().then(
76
+ () => mounted.current && setReady(true),
77
+ (error) => mounted.current && setState({ ...idle, status: "error", error })
78
+ );
79
+ }, []);
80
+ useEffect(() => {
81
+ mounted.current = true;
82
+ let poll;
83
+ if (initOnMount) {
84
+ if (isLoaded()) init();
85
+ else
86
+ poll = setInterval(() => {
87
+ if (!isLoaded()) return;
88
+ clearInterval(poll);
89
+ init();
90
+ }, 100);
91
+ }
92
+ return () => {
93
+ mounted.current = false;
94
+ clearTimeout(timer.current);
95
+ clearInterval(poll);
96
+ };
97
+ }, [init, initOnMount]);
98
+ const fetchSuggestions = useCallback(async (input) => {
99
+ const id = ++latest.current;
100
+ const current = session.current;
101
+ setState((prev) => ({ ...prev, loading: true }));
102
+ try {
103
+ const library = await loadPlaces();
104
+ const { suggestions } = await library.AutocompleteSuggestion.fetchAutocompleteSuggestions({
105
+ ...options.current,
106
+ input,
107
+ sessionToken: current.token(library)
108
+ });
109
+ if (id !== latest.current || !mounted.current) return;
110
+ const data = suggestions.flatMap((s) => s.placePrediction ? [toSuggestion(s.placePrediction)] : []);
111
+ for (const s of data) sessionOf.set(s.prediction, current);
112
+ setReady(true);
113
+ setState({ status: data.length ? "ok" : "zero-results", suggestions: data, loading: false, error: void 0 });
114
+ } catch (error) {
115
+ if (id !== latest.current || !mounted.current) return;
116
+ setState({ ...idle, status: "error", error });
117
+ }
118
+ }, []);
119
+ const clearSuggestions = useCallback(() => {
120
+ latest.current++;
121
+ clearTimeout(timer.current);
122
+ setState(idle);
123
+ }, []);
124
+ const setValue = useCallback(
125
+ (next, shouldFetch = true) => {
126
+ setValueState(next);
127
+ clearTimeout(timer.current);
128
+ if (!shouldFetch) {
129
+ session.current = createSession();
130
+ return;
131
+ }
132
+ if (next.trim().length < minLength) return clearSuggestions();
133
+ timer.current = setTimeout(() => fetchSuggestions(next), debounce);
134
+ },
135
+ [debounce, minLength, fetchSuggestions, clearSuggestions]
136
+ );
137
+ const getPlace = useCallback(async (suggestion, fields = defaultFields) => {
138
+ const owner = sessionOf.get(suggestion.prediction);
139
+ if (!owner || owner === session.current) session.current = createSession();
140
+ const place = suggestion.prediction.toPlace();
141
+ await place.fetchFields({ fields: [...fields] });
142
+ return place;
143
+ }, []);
144
+ return { ready, value, setValue, ...state, clearSuggestions, getPlace, init };
145
+ }
146
+
147
+ export {
148
+ isLoaded,
149
+ loadLibrary,
150
+ loadPlaces,
151
+ toSuggestion,
152
+ defaultFields,
153
+ usePlaces
154
+ };
@@ -0,0 +1,206 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+ var _chunkGKD4BH53cjs = require('./chunk-GKD4BH53.cjs');
6
+
7
+ // src/compat.ts
8
+ var _react = require('react');
9
+ var addressTypes = ["street_address", "premise", "subpremise", "route"];
10
+ var primaryTypes = (types) => {
11
+ if (types.some((t) => t === "geocode" || t === "establishment")) return void 0;
12
+ return [...new Set(types.flatMap((t) => t === "address" ? addressTypes : [t]))].slice(0, 5);
13
+ };
14
+ var toAutocompleteRequest = (options = {}) => {
15
+ const { componentRestrictions, types, location, radius, bounds, offset, sessionToken, ...rest } = options;
16
+ const request = { ...rest };
17
+ if (componentRestrictions == null ? void 0 : componentRestrictions.country) request.includedRegionCodes = [].concat(componentRestrictions.country);
18
+ if (types == null ? void 0 : types.length) {
19
+ const primary = primaryTypes(types);
20
+ if (primary) request.includedPrimaryTypes = primary;
21
+ }
22
+ if (!request.locationBias && location && radius != null) request.locationBias = { center: location, radius };
23
+ if (!request.locationBias && bounds) request.locationBias = bounds;
24
+ if (offset != null) request.inputOffset = offset;
25
+ return request;
26
+ };
27
+ var toSubstrings = (ranges) => ranges.map((r) => ({ offset: r.startOffset, length: r.endOffset - r.startOffset }));
28
+ var toTerms = (description) => {
29
+ let offset = 0;
30
+ return description.split(", ").map((value2) => {
31
+ const term = { offset, value: value2 };
32
+ offset += value2.length + 2;
33
+ return term;
34
+ });
35
+ };
36
+ var toAutocompletePrediction = (s) => ({
37
+ description: s.text,
38
+ place_id: s.placeId,
39
+ types: s.types,
40
+ matched_substrings: toSubstrings(s.matches),
41
+ structured_formatting: {
42
+ main_text: s.mainText,
43
+ main_text_matched_substrings: toSubstrings(s.mainTextMatches),
44
+ secondary_text: s.secondaryText
45
+ },
46
+ terms: toTerms(s.text),
47
+ ...s.distanceMeters != null ? { distance_meters: s.distanceMeters } : {}
48
+ });
49
+ var recent = /* @__PURE__ */ new Map();
50
+ var forget = (owner) => {
51
+ for (const [id, list] of recent) {
52
+ const kept = list.filter((s) => s.owner !== owner);
53
+ if (kept.length) recent.set(id, kept);
54
+ else recent.delete(id);
55
+ }
56
+ };
57
+ var remember = (shown) => {
58
+ var _a;
59
+ const id = shown.suggestion.placeId;
60
+ recent.set(id, [...(_a = recent.get(id)) != null ? _a : [], shown]);
61
+ };
62
+ var takeShown = (id) => {
63
+ const list = recent.get(id);
64
+ if (!(list == null ? void 0 : list.length)) return void 0;
65
+ const shown = list.pop();
66
+ if (list.length) recent.set(id, list);
67
+ else recent.delete(id);
68
+ return shown;
69
+ };
70
+ function usePlacesAutocomplete({
71
+ requestOptions,
72
+ debounce = 200,
73
+ defaultValue = "",
74
+ initOnMount = true,
75
+ callbackName
76
+ } = {}) {
77
+ const places = _chunkGKD4BH53cjs.usePlaces.call(void 0, { request: toAutocompleteRequest(requestOptions), debounce, defaultValue, initOnMount });
78
+ const { suggestions, getPlace, init } = places;
79
+ const [owner] = _react.useState.call(void 0, () => /* @__PURE__ */ Symbol("usePlacesAutocomplete"));
80
+ _react.useEffect.call(void 0, () => {
81
+ if (!suggestions.length) return;
82
+ forget(owner);
83
+ for (const suggestion of suggestions) remember({ owner, suggestion, getPlace });
84
+ }, [owner, suggestions, getPlace]);
85
+ _react.useEffect.call(void 0, () => () => forget(owner), [owner]);
86
+ _react.useEffect.call(void 0, () => {
87
+ if (!callbackName) return;
88
+ const w = window;
89
+ w[callbackName] = init;
90
+ return () => {
91
+ if (w[callbackName] === init) delete w[callbackName];
92
+ };
93
+ }, [callbackName, init]);
94
+ const status = { idle: "", ok: "OK", "zero-results": "ZERO_RESULTS", error: "UNKNOWN_ERROR" }[places.status];
95
+ const data = _react.useMemo.call(void 0, () => suggestions.map(toAutocompletePrediction), [suggestions]);
96
+ return {
97
+ ready: places.ready,
98
+ value: places.value,
99
+ suggestions: { loading: places.loading, status, data },
100
+ setValue: places.setValue,
101
+ clearSuggestions: places.clearSuggestions,
102
+ clearCache: () => {
103
+ },
104
+ init
105
+ };
106
+ }
107
+ var fieldNames = {
108
+ place_id: "id",
109
+ name: "displayName",
110
+ formatted_address: "formattedAddress",
111
+ adr_address: "adrFormatAddress",
112
+ geometry: "location",
113
+ address_components: "addressComponents",
114
+ types: "types",
115
+ url: "googleMapsURI",
116
+ website: "websiteURI",
117
+ international_phone_number: "internationalPhoneNumber",
118
+ formatted_phone_number: "nationalPhoneNumber",
119
+ rating: "rating",
120
+ user_ratings_total: "userRatingCount",
121
+ utc_offset: "utcOffsetMinutes",
122
+ utc_offset_minutes: "utcOffsetMinutes",
123
+ business_status: "businessStatus",
124
+ price_level: "priceLevel",
125
+ opening_hours: "regularOpeningHours",
126
+ secondary_opening_hours: "regularSecondaryOpeningHours",
127
+ photo: "photos",
128
+ photos: "photos",
129
+ review: "reviews",
130
+ reviews: "reviews",
131
+ plus_code: "plusCode",
132
+ icon: "svgIconMaskURI",
133
+ icon_mask_base_uri: "svgIconMaskURI",
134
+ icon_background_color: "iconBackgroundColor",
135
+ editorial_summary: "editorialSummary",
136
+ wheelchair_accessible_entrance: "accessibilityOptions"
137
+ };
138
+ var toPlaceResult = (place, fields) => {
139
+ var _a;
140
+ const result = {};
141
+ for (const field of fields) {
142
+ const name = (_a = fieldNames[field]) != null ? _a : field;
143
+ const value2 = place[name];
144
+ if (value2 === void 0) continue;
145
+ if (field === "geometry") result.geometry = { location: value2, ...place.viewport ? { viewport: place.viewport } : {} };
146
+ else if (field === "address_components")
147
+ result.address_components = value2.map((c) => {
148
+ var _a2, _b;
149
+ return {
150
+ long_name: (_a2 = c.longText) != null ? _a2 : "",
151
+ short_name: (_b = c.shortText) != null ? _b : "",
152
+ types: c.types
153
+ };
154
+ });
155
+ else if (field === "wheelchair_accessible_entrance")
156
+ result.wheelchair_accessible_entrance = value2 == null ? void 0 : value2.wheelchairAccessibleEntrance;
157
+ else result[field] = value2;
158
+ }
159
+ return result;
160
+ };
161
+ var basicFields = ["place_id", "formatted_address", "geometry", "address_components"];
162
+ var getDetails = async ({ placeId, fields = basicFields, language }) => {
163
+ const newFields = [...new Set(fields.map((f) => {
164
+ var _a;
165
+ return (_a = fieldNames[f]) != null ? _a : f;
166
+ }))];
167
+ if (newFields.includes("location") && !newFields.includes("viewport")) newFields.push("viewport");
168
+ const shown = takeShown(placeId);
169
+ let place;
170
+ if (shown) {
171
+ place = await shown.getPlace(shown.suggestion, newFields);
172
+ } else {
173
+ const { Place: Place2 } = await _chunkGKD4BH53cjs.loadPlaces.call(void 0, );
174
+ place = new Place2({ id: placeId, ...language ? { requestedLanguage: language } : {} });
175
+ await place.fetchFields({ fields: newFields });
176
+ }
177
+ return toPlaceResult(place, fields);
178
+ };
179
+ var getGeocode = async (request) => {
180
+ const { Geocoder } = await _chunkGKD4BH53cjs.loadLibrary.call(void 0,
181
+ "geocoding"
182
+ );
183
+ const { results } = await new Geocoder().geocode(request);
184
+ return results;
185
+ };
186
+ var value = (v) => typeof v === "function" ? v() : v;
187
+ var getLatLng = (result) => {
188
+ var _a;
189
+ const location = (_a = result.geometry) == null ? void 0 : _a.location;
190
+ if (!location) throw new Error('google-places-autocomplete-hook: the result has no geometry; request the "geometry" field');
191
+ return { lat: value(location.lat), lng: value(location.lng) };
192
+ };
193
+ var getZipCode = (result, useShortName = false) => {
194
+ var _a;
195
+ const component = (_a = result.address_components) == null ? void 0 : _a.find((c) => c.types.includes("postal_code"));
196
+ return component && (useShortName ? component.short_name : component.long_name);
197
+ };
198
+
199
+
200
+
201
+
202
+
203
+
204
+
205
+
206
+ exports.default = usePlacesAutocomplete; exports.getDetails = getDetails; exports.getGeocode = getGeocode; exports.getLatLng = getLatLng; exports.getZipCode = getZipCode; exports.toAutocompletePrediction = toAutocompletePrediction; exports.toAutocompleteRequest = toAutocompleteRequest;