@atelic-action/ui 8.4.0 → 8.5.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/README.md +50 -5
- package/dist/lib/contactLinks.d.ts +31 -0
- package/dist/lib/contactLinks.js +55 -0
- package/dist/scripts/check-contacts.d.ts +17 -0
- package/dist/scripts/check-contacts.js +162 -0
- package/package.json +10 -13
- package/src/chrome/Footer.tsx +4 -3
- package/src/chrome/SiteHeader.tsx +7 -6
- package/src/chrome/SiteMenu.tsx +11 -9
- package/src/chrome/StickyCTABar.tsx +3 -2
- package/src/components/GateLogin.tsx +2 -1
- package/src/components/MultiSelect.tsx +225 -0
- package/src/components/index.ts +1 -0
- package/src/lib/contactForm.ts +184 -0
- package/src/lib/contactLinks.ts +57 -0
- package/src/lib/googlePlaces.ts +392 -0
- package/src/lib/latestOnly.ts +47 -0
- package/src/primitives/AddressSearch.tsx +341 -0
- package/src/primitives/EmailLink.tsx +55 -0
- package/src/primitives/ExpandableText.tsx +137 -0
- package/src/primitives/GoogleMapsAttribution.tsx +14 -0
- package/src/primitives/PhoneLink.tsx +61 -0
- package/src/primitives/index.ts +18 -0
- package/src/scripts/check-base-path.ts +15 -0
- package/src/scripts/check-contacts.ts +177 -0
- package/src/sections/ContactForm.tsx +683 -87
- package/src/sections/ContactInfoCard.tsx +20 -5
- package/src/sections/InfoRows.tsx +103 -0
- package/src/sections/LocationSection.tsx +2 -1
- package/src/sections/Locations.tsx +3 -2
- package/src/sections/PageHero.tsx +22 -5
- package/src/sections/index.ts +23 -1
- package/src/styles/components.css +123 -0
- package/src/styles/defaults.css +31 -1
- package/src/styles/fields.css +33 -0
- package/src/styles/primitives.css +165 -0
- package/src/styles/sections.css +306 -19
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
import type { AddressParts, AddressProvider, AddressSuggestion } from "../primitives/AddressSearch";
|
|
2
|
+
|
|
3
|
+
/** The options a site passes `googlePlacesProvider`; only the key is required. */
|
|
4
|
+
export interface GooglePlacesOptions {
|
|
5
|
+
/**
|
|
6
|
+
* A Maps JavaScript API key with the Places API (New) enabled, restricted
|
|
7
|
+
* to the site's own domains (Websites) and to those two APIs. It ships to
|
|
8
|
+
* the browser, as every Maps JavaScript API key does.
|
|
9
|
+
*/
|
|
10
|
+
apiKey: string;
|
|
11
|
+
/** Limit suggestions to these countries, as CLDR two letter codes ("us"); up to 15. */
|
|
12
|
+
regionCodes?: string[];
|
|
13
|
+
/**
|
|
14
|
+
* Prefer addresses near a point, a soft bias rather than a limit: a center
|
|
15
|
+
* and a radius in meters, held to Google's most, 50000.
|
|
16
|
+
*/
|
|
17
|
+
near?: { lat: number; lng: number; radius: number };
|
|
18
|
+
/** The kinds of place offered, up to five. Defaults to addresses: `street_address`, `premise`, and `subpremise` (a unit). */
|
|
19
|
+
types?: string[];
|
|
20
|
+
/** The language of the suggestions (an IETF code, "en"). */
|
|
21
|
+
language?: string;
|
|
22
|
+
/** The region the suggestions are formatted for (a CLDR code, "us"). */
|
|
23
|
+
region?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The slice of the Maps JavaScript API's `places` library the provider
|
|
28
|
+
* calls: `AutocompleteSuggestion`, `AutocompleteSessionToken`, and the
|
|
29
|
+
* `Place` a prediction turns into. Named here so a test can stand in for it.
|
|
30
|
+
*/
|
|
31
|
+
export interface PlacesLibrary {
|
|
32
|
+
AutocompleteSessionToken: new () => unknown;
|
|
33
|
+
AutocompleteSuggestion: {
|
|
34
|
+
fetchAutocompleteSuggestions(request: Record<string, unknown>): Promise<{
|
|
35
|
+
suggestions: { placePrediction?: PlacePrediction | null }[];
|
|
36
|
+
}>;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface FormattableText {
|
|
41
|
+
text: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface PlacePrediction {
|
|
45
|
+
placeId: string;
|
|
46
|
+
text: FormattableText;
|
|
47
|
+
mainText?: FormattableText | null;
|
|
48
|
+
secondaryText?: FormattableText | null;
|
|
49
|
+
toPlace(): {
|
|
50
|
+
fetchFields(request: { fields: string[] }): Promise<unknown>;
|
|
51
|
+
addressComponents?: AddressComponent[] | null;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** One part of an address as Google returns it. */
|
|
56
|
+
export interface AddressComponent {
|
|
57
|
+
longText?: string | null;
|
|
58
|
+
shortText?: string | null;
|
|
59
|
+
types: string[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Addresses, buildings, and the units inside them (Table B; up to five allowed).
|
|
63
|
+
const ADDRESS_TYPES = ["street_address", "premise", "subpremise"];
|
|
64
|
+
|
|
65
|
+
function abortError(): Error {
|
|
66
|
+
return new DOMException("The lookup was aborted.", "AbortError");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Settles with `task`, or rejects the moment `signal` aborts, whichever is first. */
|
|
70
|
+
function honoring<T>(signal: AbortSignal, task: () => Promise<T>): Promise<T> {
|
|
71
|
+
if (signal.aborted) return Promise.reject(abortError());
|
|
72
|
+
return new Promise<T>((resolve, reject) => {
|
|
73
|
+
const onAbort = () => reject(abortError());
|
|
74
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
75
|
+
task().then(
|
|
76
|
+
(value) => {
|
|
77
|
+
signal.removeEventListener("abort", onAbort);
|
|
78
|
+
resolve(value);
|
|
79
|
+
},
|
|
80
|
+
(error: unknown) => {
|
|
81
|
+
signal.removeEventListener("abort", onAbort);
|
|
82
|
+
reject(error);
|
|
83
|
+
},
|
|
84
|
+
);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Google's address components as the four parts a form holds: the street
|
|
90
|
+
* number and the route (with a unit after a #), the city (the locality, or
|
|
91
|
+
* the postal town or sublocality where a country uses one), the state's
|
|
92
|
+
* short code ("CO"), and the postal code. `fallbackStreet` stands in when
|
|
93
|
+
* there is no route, such as a named building.
|
|
94
|
+
*/
|
|
95
|
+
export function addressFromComponents(
|
|
96
|
+
components: AddressComponent[],
|
|
97
|
+
fallbackStreet = "",
|
|
98
|
+
): AddressParts {
|
|
99
|
+
const find = (type: string) => components.find((component) => component.types.includes(type));
|
|
100
|
+
const long = (type: string) => find(type)?.longText ?? "";
|
|
101
|
+
const short = (type: string) => find(type)?.shortText || find(type)?.longText || "";
|
|
102
|
+
const line = [long("street_number"), long("route")].filter(Boolean).join(" ");
|
|
103
|
+
const unit = long("subpremise");
|
|
104
|
+
const street = line ? (unit ? `${line} #${unit}` : line) : fallbackStreet;
|
|
105
|
+
const city =
|
|
106
|
+
long("locality") ||
|
|
107
|
+
long("postal_town") ||
|
|
108
|
+
long("sublocality_level_1") ||
|
|
109
|
+
long("sublocality") ||
|
|
110
|
+
long("administrative_area_level_3");
|
|
111
|
+
return { street, city, state: short("administrative_area_level_1"), zip: long("postal_code") };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The provider over a loaded `places` library, separate from the loading so
|
|
116
|
+
* a test can hand it a stand in. One session token covers every search from
|
|
117
|
+
* the first keystroke to a pick; the pick's details end the session, and
|
|
118
|
+
* the next search starts a new one.
|
|
119
|
+
*/
|
|
120
|
+
export function placesProvider(
|
|
121
|
+
library: (retry: boolean) => Promise<PlacesLibrary>,
|
|
122
|
+
options: Omit<GooglePlacesOptions, "apiKey">,
|
|
123
|
+
): AddressProvider {
|
|
124
|
+
let token: unknown = null;
|
|
125
|
+
// The predictions behind the latest suggestions, so a pick resolves through
|
|
126
|
+
// its own prediction and stays in the session.
|
|
127
|
+
let predictions = new Map<string, PlacePrediction>();
|
|
128
|
+
|
|
129
|
+
return {
|
|
130
|
+
// Each focus may retry a load that failed; a search never does.
|
|
131
|
+
prepare() {
|
|
132
|
+
library(true).catch(() => {});
|
|
133
|
+
},
|
|
134
|
+
// Leaving the field without a pick abandons the session: Google gives
|
|
135
|
+
// no lifetime for one, so the next search starts a new token rather
|
|
136
|
+
// than reusing an old one.
|
|
137
|
+
abandon() {
|
|
138
|
+
token = null;
|
|
139
|
+
predictions = new Map();
|
|
140
|
+
},
|
|
141
|
+
async suggest(query, { signal }) {
|
|
142
|
+
try {
|
|
143
|
+
const places = await honoring(signal, () => library(false));
|
|
144
|
+
token ??= new places.AutocompleteSessionToken();
|
|
145
|
+
const request: Record<string, unknown> = {
|
|
146
|
+
input: query,
|
|
147
|
+
sessionToken: token,
|
|
148
|
+
includedPrimaryTypes: options.types ?? ADDRESS_TYPES,
|
|
149
|
+
};
|
|
150
|
+
if (options.regionCodes?.length) request.includedRegionCodes = options.regionCodes;
|
|
151
|
+
if (options.near) {
|
|
152
|
+
const { lat, lng, radius } = options.near;
|
|
153
|
+
// Google refuses a bias past 50000 meters, which would leave every
|
|
154
|
+
// search empty; a wider one is held to the most it takes.
|
|
155
|
+
request.locationBias = { center: { lat, lng }, radius: Math.min(radius, 50_000) };
|
|
156
|
+
}
|
|
157
|
+
if (options.language) request.language = options.language;
|
|
158
|
+
if (options.region) request.region = options.region;
|
|
159
|
+
const { suggestions } = await honoring(signal, () =>
|
|
160
|
+
places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request),
|
|
161
|
+
);
|
|
162
|
+
const found = suggestions.flatMap((suggestion) =>
|
|
163
|
+
suggestion.placePrediction ? [suggestion.placePrediction] : [],
|
|
164
|
+
);
|
|
165
|
+
predictions = new Map(found.map((prediction) => [prediction.placeId, prediction]));
|
|
166
|
+
return found.map(
|
|
167
|
+
(prediction): AddressSuggestion => ({
|
|
168
|
+
id: prediction.placeId,
|
|
169
|
+
text: prediction.mainText?.text ?? prediction.text.text,
|
|
170
|
+
secondary: prediction.secondaryText?.text ?? undefined,
|
|
171
|
+
}),
|
|
172
|
+
);
|
|
173
|
+
} catch {
|
|
174
|
+
if (signal.aborted) throw abortError();
|
|
175
|
+
// A failed lookup offers nothing; the plain fields still take the address.
|
|
176
|
+
return [];
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
async resolve(suggestion, { signal }) {
|
|
180
|
+
const prediction = predictions.get(suggestion.id);
|
|
181
|
+
if (!prediction) throw new Error("That suggestion is no longer offered.");
|
|
182
|
+
const place = prediction.toPlace();
|
|
183
|
+
// Only the address components: the cheapest field set that fills the form.
|
|
184
|
+
const fetched = honoring(signal, () => place.fetchFields({ fields: ["addressComponents"] }));
|
|
185
|
+
// The details call ends the session, answered or not; the next search starts a new one.
|
|
186
|
+
token = null;
|
|
187
|
+
predictions = new Map();
|
|
188
|
+
await fetched;
|
|
189
|
+
return addressFromComponents(place.addressComponents ?? [], suggestion.text);
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
declare global {
|
|
195
|
+
interface Window {
|
|
196
|
+
google?: {
|
|
197
|
+
maps?: {
|
|
198
|
+
importLibrary?: (name: string) => Promise<unknown>;
|
|
199
|
+
places?: Partial<PlacesLibrary>;
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const MAPS_SCRIPT = "https://maps.googleapis.com/maps/api/js";
|
|
206
|
+
/** After a failed load, searches wait this long before trying again; a focus does not wait. */
|
|
207
|
+
export const RETRY_AFTER_MS = 30_000;
|
|
208
|
+
/** How long to wait for a Maps script, ours or one already on the page, to answer. */
|
|
209
|
+
export const SCRIPT_WAIT_MS = 15_000;
|
|
210
|
+
|
|
211
|
+
const loads = new Map<string, Promise<PlacesLibrary>>();
|
|
212
|
+
const failures = new Map<string, number>();
|
|
213
|
+
let callbacks = 0;
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* The places library, when the page's Maps API can give it: by
|
|
217
|
+
* `importLibrary`, or the older namespace once it holds the Autocomplete
|
|
218
|
+
* Data classes. Null while it cannot yet, including a Maps API still
|
|
219
|
+
* attaching its libraries.
|
|
220
|
+
*/
|
|
221
|
+
function placesReady(): Promise<PlacesLibrary> | null {
|
|
222
|
+
const maps = window.google?.maps;
|
|
223
|
+
if (!maps) return null;
|
|
224
|
+
if (maps.importLibrary) return maps.importLibrary("places") as Promise<PlacesLibrary>;
|
|
225
|
+
const places = maps.places;
|
|
226
|
+
if (places?.AutocompleteSuggestion && places.AutocompleteSessionToken) {
|
|
227
|
+
return Promise.resolve(places as PlacesLibrary);
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** The places library from a Maps API already on the page, a refusal when it has none, null with no Maps. */
|
|
233
|
+
function libraryOnPage(): Promise<PlacesLibrary> | null {
|
|
234
|
+
if (!window.google?.maps) return null;
|
|
235
|
+
return (
|
|
236
|
+
placesReady() ??
|
|
237
|
+
Promise.reject(new Error("The Maps JavaScript API on the page has no Places library."))
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Waits for a Maps script already on the page (another's, or ours that was
|
|
243
|
+
* slow) rather than adding a second, until its Places library is there:
|
|
244
|
+
* a `google.maps` without it yet is still loading, not a failure.
|
|
245
|
+
*/
|
|
246
|
+
function waitForScript(script: HTMLScriptElement): Promise<PlacesLibrary> {
|
|
247
|
+
return new Promise<PlacesLibrary>((resolve, reject) => {
|
|
248
|
+
const started = Date.now();
|
|
249
|
+
let stopped = false;
|
|
250
|
+
const check = () => {
|
|
251
|
+
if (stopped) return;
|
|
252
|
+
const ready = placesReady();
|
|
253
|
+
if (ready) {
|
|
254
|
+
ready.then(resolve, reject);
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (Date.now() - started > SCRIPT_WAIT_MS) {
|
|
258
|
+
reject(
|
|
259
|
+
new Error(
|
|
260
|
+
window.google?.maps
|
|
261
|
+
? "The Maps JavaScript API on the page has no Places library."
|
|
262
|
+
: "The Maps JavaScript API on the page never finished loading.",
|
|
263
|
+
),
|
|
264
|
+
);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
setTimeout(check, 50);
|
|
268
|
+
};
|
|
269
|
+
script.addEventListener(
|
|
270
|
+
"error",
|
|
271
|
+
() => {
|
|
272
|
+
// A tag that failed is done: the poll stops with the refusal.
|
|
273
|
+
stopped = true;
|
|
274
|
+
reject(new Error("The Maps JavaScript API did not load."));
|
|
275
|
+
},
|
|
276
|
+
{ once: true },
|
|
277
|
+
);
|
|
278
|
+
check();
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Adds Google's direct script tag with `loading=async`. A tag that fails is
|
|
284
|
+
* taken back out. One that has not called back within `SCRIPT_WAIT_MS`
|
|
285
|
+
* rejects the load, down the same failure and retry path, but stays on the
|
|
286
|
+
* page with its callback left as a no op: it may still arrive, and a retry
|
|
287
|
+
* then waits for it (`waitForScript`) rather than adding a second.
|
|
288
|
+
*/
|
|
289
|
+
function addScript(apiKey: string): Promise<PlacesLibrary> {
|
|
290
|
+
return new Promise<PlacesLibrary>((resolve, reject) => {
|
|
291
|
+
callbacks += 1;
|
|
292
|
+
const callback = `__atelicPlacesReady${callbacks}`;
|
|
293
|
+
const globals = window as unknown as Record<string, unknown>;
|
|
294
|
+
const params = new URLSearchParams({
|
|
295
|
+
key: apiKey,
|
|
296
|
+
loading: "async",
|
|
297
|
+
libraries: "places",
|
|
298
|
+
v: "weekly",
|
|
299
|
+
callback,
|
|
300
|
+
});
|
|
301
|
+
const script = document.createElement("script");
|
|
302
|
+
const fail = (message: string) => {
|
|
303
|
+
clearTimeout(timer);
|
|
304
|
+
delete globals[callback];
|
|
305
|
+
script.remove();
|
|
306
|
+
reject(new Error(message));
|
|
307
|
+
};
|
|
308
|
+
const timer = setTimeout(() => {
|
|
309
|
+
// Late, not lost: the tag stays and its callback answers nothing.
|
|
310
|
+
globals[callback] = () => {};
|
|
311
|
+
reject(new Error("The Maps JavaScript API did not answer."));
|
|
312
|
+
}, SCRIPT_WAIT_MS);
|
|
313
|
+
globals[callback] = () => {
|
|
314
|
+
clearTimeout(timer);
|
|
315
|
+
delete globals[callback];
|
|
316
|
+
const ready = libraryOnPage();
|
|
317
|
+
if (ready) ready.then(resolve, reject);
|
|
318
|
+
else reject(new Error("The Maps JavaScript API loaded without google.maps."));
|
|
319
|
+
};
|
|
320
|
+
script.src = `${MAPS_SCRIPT}?${params}`;
|
|
321
|
+
script.async = true;
|
|
322
|
+
script.onerror = () => fail("The Maps JavaScript API did not load.");
|
|
323
|
+
document.head.appendChild(script);
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function startLoad(apiKey: string): Promise<PlacesLibrary> {
|
|
328
|
+
if (typeof window === "undefined") {
|
|
329
|
+
return Promise.reject(new Error("The Maps JavaScript API loads only in a browser."));
|
|
330
|
+
}
|
|
331
|
+
const ready = placesReady();
|
|
332
|
+
if (ready) return ready;
|
|
333
|
+
// A Maps script still on its way, even one whose google.maps is there
|
|
334
|
+
// before its Places library, is waited for rather than doubled.
|
|
335
|
+
const existing = document.querySelector<HTMLScriptElement>(`script[src^="${MAPS_SCRIPT}"]`);
|
|
336
|
+
if (existing) return waitForScript(existing);
|
|
337
|
+
return libraryOnPage() ?? addScript(apiKey);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Loads the Maps JavaScript API once per key, by Google's direct script tag
|
|
342
|
+
* with `loading=async`, and imports its `places` library. Uses the API when
|
|
343
|
+
* the page already has it, and waits for a Maps script already on the page
|
|
344
|
+
* rather than adding a second; where `importLibrary` is missing it takes
|
|
345
|
+
* the older `google.maps.places` namespace when that holds the Autocomplete
|
|
346
|
+
* Data classes, and fails otherwise.
|
|
347
|
+
*
|
|
348
|
+
* A failed load takes its tag back out and is remembered: a call without
|
|
349
|
+
* `retry` hands back the same failure for `RETRY_AFTER_MS`, so a search on
|
|
350
|
+
* every keystroke never adds a tag, while `retry` (the field's next focus)
|
|
351
|
+
* tries again at once. Runs only when called, never at import.
|
|
352
|
+
*/
|
|
353
|
+
export function loadPlacesLibrary(
|
|
354
|
+
apiKey: string,
|
|
355
|
+
{ retry = false }: { retry?: boolean } = {},
|
|
356
|
+
): Promise<PlacesLibrary> {
|
|
357
|
+
const cached = loads.get(apiKey);
|
|
358
|
+
if (cached) {
|
|
359
|
+
const failedAt = failures.get(apiKey);
|
|
360
|
+
if (failedAt === undefined) return cached;
|
|
361
|
+
if (!retry && Date.now() - failedAt < RETRY_AFTER_MS) return cached;
|
|
362
|
+
failures.delete(apiKey);
|
|
363
|
+
}
|
|
364
|
+
const load = startLoad(apiKey);
|
|
365
|
+
load.catch(() => failures.set(apiKey, Date.now()));
|
|
366
|
+
loads.set(apiKey, load);
|
|
367
|
+
return load;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Google's address suggestions as an `AddressSearch` provider: pass a key,
|
|
372
|
+
* and the search offers Google's addresses and fills the form with the
|
|
373
|
+
* street, city, state, and ZIP of the one picked.
|
|
374
|
+
*
|
|
375
|
+
* Built on the Maps JavaScript API's Places library (Autocomplete Data API,
|
|
376
|
+
* the New one), loaded on the field's first focus and never before (a
|
|
377
|
+
* failed load is tried again on a later focus, not on every keystroke), so a
|
|
378
|
+
* page whose visitor never reaches the address loads nothing of Google's.
|
|
379
|
+
* Google documents a website restricted key for the JavaScript API, and does
|
|
380
|
+
* not document one for calling the Places web service from a browser, which
|
|
381
|
+
* is why it is not called directly. A session token covers the searches and
|
|
382
|
+
* the pick, so they bill as one session, and the pick asks for the address
|
|
383
|
+
* components alone. A failed load or search offers no suggestions, so the
|
|
384
|
+
* plain fields still take the address; an aborted search rejects.
|
|
385
|
+
*
|
|
386
|
+
* Wherever its suggestions show, Google's terms ask for its attribution:
|
|
387
|
+
* pass `GoogleMapsAttribution` as the search's `attribution` (ContactForm's
|
|
388
|
+
* `googlePlacesKey` does).
|
|
389
|
+
*/
|
|
390
|
+
export function googlePlacesProvider({ apiKey, ...options }: GooglePlacesOptions): AddressProvider {
|
|
391
|
+
return placesProvider((retry) => loadPlacesLibrary(apiKey, { retry }), options);
|
|
392
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** What a lookup run through `latestOnly` settles to. */
|
|
2
|
+
export type LatestAnswer<T> = { stale: false; value: T } | { stale: true };
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Runs asynchronous lookups of which only the latest answer counts: an
|
|
6
|
+
* address search asks again on every pause in the typing, and an answer to
|
|
7
|
+
* an earlier question that arrives after a later one is dropped rather than
|
|
8
|
+
* shown over it. Each new run aborts the signal handed to the one before, so
|
|
9
|
+
* a provider that passes the signal to `fetch` stops the request too. A
|
|
10
|
+
* failed run settles stale when a later run has started, and rejects
|
|
11
|
+
* otherwise, so the caller hears only the failures that still matter.
|
|
12
|
+
*/
|
|
13
|
+
export function latestOnly() {
|
|
14
|
+
let current = 0;
|
|
15
|
+
let controller: AbortController | null = null;
|
|
16
|
+
|
|
17
|
+
return {
|
|
18
|
+
run<T>(task: (signal: AbortSignal) => Promise<T>): Promise<LatestAnswer<T>> {
|
|
19
|
+
controller?.abort();
|
|
20
|
+
const mine = new AbortController();
|
|
21
|
+
controller = mine;
|
|
22
|
+
current += 1;
|
|
23
|
+
const ticket = current;
|
|
24
|
+
// A task that throws before it returns a promise rejects like one that fails later.
|
|
25
|
+
let started: Promise<T>;
|
|
26
|
+
try {
|
|
27
|
+
started = task(mine.signal);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
started = Promise.reject(error);
|
|
30
|
+
}
|
|
31
|
+
return started.then(
|
|
32
|
+
(value) =>
|
|
33
|
+
ticket === current ? { stale: false as const, value } : { stale: true as const },
|
|
34
|
+
(error: unknown) => {
|
|
35
|
+
if (ticket !== current) return { stale: true as const };
|
|
36
|
+
throw error;
|
|
37
|
+
},
|
|
38
|
+
);
|
|
39
|
+
},
|
|
40
|
+
/** Drops whatever is in flight: its answer, when it comes, is stale. */
|
|
41
|
+
cancel() {
|
|
42
|
+
controller?.abort();
|
|
43
|
+
controller = null;
|
|
44
|
+
current += 1;
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|