@atelic-action/ui 8.4.0 → 8.6.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 (38) hide show
  1. package/README.md +65 -5
  2. package/dist/lib/contactLinks.d.ts +31 -0
  3. package/dist/lib/contactLinks.js +55 -0
  4. package/dist/scripts/check-contacts.d.ts +17 -0
  5. package/dist/scripts/check-contacts.js +162 -0
  6. package/package.json +10 -13
  7. package/src/chrome/Footer.tsx +4 -3
  8. package/src/chrome/SiteHeader.tsx +7 -6
  9. package/src/chrome/SiteMenu.tsx +11 -9
  10. package/src/chrome/StickyCTABar.tsx +5 -3
  11. package/src/components/GateLogin.tsx +2 -1
  12. package/src/components/MultiSelect.tsx +225 -0
  13. package/src/components/index.ts +1 -0
  14. package/src/lib/contactForm.ts +184 -0
  15. package/src/lib/contactLinks.ts +57 -0
  16. package/src/lib/googlePlaces.ts +392 -0
  17. package/src/lib/latestOnly.ts +47 -0
  18. package/src/primitives/AddressSearch.tsx +440 -0
  19. package/src/primitives/EmailLink.tsx +55 -0
  20. package/src/primitives/ExpandableText.tsx +161 -0
  21. package/src/primitives/GoogleMapsAttribution.tsx +14 -0
  22. package/src/primitives/PhoneLink.tsx +73 -0
  23. package/src/primitives/index.ts +18 -0
  24. package/src/scripts/check-base-path.ts +15 -0
  25. package/src/scripts/check-contacts.ts +177 -0
  26. package/src/sections/ContactForm.tsx +685 -87
  27. package/src/sections/ContactInfoCard.tsx +20 -5
  28. package/src/sections/ContactSection.tsx +72 -0
  29. package/src/sections/InfoRows.tsx +103 -0
  30. package/src/sections/LocationSection.tsx +5 -2
  31. package/src/sections/Locations.tsx +3 -2
  32. package/src/sections/PageHero.tsx +22 -5
  33. package/src/sections/index.ts +24 -1
  34. package/src/styles/components.css +123 -0
  35. package/src/styles/defaults.css +42 -1
  36. package/src/styles/fields.css +33 -0
  37. package/src/styles/primitives.css +172 -0
  38. package/src/styles/sections.css +350 -19
@@ -0,0 +1,440 @@
1
+ import { MapPin } from "lucide-react";
2
+ import {
3
+ type KeyboardEvent,
4
+ type ReactNode,
5
+ useEffect,
6
+ useId,
7
+ useMemo,
8
+ useRef,
9
+ useState,
10
+ } from "react";
11
+ import { latestOnly } from "../lib/latestOnly";
12
+
13
+ /** One suggestion a provider offers: its main line and the rest beneath it. */
14
+ export interface AddressSuggestion {
15
+ /** The provider's own key for the suggestion, handed back to `resolve`. */
16
+ id: string;
17
+ /** The main line, the street: "418 Alder Street". */
18
+ text: string;
19
+ /** The line beneath it, the place: "Fairhaven, CO 80000". */
20
+ secondary?: string;
21
+ }
22
+
23
+ /** A postal address in the four parts a form's fields hold. */
24
+ export interface AddressParts {
25
+ street: string;
26
+ city: string;
27
+ state: string;
28
+ zip: string;
29
+ }
30
+
31
+ /**
32
+ * Where suggestions come from. The search knows no service: a site wraps the
33
+ * one it uses (Google's address autocomplete, a postal service's lookup) in
34
+ * these two functions. Each is handed an `AbortSignal` that aborts once its
35
+ * answer can no longer be used, which a provider passes on to `fetch`.
36
+ */
37
+ export interface AddressProvider {
38
+ /** The suggestions for what has been typed so far. */
39
+ suggest(query: string, options: { signal: AbortSignal }): Promise<AddressSuggestion[]>;
40
+ /** The four parts of the suggestion the visitor picked. */
41
+ resolve(suggestion: AddressSuggestion, options: { signal: AbortSignal }): Promise<AddressParts>;
42
+ /**
43
+ * Called on each focus of the field, so a provider that loads a library
44
+ * can start before the first keystroke rather than at page load, and try
45
+ * again on a later focus when a load failed.
46
+ */
47
+ prepare?(): void;
48
+ /** Called when the visitor leaves the field without a pick, so a provider can end its session. */
49
+ abandon?(): void;
50
+ }
51
+
52
+ export interface AddressSearchProps {
53
+ /** Where the suggestions come from. With none, nothing renders. */
54
+ provider?: AddressProvider;
55
+ /** The field's label. */
56
+ label: ReactNode;
57
+ /** A quiet note beside the label, such as "(optional)". */
58
+ hint?: ReactNode;
59
+ placeholder?: string;
60
+ /**
61
+ * Called with the parts of the address picked. Return false when the
62
+ * pick is not taken after all (a form that has moved on): the field then
63
+ * goes back to what the visitor typed (8.6.0). Any handler that returns
64
+ * nothing, a state setter included, still fits.
65
+ */
66
+ // biome-ignore lint/suspicious/noConfusingVoidType: void keeps every handler that returns nothing (onPick={setAddress}) assignable, as it was before 8.6.0
67
+ onPick: (address: AddressParts) => boolean | void;
68
+ /**
69
+ * Called the moment a suggestion is chosen, before its parts arrive, so a
70
+ * form can tell a pick that lands after the visitor moved on.
71
+ */
72
+ onChoose?: (suggestion: AddressSuggestion) => void;
73
+ /** Drawn under the suggestions, for a provider whose terms ask for it ("Powered by ..."). */
74
+ attribution?: ReactNode;
75
+ /** The suggestion list's accessible name. */
76
+ listLabel?: string;
77
+ /** What a screen reader hears when the suggestions change. */
78
+ countLabel?: (count: number) => string;
79
+ /** Characters typed before the first lookup. Defaults to 3. */
80
+ minLength?: number;
81
+ /** The pause in the typing before a lookup, in milliseconds. Defaults to 250. */
82
+ debounceMs?: number;
83
+ /** The input's id; minted when left out. */
84
+ id?: string;
85
+ className?: string;
86
+ }
87
+
88
+ const defaultCount = (count: number) =>
89
+ count === 0 ? "No suggestions" : count === 1 ? "1 suggestion" : `${count} suggestions`;
90
+
91
+ /**
92
+ * How long a press may still bring its click after it is released, or
93
+ * after it leaves its suggestion: past a touch's click delay.
94
+ */
95
+ const PRESS_WAIT_MS = 600;
96
+
97
+ /** The line an address reads as once picked: the main line and the rest. */
98
+ const pickedText = (suggestion: AddressSuggestion) =>
99
+ [suggestion.text, suggestion.secondary].filter(Boolean).join(", ");
100
+
101
+ /**
102
+ * A text field that offers addresses as the visitor types and, on a pick,
103
+ * hands back the street, city, state, and ZIP. It knows no service: the
104
+ * suggestions come from `provider`, and with no provider it renders nothing,
105
+ * so the plain address fields beside it stand alone.
106
+ *
107
+ * It is the ARIA combobox with a list popup: the input keeps focus while
108
+ * the arrows move a highlight through the suggestions
109
+ * (`aria-activedescendant`), Enter picks the highlighted one, Escape closes
110
+ * the list, and a click picks one too. A lookup waits for a pause in the
111
+ * typing, and an answer that arrives after a newer question was asked is
112
+ * dropped. The count of suggestions is announced each time it changes.
113
+ * Nothing touches the page until an effect or a handler runs, so it
114
+ * prerenders.
115
+ */
116
+ export function AddressSearch({
117
+ provider,
118
+ label,
119
+ hint,
120
+ placeholder,
121
+ onPick,
122
+ onChoose,
123
+ attribution,
124
+ listLabel = "Suggestions",
125
+ countLabel = defaultCount,
126
+ minLength = 3,
127
+ debounceMs = 250,
128
+ id,
129
+ className,
130
+ }: AddressSearchProps) {
131
+ const minted = useId();
132
+ const inputId = id ?? `${minted}-input`;
133
+ const listId = `${minted}-list`;
134
+ const labelTextId = `${minted}-label`;
135
+ const hintId = `${minted}-hint`;
136
+ const optionId = (index: number) => `${minted}-option-${index}`;
137
+ const inputRef = useRef<HTMLInputElement>(null);
138
+ const [query, setQuery] = useState("");
139
+ const [suggestions, setSuggestions] = useState<AddressSuggestion[]>([]);
140
+ const [open, setOpen] = useState(false);
141
+ const [active, setActive] = useState(-1);
142
+ const [announce, setAnnounce] = useState("");
143
+ // The text a pick wrote into the field, so writing it asks nothing.
144
+ const picked = useRef<string | null>(null);
145
+ const lookups = useMemo(() => latestOnly(), []);
146
+ const resolves = useMemo(() => latestOnly(), []);
147
+ // The latest of each function prop, read when it is needed, so a site
148
+ // passing an inline function or provider never starts a lookup by rendering.
149
+ const latestPick = useRef(onPick);
150
+ latestPick.current = onPick;
151
+ const latestProvider = useRef(provider);
152
+ latestProvider.current = provider;
153
+ const latestCount = useRef(countLabel);
154
+ latestCount.current = countLabel;
155
+ // The provider whose answer the offered suggestions are, which a pick
156
+ // resolves through even if the site has passed a new one since.
157
+ const offeredBy = useRef<AddressProvider | null>(null);
158
+ // A press on a suggestion, from its pointerdown until its click. A touch
159
+ // fires pointerdown, pointerup, pointerout, pointerleave, and only then
160
+ // the compatibility mousedown (where focus moves, so the blur) and the
161
+ // click (Pointer Events 3, 4.2.6): the blur in between is the pick's, and
162
+ // leaves the list, the suggestions, and the provider's session alone
163
+ // (8.6.0). The press ends at its click, at a pointercancel, when its
164
+ // suggestions are replaced, or a while after its pointerup with no click.
165
+ const picking = useRef(false);
166
+ // The end of a press whose click never came, started at its pointerup.
167
+ const pressEnd = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
168
+ // The blur's cleanup, held past the click so a pick can call it off.
169
+ const leaving = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
170
+ // The pause before a lookup, held so a blur can stop it.
171
+ const pending = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
172
+ const hasProvider = Boolean(provider);
173
+
174
+ /** What leaving the field does once no pick is under way. */
175
+ const leave = () => {
176
+ clearTimeout(pending.current);
177
+ lookups.cancel();
178
+ setOpen(false);
179
+ setActive(-1);
180
+ // The session and the suggestions go only after any click has landed,
181
+ // and once however many blurs ask.
182
+ clearTimeout(leaving.current);
183
+ leaving.current = setTimeout(() => {
184
+ leaving.current = undefined;
185
+ latestProvider.current?.abandon?.();
186
+ // Nothing stale is offered after the visitor leaves; typing again asks anew.
187
+ setSuggestions([]);
188
+ }, 0);
189
+ };
190
+
191
+ /** Ends a press that brought no pick; a field the press left is then left properly. */
192
+ const endPress = () => {
193
+ clearTimeout(pressEnd.current);
194
+ if (!picking.current) return;
195
+ picking.current = false;
196
+ if (document.activeElement !== inputRef.current) leave();
197
+ };
198
+ const latestEndPress = useRef(endPress);
199
+ latestEndPress.current = endPress;
200
+
201
+ // A press on an option the list no longer holds (its suggestions replaced,
202
+ // or the list gone) is no pick, so the guard never outlives its option.
203
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the suggestions are what a press belongs to; the press ends when they change
204
+ useEffect(() => () => latestEndPress.current(), [suggestions]);
205
+
206
+ // Nothing waits on a field that is gone, but a leave it had begun (a blur
207
+ // just before the field went) still ends the provider's session.
208
+ useEffect(
209
+ () => () => {
210
+ clearTimeout(pressEnd.current);
211
+ if (leaving.current !== undefined) {
212
+ clearTimeout(leaving.current);
213
+ leaving.current = undefined;
214
+ latestProvider.current?.abandon?.();
215
+ }
216
+ },
217
+ [],
218
+ );
219
+
220
+ useEffect(() => {
221
+ if (!hasProvider) return;
222
+ if (picked.current === query) return;
223
+ picked.current = null;
224
+ const asked = query.trim();
225
+ if (asked.length < minLength) {
226
+ lookups.cancel();
227
+ setSuggestions([]);
228
+ setOpen(false);
229
+ setActive(-1);
230
+ return;
231
+ }
232
+ pending.current = setTimeout(() => {
233
+ const source = latestProvider.current;
234
+ if (!source) return;
235
+ lookups
236
+ .run((signal) => source.suggest(asked, { signal }))
237
+ .then(
238
+ (answer) => {
239
+ if (answer.stale) return;
240
+ offeredBy.current = source;
241
+ setSuggestions(answer.value);
242
+ setActive(-1);
243
+ // Never opens under a field the visitor has left.
244
+ setOpen(answer.value.length > 0 && document.activeElement === inputRef.current);
245
+ setAnnounce(latestCount.current(answer.value.length));
246
+ },
247
+ // A lookup that fails offers nothing; the plain fields still take the address.
248
+ () => {
249
+ setSuggestions([]);
250
+ setOpen(false);
251
+ },
252
+ );
253
+ }, debounceMs);
254
+ return () => clearTimeout(pending.current);
255
+ }, [query, hasProvider, minLength, debounceMs, lookups]);
256
+
257
+ // A form's reset empties the search with the rest of the form.
258
+ // biome-ignore lint/correctness/useExhaustiveDependencies: hasProvider is read through the input it puts on the page, which the effect finds by ref
259
+ useEffect(() => {
260
+ const form = inputRef.current?.form;
261
+ if (!form) return;
262
+ const onReset = () => {
263
+ lookups.cancel();
264
+ resolves.cancel();
265
+ picked.current = null;
266
+ setQuery("");
267
+ setSuggestions([]);
268
+ setOpen(false);
269
+ setActive(-1);
270
+ };
271
+ form.addEventListener("reset", onReset);
272
+ return () => form.removeEventListener("reset", onReset);
273
+ // The input exists only once there is a provider, so a provider that
274
+ // arrives after the first render attaches the listener then.
275
+ }, [lookups, resolves, hasProvider]);
276
+
277
+ if (!provider) return null;
278
+
279
+ const pick = (suggestion: AddressSuggestion) => {
280
+ picking.current = false;
281
+ clearTimeout(pressEnd.current);
282
+ clearTimeout(leaving.current);
283
+ leaving.current = undefined;
284
+ const text = pickedText(suggestion);
285
+ // What the visitor typed, to go back to if the pick cannot be resolved.
286
+ const typed = query;
287
+ onChoose?.(suggestion);
288
+ picked.current = text;
289
+ lookups.cancel();
290
+ setQuery(text);
291
+ // The suggestions belong to the session the pick ends; none are offered again.
292
+ setSuggestions([]);
293
+ setOpen(false);
294
+ setActive(-1);
295
+ const source = offeredBy.current ?? provider;
296
+ resolves
297
+ .run((signal) => source.resolve(suggestion, { signal }))
298
+ .then(
299
+ (answer) => {
300
+ if (answer.stale) return;
301
+ // A form that has moved on declines the pick: the field goes back
302
+ // to what was typed, as it does when the address cannot be read.
303
+ // The restored words count as answered, so no new lookup (and no
304
+ // new billable request) runs until the visitor types again.
305
+ if (latestPick.current(answer.value) === false) {
306
+ picked.current = typed;
307
+ setQuery(typed);
308
+ }
309
+ },
310
+ () => {
311
+ // The address could not be read: the field goes back to what was
312
+ // typed, which asks again, so the field never shows an address the
313
+ // form did not receive.
314
+ picked.current = null;
315
+ setQuery(typed);
316
+ },
317
+ );
318
+ };
319
+
320
+ const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
321
+ const count = suggestions.length;
322
+ if (event.key === "ArrowDown" && count > 0) {
323
+ event.preventDefault();
324
+ if (!open) setOpen(true);
325
+ setActive((index) => (index + 1) % count);
326
+ } else if (event.key === "ArrowUp" && count > 0) {
327
+ event.preventDefault();
328
+ if (!open) setOpen(true);
329
+ setActive((index) => (index <= 0 ? count - 1 : index - 1));
330
+ } else if (event.key === "Enter" && open && active >= 0) {
331
+ // Picks the highlighted address rather than sending the form.
332
+ event.preventDefault();
333
+ const chosen = suggestions[active];
334
+ if (chosen) pick(chosen);
335
+ } else if (event.key === "Escape" && open) {
336
+ event.preventDefault();
337
+ setOpen(false);
338
+ setActive(-1);
339
+ }
340
+ };
341
+
342
+ return (
343
+ <div className={["address-search", className].filter(Boolean).join(" ")}>
344
+ <label htmlFor={inputId} className="address-search-label">
345
+ <span id={labelTextId}>{label}</span>
346
+ {hint && (
347
+ <>
348
+ {" "}
349
+ <small id={hintId}>{hint}</small>
350
+ </>
351
+ )}
352
+ </label>
353
+ <div className="address-search-bar">
354
+ <MapPin className="address-search-pin" size={20} aria-hidden="true" />
355
+ <input
356
+ ref={inputRef}
357
+ id={inputId}
358
+ className="address-search-input"
359
+ type="text"
360
+ role="combobox"
361
+ aria-expanded={open}
362
+ aria-controls={listId}
363
+ aria-autocomplete="list"
364
+ // The words and the hint named apart, so the name always has the space between them.
365
+ aria-labelledby={hint ? `${labelTextId} ${hintId}` : labelTextId}
366
+ aria-activedescendant={open && active >= 0 ? optionId(active) : undefined}
367
+ autoComplete="off"
368
+ placeholder={placeholder}
369
+ value={query}
370
+ onChange={(event) => {
371
+ // Typing again drops a pick still being read, so it never lands late.
372
+ resolves.cancel();
373
+ setQuery(event.target.value);
374
+ }}
375
+ onKeyDown={onKeyDown}
376
+ onFocus={() => latestProvider.current?.prepare?.()}
377
+ onBlur={() => {
378
+ // A press on a suggestion moved focus first (a touch browser, a
379
+ // screen reader): the pick is coming, and keeps what it needs.
380
+ if (picking.current) return;
381
+ // Leaving the field stops the pause and the lookup in flight,
382
+ // so no answer reopens the list behind the visitor.
383
+ leave();
384
+ }}
385
+ />
386
+ </div>
387
+ <div className="address-search-popup" hidden={!open}>
388
+ <div id={listId} className="address-search-list" role="listbox" aria-label={listLabel}>
389
+ {suggestions.map((suggestion, index) => (
390
+ // biome-ignore lint/a11y/useFocusableInteractive: focus stays in the field, which moves the highlight by aria-activedescendant
391
+ // biome-ignore lint/a11y/useKeyWithClickEvents: the keys live on the field, for the same reason
392
+ <div
393
+ key={suggestion.id}
394
+ id={optionId(index)}
395
+ role="option"
396
+ aria-selected={index === active}
397
+ className="address-search-option"
398
+ // Keeps focus in the field, so the press is a pick and not a blur.
399
+ onMouseDown={(event) => event.preventDefault()}
400
+ onPointerDown={() => {
401
+ clearTimeout(pressEnd.current);
402
+ picking.current = true;
403
+ }}
404
+ // No click follows a cancelled press (a scroll that took the touch).
405
+ onPointerCancel={endPress}
406
+ // A mouse press dragged off its suggestion is released elsewhere,
407
+ // where this option hears no pointerup: the wait starts here, and
408
+ // a press that comes back and clicks still picks.
409
+ onPointerLeave={() => {
410
+ if (!picking.current) return;
411
+ clearTimeout(pressEnd.current);
412
+ pressEnd.current = setTimeout(endPress, PRESS_WAIT_MS);
413
+ }}
414
+ // A click follows a pointerup at once, or after a touch's short
415
+ // delay; a press that brings none ends after this.
416
+ onPointerUp={() => {
417
+ clearTimeout(pressEnd.current);
418
+ pressEnd.current = setTimeout(endPress, PRESS_WAIT_MS);
419
+ }}
420
+ onClick={() => pick(suggestion)}
421
+ >
422
+ <span className="address-search-option-text">{suggestion.text}</span>
423
+ {suggestion.secondary && (
424
+ <span className="address-search-option-secondary">{suggestion.secondary}</span>
425
+ )}
426
+ </div>
427
+ ))}
428
+ </div>
429
+ {attribution && <div className="address-search-attribution">{attribution}</div>}
430
+ </div>
431
+ {/* An explicit live region under Component Rules 14: a combobox's count
432
+ has to be heard as it changes, and it changes once per pause in the
433
+ typing, never on a tick. React writes the words only when they differ,
434
+ so the same count is not announced twice. */}
435
+ <div className="visually-hidden" aria-live="polite">
436
+ {announce}
437
+ </div>
438
+ </div>
439
+ );
440
+ }
@@ -0,0 +1,55 @@
1
+ import type { AnchorHTMLAttributes, ReactNode } from "react";
2
+ import { breakableEmail } from "../lib/emailText";
3
+
4
+ export interface EmailLinkProps
5
+ extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "target" | "children"> {
6
+ email: string;
7
+ /**
8
+ * The visible words. Left out, the address itself, marked to break after
9
+ * its @ and before each dot of the domain (`breakableEmail`), never
10
+ * inside a word.
11
+ */
12
+ children?: ReactNode;
13
+ }
14
+
15
+ const warned = new Set<string>();
16
+
17
+ /** Says once, in development only, that an address was left unlinked. */
18
+ function warnOnce(email: string) {
19
+ if (!import.meta.env?.DEV || warned.has(email)) return;
20
+ warned.add(email);
21
+ console.warn(
22
+ `[atelic-ui] "${email}" is not an address to write to; it is shown without a mailto: link.`,
23
+ );
24
+ }
25
+
26
+ /**
27
+ * The `mailto:` href for an address, the one place it is built: the address
28
+ * exactly as given, as every link drew it before 8.5.0, so the browser is
29
+ * never stricter than it was; a malformed configured address is the build
30
+ * guard's to catch (`contactProblems`). An empty one has no href.
31
+ */
32
+ export function emailHref(email: string): string | undefined {
33
+ // A config written in plain JavaScript can hand over anything; only words link.
34
+ return typeof email === "string" && email.trim() ? `mailto:${email}` : undefined;
35
+ }
36
+
37
+ /**
38
+ * An email address as a link that writes to it (Component Rules 17), the
39
+ * one way the package draws one. It never opens a new tab (Component Rules
40
+ * 12). Its href is `emailHref`'s; only an empty address is shown as plain
41
+ * words, with a warning in development.
42
+ */
43
+ export function EmailLink({ email, children, className, ...anchor }: EmailLinkProps) {
44
+ const href = emailHref(email);
45
+ const words = children ?? (typeof email === "string" ? breakableEmail(email) : null);
46
+ if (!href) {
47
+ warnOnce(String(email));
48
+ return <span className={className}>{words}</span>;
49
+ }
50
+ return (
51
+ <a className={className} href={href} {...anchor}>
52
+ {words}
53
+ </a>
54
+ );
55
+ }
@@ -0,0 +1,161 @@
1
+ import {
2
+ type CSSProperties,
3
+ type ReactNode,
4
+ type RefObject,
5
+ useEffect,
6
+ useId,
7
+ useLayoutEffect,
8
+ useRef,
9
+ useState,
10
+ } from "react";
11
+
12
+ /** A layout effect in a browser, so a measure lands before paint; an effect where nothing paints (prerender). */
13
+ const useMeasureEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
14
+
15
+ export interface ExpandableTextProps {
16
+ /** The text: prose only, since all of it stays in the page while clamped. */
17
+ children: ReactNode;
18
+ /** The lines shown while closed. Defaults to 3. */
19
+ lines?: number;
20
+ /**
21
+ * What shows only once opened, under the text: links, say, the terms and
22
+ * the privacy policy a consent line points to. It stays in the page while
23
+ * closed, hidden and `inert`, so its links leave the tab order.
24
+ */
25
+ more?: ReactNode;
26
+ /** The control's words while closed. */
27
+ moreLabel?: string;
28
+ /** The control's words while open. */
29
+ lessLabel?: string;
30
+ /**
31
+ * Draws the text as the label of this control's id, so a checkbox's name
32
+ * is the whole text, clamped or not: a consent line.
33
+ */
34
+ labelFor?: string;
35
+ /** Open on first render. */
36
+ defaultExpanded?: boolean;
37
+ /**
38
+ * Sets the control at the end of the last line rather than under the
39
+ * text (8.5.0): closed, over the line's end on a fade of
40
+ * `--expandable-ground` (the page surface unless set), after an
41
+ * ellipsis; open, straight after the last word. It stays a sibling of
42
+ * the text, so a checkbox the text labels never hears its words.
43
+ */
44
+ inline?: boolean;
45
+ className?: string;
46
+ }
47
+
48
+ /**
49
+ * Long text cut to a few lines, with a Show more control under it that
50
+ * opens the rest and a Show less that closes it again. The control carries
51
+ * `aria-expanded` and names the text it controls.
52
+ *
53
+ * The cut is drawn, never made: the whole text stays in the page, so a
54
+ * screen reader reads all of it, a search finds it, and a checkbox it
55
+ * labels (`labelFor`) is named by every word. That is why the text is prose
56
+ * only; anything a reader acts on goes in `more`, which is hidden and
57
+ * `inert` while closed. When the text fits in its lines and there is no
58
+ * `more`, the control is not drawn (measured once the page is up, so a
59
+ * prerendered page shows it until then).
60
+ */
61
+ export function ExpandableText({
62
+ children,
63
+ lines = 3,
64
+ more,
65
+ moreLabel = "Show more",
66
+ lessLabel = "Show less",
67
+ labelFor,
68
+ defaultExpanded = false,
69
+ inline = false,
70
+ className,
71
+ }: ExpandableTextProps) {
72
+ const minted = useId();
73
+ const bodyId = `${minted}-text`;
74
+ const moreId = `${minted}-more`;
75
+ const bodyRef = useRef<HTMLElement>(null);
76
+ const [open, setOpen] = useState(defaultExpanded);
77
+ // Whether the text runs past its lines; unknown until measured.
78
+ const [overflows, setOverflows] = useState<boolean | null>(null);
79
+
80
+ useMeasureEffect(() => {
81
+ const body = bodyRef.current;
82
+ if (!body || open) return;
83
+ const measure = () => setOverflows(body.scrollHeight > body.clientHeight + 1);
84
+ measure();
85
+ if (typeof ResizeObserver === "undefined") return;
86
+ const observer = new ResizeObserver(measure);
87
+ observer.observe(body);
88
+ return () => observer.disconnect();
89
+ }, [open]);
90
+
91
+ const hasMore = more != null && more !== false;
92
+ // Inline text that fits has nothing hidden, so what `more` holds shows
93
+ // and no control is drawn; inline text not yet measured has its control
94
+ // placed but unseen, so measuring never moves the page (8.6.0).
95
+ const fitsInline = inline && !open && overflows === false;
96
+ const unmeasuredInline = inline && !open && overflows === null;
97
+ const moreShown = open || (fitsInline && hasMore);
98
+ const showControl = inline ? !fitsInline : hasMore || open || overflows !== false;
99
+ const style = { "--expandable-lines": lines } as CSSProperties;
100
+ // is-clamped is the clamp the measuring needs, which cuts nothing when the
101
+ // text fits; is-cut says it was measured cutting, and only then is an
102
+ // inline control seen over the line's end (8.6.0). Before measuring (a
103
+ // prerendered page) the inline control already sits there, out of the
104
+ // flow and unseen, so nothing moves when it shows.
105
+ const bodyClass = [
106
+ "expandable-text-body",
107
+ !open && "is-clamped",
108
+ !open && overflows === true && "is-cut",
109
+ ]
110
+ .filter(Boolean)
111
+ .join(" ");
112
+
113
+ const control = showControl && (
114
+ <button
115
+ type="button"
116
+ className="expandable-text-toggle"
117
+ aria-expanded={open}
118
+ aria-controls={hasMore ? `${bodyId} ${moreId}` : bodyId}
119
+ // Unseen until measured: out of the accessibility tree and the tab order.
120
+ aria-hidden={unmeasuredInline || undefined}
121
+ tabIndex={unmeasuredInline ? -1 : undefined}
122
+ onClick={() => setOpen((was) => !was)}
123
+ >
124
+ <span className="expandable-text-toggle-label">{open ? lessLabel : moreLabel}</span>
125
+ </button>
126
+ );
127
+
128
+ return (
129
+ <div
130
+ className={["expandable-text", inline && "is-inline", className].filter(Boolean).join(" ")}
131
+ >
132
+ {labelFor ? (
133
+ <label
134
+ ref={bodyRef as RefObject<HTMLLabelElement>}
135
+ id={bodyId}
136
+ htmlFor={labelFor}
137
+ className={bodyClass}
138
+ style={style}
139
+ >
140
+ {children}
141
+ </label>
142
+ ) : (
143
+ <div
144
+ ref={bodyRef as RefObject<HTMLDivElement>}
145
+ id={bodyId}
146
+ className={bodyClass}
147
+ style={style}
148
+ >
149
+ {children}
150
+ </div>
151
+ )}
152
+ {inline && control}
153
+ {hasMore && (
154
+ <div id={moreId} className="expandable-text-more" hidden={!moreShown} inert={!moreShown}>
155
+ {more}
156
+ </div>
157
+ )}
158
+ {!inline && control}
159
+ </div>
160
+ );
161
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The attribution Google's terms ask for wherever its Places suggestions
3
+ * show without a Google map: the words "Google Maps", never modified,
4
+ * translated, or wrapped (`translate="no"`), at 12 to 16 pixels in a regular
5
+ * weight. The terms prefer Google's logo where there is room; a site that
6
+ * draws it passes its own node as `AddressSearch`'s `attribution` instead.
7
+ */
8
+ export function GoogleMapsAttribution() {
9
+ return (
10
+ <span className="google-maps-attribution" translate="no">
11
+ Google Maps
12
+ </span>
13
+ );
14
+ }