-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathapi-provider.tsx
262 lines (233 loc) · 7.75 KB
/
api-provider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import React, {
FunctionComponent,
PropsWithChildren,
useCallback,
useEffect,
useMemo,
useReducer,
useState
} from 'react';
import {
ApiParams,
GoogleMapsApiLoader
} from '../libraries/google-maps-api-loader';
import {APILoadingStatus} from '../libraries/api-loading-status';
type ImportLibraryFunction = typeof google.maps.importLibrary;
type GoogleMapsLibrary = Awaited<ReturnType<ImportLibraryFunction>>;
type LoadedLibraries = {[name: string]: GoogleMapsLibrary};
export interface APIProviderContextValue {
status: APILoadingStatus;
loadedLibraries: LoadedLibraries;
importLibrary: typeof google.maps.importLibrary;
mapInstances: Record<string, google.maps.Map>;
addMapInstance: (map: google.maps.Map, id?: string) => void;
removeMapInstance: (id?: string) => void;
clearMapInstances: () => void;
}
const DEFAULT_SOLUTION_CHANNEL = 'GMP_visgl_rgmlibrary_v1_default';
export const APIProviderContext =
React.createContext<APIProviderContextValue | null>(null);
export type APIProviderProps = PropsWithChildren<{
/**
* apiKey must be provided to load the Google Maps JavaScript API. To create an API key, see: https://developers.google.com/maps/documentation/javascript/get-api-key
* Part of:
*/
apiKey: string;
/**
* A custom id to reference the script tag can be provided. The default is set to 'google-maps-api'
* @default 'google-maps-api'
*/
libraries?: Array<string>;
/**
* A specific version of the Google Maps JavaScript API can be used.
* Read more about versioning: https://developers.google.com/maps/documentation/javascript/versions
* Part of: https://developers.google.com/maps/documentation/javascript/url-params
*/
version?: string;
/**
* Sets the map to a specific region.
* Read more about localizing the Map: https://developers.google.com/maps/documentation/javascript/localization
* Part of: https://developers.google.com/maps/documentation/javascript/url-params
*/
region?: string;
/**
* Use a specific language for the map.
* Read more about localizing the Map: https://developers.google.com/maps/documentation/javascript/localization
* Part of: https://developers.google.com/maps/documentation/javascript/url-params
*/
language?: string;
/**
* auth_referrer_policy can be set to 'origin'.
* Part of: https://developers.google.com/maps/documentation/javascript/url-params
*/
authReferrerPolicy?: string;
/**
* To understand usage and ways to improve our solutions, Google includes the
* `solution_channel` query parameter in API calls to gather information about
* code usage. You may opt out at any time by setting this attribute to an
* empty string. Read more in the
* [documentation](https://developers.google.com/maps/reporting-and-monitoring/reporting#solutions-usage).
*/
channel?: number;
/**
* To track usage of Google Maps JavaScript API via numeric channels. The only acceptable channel values are numbers from 0-999.
* Read more in the
* [documentation](https://developers.google.com/maps/reporting-and-monitoring/reporting#usage-tracking-per-channel)
*/
solutionChannel?: string;
/**
* A function that can be used to execute code after the Google Maps JavaScript API has been loaded.
*/
onLoad?: () => void;
/**
* A function that will be called if there was an error when loading the Google Maps JavaScript API.
*/
onError?: (error: unknown) => void;
}>;
/**
* local hook to set up the map-instance management context.
*/
function useMapInstances() {
const [mapInstances, setMapInstances] = useState<
Record<string, google.maps.Map>
>({});
const addMapInstance = (mapInstance: google.maps.Map, id = 'default') => {
setMapInstances(instances => ({...instances, [id]: mapInstance}));
};
const removeMapInstance = (id = 'default') => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setMapInstances(({[id]: _, ...remaining}) => remaining);
};
const clearMapInstances = () => {
setMapInstances({});
};
return {mapInstances, addMapInstance, removeMapInstance, clearMapInstances};
}
/**
* local hook to handle the loading of the maps API, returns the current loading status
* @param props
*/
function useGoogleMapsApiLoader(props: APIProviderProps) {
const {
onLoad,
onError,
apiKey,
version,
libraries = [],
...otherApiParams
} = props;
const [status, setStatus] = useState<APILoadingStatus>(
GoogleMapsApiLoader.loadingStatus
);
const [loadedLibraries, addLoadedLibrary] = useReducer(
(
loadedLibraries: LoadedLibraries,
action: {name: keyof LoadedLibraries; value: LoadedLibraries[string]}
) => {
return loadedLibraries[action.name]
? loadedLibraries
: {...loadedLibraries, [action.name]: action.value};
},
{}
);
const librariesString = useMemo(() => libraries?.join(','), [libraries]);
const serializedParams = useMemo(
() => JSON.stringify({apiKey, version, ...otherApiParams}),
[apiKey, version, otherApiParams]
);
const importLibrary: typeof google.maps.importLibrary = useCallback(
async (name: string) => {
if (loadedLibraries[name]) {
return loadedLibraries[name];
}
if (!google?.maps?.importLibrary) {
throw new Error(
'[api-provider-internal] importLibrary was called before ' +
'google.maps.importLibrary was defined.'
);
}
const res = await window.google.maps.importLibrary(name);
addLoadedLibrary({name, value: res});
return res;
},
[loadedLibraries]
);
useEffect(
() => {
(async () => {
try {
const params: ApiParams = {key: apiKey, ...otherApiParams};
if (version) params.v = version;
if (librariesString?.length > 0) params.libraries = librariesString;
if (
params.channel === undefined ||
params.channel < 0 ||
params.channel > 999
)
delete params.channel;
if (params.solutionChannel === undefined)
params.solutionChannel = DEFAULT_SOLUTION_CHANNEL;
else if (params.solutionChannel === '') delete params.solutionChannel;
await GoogleMapsApiLoader.load(params, status => setStatus(status));
for (const name of ['core', 'maps', ...libraries]) {
await importLibrary(name);
}
if (onLoad) {
onLoad();
}
} catch (error) {
if (onError) {
onError(error);
} else {
console.error(
'<ApiProvider> failed to load the Google Maps JavaScript API',
error
);
}
}
})();
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[apiKey, librariesString, serializedParams]
);
return {
status,
loadedLibraries,
importLibrary
};
}
/**
* Component to wrap the components from this library and load the Google Maps JavaScript API
*/
export const APIProvider: FunctionComponent<APIProviderProps> = props => {
const {children, ...loaderProps} = props;
const {mapInstances, addMapInstance, removeMapInstance, clearMapInstances} =
useMapInstances();
const {status, loadedLibraries, importLibrary} =
useGoogleMapsApiLoader(loaderProps);
const contextValue: APIProviderContextValue = useMemo(
() => ({
mapInstances,
addMapInstance,
removeMapInstance,
clearMapInstances,
status,
loadedLibraries,
importLibrary
}),
[
mapInstances,
addMapInstance,
removeMapInstance,
clearMapInstances,
status,
loadedLibraries,
importLibrary
]
);
return (
<APIProviderContext.Provider value={contextValue}>
{children}
</APIProviderContext.Provider>
);
};