@atelic-action/ui 8.3.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.
Files changed (43) hide show
  1. package/README.md +74 -9
  2. package/dist/lib/contactLinks.d.ts +31 -0
  3. package/dist/lib/contactLinks.js +55 -0
  4. package/dist/monitoring/server.js +82 -15
  5. package/dist/scripts/check-contacts.d.ts +17 -0
  6. package/dist/scripts/check-contacts.js +162 -0
  7. package/package.json +10 -13
  8. package/src/chrome/Footer.tsx +27 -17
  9. package/src/chrome/SiteHeader.tsx +7 -6
  10. package/src/chrome/SiteMenu.tsx +13 -10
  11. package/src/chrome/StickyCTABar.tsx +34 -16
  12. package/src/components/GateLogin.tsx +2 -1
  13. package/src/components/MultiSelect.tsx +225 -0
  14. package/src/components/index.ts +1 -0
  15. package/src/lib/contactForm.ts +184 -0
  16. package/src/lib/contactLinks.ts +57 -0
  17. package/src/lib/googlePlaces.ts +392 -0
  18. package/src/lib/latestOnly.ts +47 -0
  19. package/src/monitoring/server.ts +92 -16
  20. package/src/primitives/AddressSearch.tsx +341 -0
  21. package/src/primitives/EmailLink.tsx +55 -0
  22. package/src/primitives/ExpandableText.tsx +137 -0
  23. package/src/primitives/GoogleMapsAttribution.tsx +14 -0
  24. package/src/primitives/PhoneLink.tsx +61 -0
  25. package/src/primitives/index.ts +18 -0
  26. package/src/routing/miss.ts +14 -13
  27. package/src/scripts/check-base-path.ts +15 -0
  28. package/src/scripts/check-contacts.ts +177 -0
  29. package/src/sections/ContactForm.tsx +683 -87
  30. package/src/sections/ContactInfoCard.tsx +21 -4
  31. package/src/sections/InfoRows.tsx +103 -0
  32. package/src/sections/LocationSection.tsx +2 -1
  33. package/src/sections/Locations.tsx +3 -2
  34. package/src/sections/PageHero.tsx +22 -5
  35. package/src/sections/index.ts +23 -1
  36. package/src/sections/siteConfig.ts +12 -1
  37. package/src/styles/chrome.css +30 -17
  38. package/src/styles/components.css +123 -0
  39. package/src/styles/defaults.css +33 -1
  40. package/src/styles/fields.css +33 -0
  41. package/src/styles/primitives.css +165 -0
  42. package/src/styles/sections.css +310 -22
  43. package/src/types.ts +7 -2
@@ -0,0 +1,184 @@
1
+ import type { AddressParts } from "../primitives/AddressSearch";
2
+ import { EMAIL_PATTERN, toE164 } from "./contactLinks";
3
+
4
+ /** Which of the contact form's opt in fields are drawn, and which must be filled. */
5
+ export interface ContactFormShape {
6
+ /** First and last name in place of the one name. */
7
+ splitName: boolean;
8
+ phone: "off" | "optional" | "required";
9
+ address: "off" | "optional" | "required";
10
+ /** The services multi select in place of the topic select. */
11
+ services: boolean;
12
+ consent: boolean;
13
+ }
14
+
15
+ /** The shape the form had before 8.5.0, and still has with no opt in prop. */
16
+ export const PLAIN_SHAPE: ContactFormShape = {
17
+ splitName: false,
18
+ phone: "off",
19
+ address: "off",
20
+ services: false,
21
+ consent: false,
22
+ };
23
+
24
+ /** What a visitor wrote, read from the form, trimmed. */
25
+ export interface ContactFormValues {
26
+ /** The one name, or the first and last joined by a space. */
27
+ name: string;
28
+ firstName: string;
29
+ lastName: string;
30
+ email: string;
31
+ phone: string;
32
+ /** The topic chosen, or the chosen services joined by commas. */
33
+ topic: string;
34
+ services: string[];
35
+ address: AddressParts;
36
+ message: string;
37
+ consent: boolean;
38
+ /** The honeypot, verbatim. */
39
+ company: string;
40
+ }
41
+
42
+ /** A field the form can refuse, in the order the form draws them. */
43
+ export type ContactFormField =
44
+ | "name"
45
+ | "firstName"
46
+ | "lastName"
47
+ | "phone"
48
+ | "email"
49
+ | "street"
50
+ | "city"
51
+ | "state"
52
+ | "zip"
53
+ | "message";
54
+
55
+ /** Every refusable field in the page's order, so focus goes to the first refused. */
56
+ export const FIELD_ORDER: ContactFormField[] = [
57
+ "name",
58
+ "firstName",
59
+ "lastName",
60
+ "phone",
61
+ "email",
62
+ "street",
63
+ "city",
64
+ "state",
65
+ "zip",
66
+ "message",
67
+ ];
68
+
69
+ export type ContactFormRefusals = Partial<Record<ContactFormField, true>>;
70
+
71
+ /**
72
+ * Whether a typed number is one to dial: one that reads into E.164
73
+ * (`toE164`), the same check the phone link makes. The form's default
74
+ * phone check.
75
+ */
76
+ export function isPhoneNumber(value: string): boolean {
77
+ return toE164(value) !== null;
78
+ }
79
+
80
+ /** A US ZIP code, five digits or ZIP+4. */
81
+ export function isZIP(value: string): boolean {
82
+ return /^\d{5}(-?\d{4})?$/.test(value.trim());
83
+ }
84
+
85
+ /** An address on one line: "418 Alder Street, Fairhaven, CO 80000", skipping empty parts. */
86
+ export function addressLine(address: AddressParts): string {
87
+ const place = [address.state, address.zip].filter(Boolean).join(" ");
88
+ return [address.street, address.city, place].filter(Boolean).join(", ");
89
+ }
90
+
91
+ /** Reads what the visitor wrote from the form's data, for the fields the shape draws. */
92
+ export function readContactForm(data: FormData, shape: ContactFormShape): ContactFormValues {
93
+ const text = (key: string) => String(data.get(key) ?? "").trim();
94
+ const firstName = shape.splitName ? text("firstName") : "";
95
+ const lastName = shape.splitName ? text("lastName") : "";
96
+ const services = shape.services ? data.getAll("services").map(String) : [];
97
+ const street = text("street");
98
+ const city = text("city");
99
+ const zip = text("zip");
100
+ // An optional address nobody wrote is no address: a state select's
101
+ // default alone is not the visitor's answer, so it goes too.
102
+ const unwritten = shape.address === "optional" && !street && !city && !zip;
103
+ return {
104
+ name: shape.splitName ? [firstName, lastName].filter(Boolean).join(" ") : text("name"),
105
+ firstName,
106
+ lastName,
107
+ email: text("email"),
108
+ phone: shape.phone === "off" ? "" : text("phone"),
109
+ // The topic is read untrimmed, as it always was.
110
+ topic: shape.services ? services.join(", ") : String(data.get("topic") ?? ""),
111
+ services,
112
+ address:
113
+ shape.address === "off"
114
+ ? { street: "", city: "", state: "", zip: "" }
115
+ : { street, city, state: unwritten ? "" : text("state"), zip },
116
+ message: text("message"),
117
+ consent: shape.consent && data.get("consent") !== null,
118
+ company: String(data.get("company") ?? ""),
119
+ };
120
+ }
121
+
122
+ /**
123
+ * The fields to refuse. The name (or the first and the last), a valid email,
124
+ * and the message are always required, as they always were. A required
125
+ * phone must be a number `validPhone` accepts; an optional one is refused
126
+ * only when something is written that it does not accept. A required
127
+ * address needs every part and a ZIP code; an optional one is not checked.
128
+ */
129
+ export function checkContactForm(
130
+ values: ContactFormValues,
131
+ shape: ContactFormShape,
132
+ validPhone: (value: string) => boolean = isPhoneNumber,
133
+ ): ContactFormRefusals {
134
+ const refused: ContactFormRefusals = {};
135
+ if (shape.splitName) {
136
+ if (!values.firstName) refused.firstName = true;
137
+ if (!values.lastName) refused.lastName = true;
138
+ } else if (!values.name) refused.name = true;
139
+ if (shape.phone === "required" && !validPhone(values.phone)) refused.phone = true;
140
+ if (shape.phone === "optional" && values.phone && !validPhone(values.phone)) refused.phone = true;
141
+ if (!EMAIL_PATTERN.test(values.email)) refused.email = true;
142
+ if (shape.address === "required") {
143
+ if (!values.address.street) refused.street = true;
144
+ if (!values.address.city) refused.city = true;
145
+ if (!values.address.state) refused.state = true;
146
+ if (!isZIP(values.address.zip)) refused.zip = true;
147
+ }
148
+ if (!values.message) refused.message = true;
149
+ return refused;
150
+ }
151
+
152
+ /** The first field to fix, in the page's order, or none. */
153
+ export function firstRefused(refused: ContactFormRefusals): ContactFormField | undefined {
154
+ return FIELD_ORDER.find((field) => refused[field]);
155
+ }
156
+
157
+ /**
158
+ * The JSON body the form posts. It always carries `name`, `email`, `topic`,
159
+ * `message`, and `company` (the honeypot, verbatim), so a relay that reads
160
+ * only those keeps working whatever the form draws: with the split name,
161
+ * `name` is the first and last joined; with the services, `topic` is the
162
+ * chosen services joined by commas. Each opt in field adds its own keys
163
+ * only when it is drawn: `firstName` and `lastName`; `phone`; `address`, an
164
+ * object of `street`, `city`, `state`, and `zip`; `services`, an array of
165
+ * the chosen values; `consent`, a boolean.
166
+ */
167
+ export function contactFormBody(
168
+ values: ContactFormValues,
169
+ shape: ContactFormShape,
170
+ ): Record<string, unknown> {
171
+ const { name, email, topic, message, company } = values;
172
+ return {
173
+ name,
174
+ email,
175
+ topic,
176
+ message,
177
+ company,
178
+ ...(shape.splitName && { firstName: values.firstName, lastName: values.lastName }),
179
+ ...(shape.phone !== "off" && { phone: values.phone }),
180
+ ...(shape.address !== "off" && { address: values.address }),
181
+ ...(shape.services && { services: values.services }),
182
+ ...(shape.consent && { consent: values.consent }),
183
+ };
184
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Whether a phone number or an email address is well formed enough to link.
3
+ * One check each, shared by the contact form (what it accepts) and the link
4
+ * primitives (what they link), so the two never disagree. Light by design:
5
+ * the build guard checks a site's configured numbers against Google's full
6
+ * numbering plan (`checkSiteContacts`, in the scripts); a page carries none
7
+ * of that.
8
+ */
9
+
10
+ /** An email address: something, an @, something, a dot, something; no spaces. */
11
+ export const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
12
+
13
+ /** Whether an address is one to send to, ignoring the space around it. */
14
+ export function isEmail(value: string): boolean {
15
+ return EMAIL_PATTERN.test(value.trim());
16
+ }
17
+
18
+ /** A number in E.164: a + and 8 to 15 digits, never opening on 0. */
19
+ export function isE164(value: string): boolean {
20
+ return /^\+[1-9]\d{7,14}$/.test(value);
21
+ }
22
+
23
+ /** An extension after the number ("x12", "ext. 12", "extension 12"), which no dialer takes in E.164. */
24
+ export const EXTENSION = /\s*(?:,|;|#|x|ext\.?|extension)\s*\d+\s*$/i;
25
+
26
+ /**
27
+ * A typed number in E.164, or null when it is not one to dial. A number
28
+ * typed with a + keeps its country code; ten digits, typed any common way,
29
+ * take the North American +1 (an area code never opens on 0 or 1); eleven
30
+ * that open on 1 take the +. An extension is dropped, so the link dials the
31
+ * main line while the words still show it. Anything else, letters included,
32
+ * is null.
33
+ */
34
+ export function toE164(value: string): string | null {
35
+ const number = value.trim().replace(EXTENSION, "");
36
+ if (!number || /[^\d\s().+-]/.test(number) || number.lastIndexOf("+") > 0) return null;
37
+ const digits = number.replace(/\D/g, "");
38
+ if (number.startsWith("+")) {
39
+ const e164 = `+${digits}`;
40
+ return isE164(e164) ? e164 : null;
41
+ }
42
+ if (/^[2-9]\d{9}$/.test(digits)) return `+1${digits}`;
43
+ if (/^1[2-9]\d{9}$/.test(digits)) return `+${digits}`;
44
+ return null;
45
+ }
46
+
47
+ /**
48
+ * What a dialer can still take from a typed number `toE164` cannot read:
49
+ * its digits, its extension dropped and a typed leading + kept. Null when
50
+ * there is no digit to dial.
51
+ */
52
+ export function dialable(value: string): string | null {
53
+ const number = value.trim().replace(EXTENSION, "");
54
+ const digits = number.replace(/\D/g, "");
55
+ if (!digits) return null;
56
+ return number.startsWith("+") ? `+${digits}` : digits;
57
+ }
@@ -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
+ }