@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
@@ -114,13 +114,42 @@ function eventID(): string {
114
114
  return id;
115
115
  }
116
116
 
117
- /** The thrown value as Sentry's exception: its type, message, and frames. */
118
- function exceptionOf(error: unknown) {
119
- if (error instanceof Error) {
120
- const frames = parseStack(error.stack);
117
+ /** How many causes deep a report follows a thrown value's `cause`. */
118
+ const CAUSE_DEPTH = 5;
119
+
120
+ /** The longest an exception's message is kept in a report. */
121
+ const EXCEPTION_VALUE_MAX = 300;
122
+
123
+ /**
124
+ * One thrown value as Sentry's exception: its type, message, and frames. A
125
+ * cause's words are upstream free text (a resolver's, a socket's), so they
126
+ * take the refusal's scrub, and its `code` (ENOTFOUND, ECONNRESET, a TLS
127
+ * error's) leads its message when the message does not already say it, so a
128
+ * DNS fault reads apart from a refused connection.
129
+ */
130
+ function exceptionOne(error: unknown, isCause: boolean) {
131
+ const words = (text: string) => (isCause ? scrub(text) : text).slice(0, EXCEPTION_VALUE_MAX);
132
+ const shaped =
133
+ error instanceof Error ||
134
+ (isCause &&
135
+ error !== null &&
136
+ typeof error === "object" &&
137
+ ("message" in error || "code" in error));
138
+ if (shaped) {
139
+ const { name, message, stack, code } = error as {
140
+ name?: unknown;
141
+ message?: unknown;
142
+ stack?: unknown;
143
+ code?: unknown;
144
+ };
145
+ const text = typeof message === "string" ? message : "";
146
+ const coded =
147
+ isCause && (typeof code === "string" || typeof code === "number") ? String(code) : "";
148
+ const value = coded && !text.includes(coded) ? (text ? `${coded}: ${text}` : coded) : text;
149
+ const frames = parseStack(typeof stack === "string" ? stack : undefined);
121
150
  return {
122
- type: error.name || "Error",
123
- value: error.message,
151
+ type: typeof name === "string" && name ? name : "Error",
152
+ value: words(value),
124
153
  ...(frames.length ? { stacktrace: { frames } } : {}),
125
154
  };
126
155
  }
@@ -130,7 +159,47 @@ function exceptionOf(error: unknown) {
130
159
  } catch {
131
160
  value = String(error);
132
161
  }
133
- return { type: "Error", value: value ?? String(error) };
162
+ return { type: "Error", value: words(value ?? String(error)) };
163
+ }
164
+
165
+ /** A value's `cause`, read so that a throwing getter reads as none. */
166
+ function causeOf(error: unknown): unknown {
167
+ if (error === null || typeof error !== "object") return undefined;
168
+ try {
169
+ return (error as { cause?: unknown }).cause;
170
+ } catch {
171
+ return undefined;
172
+ }
173
+ }
174
+
175
+ /**
176
+ * The thrown value and the causes under it, up to five deep, as Sentry's
177
+ * exception values: innermost first and the thrown value last, as Sentry
178
+ * orders a chain, each cause linked to the one it caused (`mechanism`
179
+ * `chained`, `source` `cause`, its own `exception_id` and its parent's
180
+ * `parent_id`), the thrown value `exception_id` 0 under the generic
181
+ * mechanism, handled, since the reporter is called by code that caught it.
182
+ * A cause met twice (a cycle) ends the chain. A value with no cause is the
183
+ * one exception it always was, with no mechanism.
184
+ */
185
+ function exceptionsOf(error: unknown) {
186
+ const chain: unknown[] = [error];
187
+ const seen = new Set<unknown>([error]);
188
+ for (let cause = causeOf(error); chain.length <= CAUSE_DEPTH; cause = causeOf(cause)) {
189
+ if (cause === undefined || cause === null || seen.has(cause)) break;
190
+ seen.add(cause);
191
+ chain.push(cause);
192
+ }
193
+ if (chain.length === 1) return [exceptionOne(error, false)];
194
+ return chain
195
+ .map((value, id) => ({
196
+ ...exceptionOne(value, id > 0),
197
+ mechanism:
198
+ id === 0
199
+ ? { type: "generic", handled: true, exception_id: 0 }
200
+ : { type: "chained", source: "cause", exception_id: id, parent_id: id - 1 },
201
+ }))
202
+ .reverse();
134
203
  }
135
204
 
136
205
  /**
@@ -179,7 +248,7 @@ export function buildEnvelope(
179
248
  ...(environment ? { environment } : {}),
180
249
  tags: { runtime: runtime(), ...options.tags },
181
250
  ...(request ? { request } : {}),
182
- exception: { values: [exceptionOf(error)] },
251
+ exception: { values: exceptionsOf(error) },
183
252
  };
184
253
  const header = { event_id: id, sent_at: now.toISOString(), dsn, sdk: SDK };
185
254
  return [JSON.stringify(header), JSON.stringify({ type: "event" }), JSON.stringify(event)].join(
@@ -301,17 +370,24 @@ const ADDRESS = /[^\s@<>()[\]"',;:]+@[\p{L}\p{N}_-]+(?:\.[\p{L}\p{N}_-]+)+/gu;
301
370
  /** A separator inside a phone number: a space, a dot, a slash, or any hyphen or dash. */
302
371
  const SEP = "[\\s./\\u2010-\\u2015\\u2212-]";
303
372
 
373
+ /** One part of a dotted IPv4 address, 0 to 255. */
374
+ const OCTET = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
375
+
304
376
  /**
305
- * A run shaped like a phone number: an optional country code, then an area
306
- * code in parentheses and the number after it, or at least three groups of
307
- * digits joined by separators, the last of three or four digits, or a plus
308
- * sign and seven to fifteen digits run together (E.164). A date
309
- * (2026-11-23), a bare id (12345678), and a count beside a year (120 2026)
310
- * are none of these, and stay.
377
+ * A run shaped like a phone number: an optional country code (a plus sign
378
+ * and one to three digits, or one to three digits and a separator, as in
379
+ * 1-555-555-0142), then an area code in parentheses and the number after
380
+ * it, or at least three groups of digits joined by separators, the last of
381
+ * three or four digits, or a plus sign and seven to fifteen digits run
382
+ * together (E.164); any of them may close on an extension (x12, ext. 12). A
383
+ * date (2026-11-23), a bare id (12345678), a count beside a year (120
384
+ * 2026), a status (429), and a dotted IPv4 address (192.168.10.200) are none
385
+ * of these, and stay. A run starts at a word's edge and never just after a
386
+ * digit's dot, so no tail of a longer dotted run is taken for one.
311
387
  */
312
388
  const PHONE = new RegExp(
313
- `(?<![\\w+-])\\+\\d{7,15}(?![\\w-])|(?<![\\w+-])(?:\\+\\d{1,3}${SEP}?)?(?:\\(\\d{2,4}\\)${SEP}?\\d{2,4}(?:${SEP}\\d{3,4})?|\\d{2,4}(?:${SEP}\\d{2,4}){1,2}${SEP}\\d{3,4})(?![\\w-])`,
314
- "gu",
389
+ `(?<![\\w+-])(?<!\\d\\.)(?:\\+\\d{7,15}|(?!(?:${OCTET}\\.){3}${OCTET}(?![\\w.-]))(?:\\+\\d{1,3}${SEP}?|\\d{1,3}${SEP})?(?:\\(\\d{2,4}\\)${SEP}?\\d{2,4}(?:${SEP}\\d{3,4})?|\\d{2,4}(?:${SEP}\\d{2,4}){1,2}${SEP}\\d{3,4}))(?:\\s*(?:x|ext\\.?|extension)\\s*\\d{1,6})?(?![\\w-])`,
390
+ "giu",
315
391
  );
316
392
 
317
393
  /** A refusal's field with every address and phone number in it replaced. */
@@ -0,0 +1,341 @@
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
+ /** Called with the parts of the address the visitor picked. */
61
+ onPick: (address: AddressParts) => void;
62
+ /**
63
+ * Called the moment a suggestion is chosen, before its parts arrive, so a
64
+ * form can tell a pick that lands after the visitor moved on.
65
+ */
66
+ onChoose?: (suggestion: AddressSuggestion) => void;
67
+ /** Drawn under the suggestions, for a provider whose terms ask for it ("Powered by ..."). */
68
+ attribution?: ReactNode;
69
+ /** The suggestion list's accessible name. */
70
+ listLabel?: string;
71
+ /** What a screen reader hears when the suggestions change. */
72
+ countLabel?: (count: number) => string;
73
+ /** Characters typed before the first lookup. Defaults to 3. */
74
+ minLength?: number;
75
+ /** The pause in the typing before a lookup, in milliseconds. Defaults to 250. */
76
+ debounceMs?: number;
77
+ /** The input's id; minted when left out. */
78
+ id?: string;
79
+ className?: string;
80
+ }
81
+
82
+ const defaultCount = (count: number) =>
83
+ count === 0 ? "No suggestions" : count === 1 ? "1 suggestion" : `${count} suggestions`;
84
+
85
+ /** The line an address reads as once picked: the main line and the rest. */
86
+ const pickedText = (suggestion: AddressSuggestion) =>
87
+ [suggestion.text, suggestion.secondary].filter(Boolean).join(", ");
88
+
89
+ /**
90
+ * A text field that offers addresses as the visitor types and, on a pick,
91
+ * hands back the street, city, state, and ZIP. It knows no service: the
92
+ * suggestions come from `provider`, and with no provider it renders nothing,
93
+ * so the plain address fields beside it stand alone.
94
+ *
95
+ * It is the ARIA combobox with a list popup: the input keeps focus while
96
+ * the arrows move a highlight through the suggestions
97
+ * (`aria-activedescendant`), Enter picks the highlighted one, Escape closes
98
+ * the list, and a click picks one too. A lookup waits for a pause in the
99
+ * typing, and an answer that arrives after a newer question was asked is
100
+ * dropped. The count of suggestions is announced each time it changes.
101
+ * Nothing touches the page until an effect or a handler runs, so it
102
+ * prerenders.
103
+ */
104
+ export function AddressSearch({
105
+ provider,
106
+ label,
107
+ hint,
108
+ placeholder,
109
+ onPick,
110
+ onChoose,
111
+ attribution,
112
+ listLabel = "Suggestions",
113
+ countLabel = defaultCount,
114
+ minLength = 3,
115
+ debounceMs = 250,
116
+ id,
117
+ className,
118
+ }: AddressSearchProps) {
119
+ const minted = useId();
120
+ const inputId = id ?? `${minted}-input`;
121
+ const listId = `${minted}-list`;
122
+ const labelTextId = `${minted}-label`;
123
+ const hintId = `${minted}-hint`;
124
+ const optionId = (index: number) => `${minted}-option-${index}`;
125
+ const inputRef = useRef<HTMLInputElement>(null);
126
+ const [query, setQuery] = useState("");
127
+ const [suggestions, setSuggestions] = useState<AddressSuggestion[]>([]);
128
+ const [open, setOpen] = useState(false);
129
+ const [active, setActive] = useState(-1);
130
+ const [announce, setAnnounce] = useState("");
131
+ // The text a pick wrote into the field, so writing it asks nothing.
132
+ const picked = useRef<string | null>(null);
133
+ const lookups = useMemo(() => latestOnly(), []);
134
+ const resolves = useMemo(() => latestOnly(), []);
135
+ // The latest of each function prop, read when it is needed, so a site
136
+ // passing an inline function or provider never starts a lookup by rendering.
137
+ const latestPick = useRef(onPick);
138
+ latestPick.current = onPick;
139
+ const latestProvider = useRef(provider);
140
+ latestProvider.current = provider;
141
+ const latestCount = useRef(countLabel);
142
+ latestCount.current = countLabel;
143
+ // The provider whose answer the offered suggestions are, which a pick
144
+ // resolves through even if the site has passed a new one since.
145
+ const offeredBy = useRef<AddressProvider | null>(null);
146
+ // The pause before a lookup, held so a blur can stop it.
147
+ const pending = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
148
+ const hasProvider = Boolean(provider);
149
+
150
+ useEffect(() => {
151
+ if (!hasProvider) return;
152
+ if (picked.current === query) return;
153
+ picked.current = null;
154
+ const asked = query.trim();
155
+ if (asked.length < minLength) {
156
+ lookups.cancel();
157
+ setSuggestions([]);
158
+ setOpen(false);
159
+ setActive(-1);
160
+ return;
161
+ }
162
+ pending.current = setTimeout(() => {
163
+ const source = latestProvider.current;
164
+ if (!source) return;
165
+ lookups
166
+ .run((signal) => source.suggest(asked, { signal }))
167
+ .then(
168
+ (answer) => {
169
+ if (answer.stale) return;
170
+ offeredBy.current = source;
171
+ setSuggestions(answer.value);
172
+ setActive(-1);
173
+ // Never opens under a field the visitor has left.
174
+ setOpen(answer.value.length > 0 && document.activeElement === inputRef.current);
175
+ setAnnounce(latestCount.current(answer.value.length));
176
+ },
177
+ // A lookup that fails offers nothing; the plain fields still take the address.
178
+ () => {
179
+ setSuggestions([]);
180
+ setOpen(false);
181
+ },
182
+ );
183
+ }, debounceMs);
184
+ return () => clearTimeout(pending.current);
185
+ }, [query, hasProvider, minLength, debounceMs, lookups]);
186
+
187
+ // A form's reset empties the search with the rest of the form.
188
+ // biome-ignore lint/correctness/useExhaustiveDependencies: hasProvider is read through the input it puts on the page, which the effect finds by ref
189
+ useEffect(() => {
190
+ const form = inputRef.current?.form;
191
+ if (!form) return;
192
+ const onReset = () => {
193
+ lookups.cancel();
194
+ resolves.cancel();
195
+ picked.current = null;
196
+ setQuery("");
197
+ setSuggestions([]);
198
+ setOpen(false);
199
+ setActive(-1);
200
+ };
201
+ form.addEventListener("reset", onReset);
202
+ return () => form.removeEventListener("reset", onReset);
203
+ // The input exists only once there is a provider, so a provider that
204
+ // arrives after the first render attaches the listener then.
205
+ }, [lookups, resolves, hasProvider]);
206
+
207
+ if (!provider) return null;
208
+
209
+ const pick = (suggestion: AddressSuggestion) => {
210
+ const text = pickedText(suggestion);
211
+ // What the visitor typed, to go back to if the pick cannot be resolved.
212
+ const typed = query;
213
+ onChoose?.(suggestion);
214
+ picked.current = text;
215
+ lookups.cancel();
216
+ setQuery(text);
217
+ // The suggestions belong to the session the pick ends; none are offered again.
218
+ setSuggestions([]);
219
+ setOpen(false);
220
+ setActive(-1);
221
+ const source = offeredBy.current ?? provider;
222
+ resolves
223
+ .run((signal) => source.resolve(suggestion, { signal }))
224
+ .then(
225
+ (answer) => {
226
+ if (!answer.stale) latestPick.current(answer.value);
227
+ },
228
+ () => {
229
+ // The address could not be read: the field goes back to what was
230
+ // typed, which asks again, so the field never shows an address the
231
+ // form did not receive.
232
+ picked.current = null;
233
+ setQuery(typed);
234
+ },
235
+ );
236
+ };
237
+
238
+ const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
239
+ const count = suggestions.length;
240
+ if (event.key === "ArrowDown" && count > 0) {
241
+ event.preventDefault();
242
+ if (!open) setOpen(true);
243
+ setActive((index) => (index + 1) % count);
244
+ } else if (event.key === "ArrowUp" && count > 0) {
245
+ event.preventDefault();
246
+ if (!open) setOpen(true);
247
+ setActive((index) => (index <= 0 ? count - 1 : index - 1));
248
+ } else if (event.key === "Enter" && open && active >= 0) {
249
+ // Picks the highlighted address rather than sending the form.
250
+ event.preventDefault();
251
+ const chosen = suggestions[active];
252
+ if (chosen) pick(chosen);
253
+ } else if (event.key === "Escape" && open) {
254
+ event.preventDefault();
255
+ setOpen(false);
256
+ setActive(-1);
257
+ }
258
+ };
259
+
260
+ return (
261
+ <div className={["address-search", className].filter(Boolean).join(" ")}>
262
+ <label htmlFor={inputId} className="address-search-label">
263
+ <span id={labelTextId}>{label}</span>
264
+ {hint && (
265
+ <>
266
+ {" "}
267
+ <small id={hintId}>{hint}</small>
268
+ </>
269
+ )}
270
+ </label>
271
+ <div className="address-search-bar">
272
+ <MapPin className="address-search-pin" size={20} aria-hidden="true" />
273
+ <input
274
+ ref={inputRef}
275
+ id={inputId}
276
+ className="address-search-input"
277
+ type="text"
278
+ role="combobox"
279
+ aria-expanded={open}
280
+ aria-controls={listId}
281
+ aria-autocomplete="list"
282
+ // The words and the hint named apart, so the name always has the space between them.
283
+ aria-labelledby={hint ? `${labelTextId} ${hintId}` : labelTextId}
284
+ aria-activedescendant={open && active >= 0 ? optionId(active) : undefined}
285
+ autoComplete="off"
286
+ placeholder={placeholder}
287
+ value={query}
288
+ onChange={(event) => {
289
+ // Typing again drops a pick still being read, so it never lands late.
290
+ resolves.cancel();
291
+ setQuery(event.target.value);
292
+ }}
293
+ onKeyDown={onKeyDown}
294
+ onFocus={() => latestProvider.current?.prepare?.()}
295
+ onBlur={() => {
296
+ // Leaving the field stops the pause and the lookup in flight,
297
+ // so no answer reopens the list behind the visitor.
298
+ clearTimeout(pending.current);
299
+ lookups.cancel();
300
+ latestProvider.current?.abandon?.();
301
+ // Nothing stale is offered after the visitor leaves; typing again asks anew.
302
+ setSuggestions([]);
303
+ setOpen(false);
304
+ setActive(-1);
305
+ }}
306
+ />
307
+ </div>
308
+ <div className="address-search-popup" hidden={!open}>
309
+ <div id={listId} className="address-search-list" role="listbox" aria-label={listLabel}>
310
+ {suggestions.map((suggestion, index) => (
311
+ // biome-ignore lint/a11y/useFocusableInteractive: focus stays in the field, which moves the highlight by aria-activedescendant
312
+ // biome-ignore lint/a11y/useKeyWithClickEvents: the keys live on the field, for the same reason
313
+ <div
314
+ key={suggestion.id}
315
+ id={optionId(index)}
316
+ role="option"
317
+ aria-selected={index === active}
318
+ className="address-search-option"
319
+ // Keeps focus in the field, so the press is a pick and not a blur.
320
+ onMouseDown={(event) => event.preventDefault()}
321
+ onClick={() => pick(suggestion)}
322
+ >
323
+ <span className="address-search-option-text">{suggestion.text}</span>
324
+ {suggestion.secondary && (
325
+ <span className="address-search-option-secondary">{suggestion.secondary}</span>
326
+ )}
327
+ </div>
328
+ ))}
329
+ </div>
330
+ {attribution && <div className="address-search-attribution">{attribution}</div>}
331
+ </div>
332
+ {/* An explicit live region under Component Rules 14: a combobox's count
333
+ has to be heard as it changes, and it changes once per pause in the
334
+ typing, never on a tick. React writes the words only when they differ,
335
+ so the same count is not announced twice. */}
336
+ <div className="visually-hidden" aria-live="polite">
337
+ {announce}
338
+ </div>
339
+ </div>
340
+ );
341
+ }
@@ -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,137 @@
1
+ import {
2
+ type CSSProperties,
3
+ type ReactNode,
4
+ type RefObject,
5
+ useEffect,
6
+ useId,
7
+ useRef,
8
+ useState,
9
+ } from "react";
10
+
11
+ export interface ExpandableTextProps {
12
+ /** The text: prose only, since all of it stays in the page while clamped. */
13
+ children: ReactNode;
14
+ /** The lines shown while closed. Defaults to 3. */
15
+ lines?: number;
16
+ /**
17
+ * What shows only once opened, under the text: links, say, the terms and
18
+ * the privacy policy a consent line points to. It stays in the page while
19
+ * closed, hidden and `inert`, so its links leave the tab order.
20
+ */
21
+ more?: ReactNode;
22
+ /** The control's words while closed. */
23
+ moreLabel?: string;
24
+ /** The control's words while open. */
25
+ lessLabel?: string;
26
+ /**
27
+ * Draws the text as the label of this control's id, so a checkbox's name
28
+ * is the whole text, clamped or not: a consent line.
29
+ */
30
+ labelFor?: string;
31
+ /** Open on first render. */
32
+ defaultExpanded?: boolean;
33
+ /**
34
+ * Sets the control at the end of the last line rather than under the
35
+ * text (8.5.0): closed, over the line's end on a fade of
36
+ * `--expandable-ground` (the page surface unless set), after an
37
+ * ellipsis; open, straight after the last word. It stays a sibling of
38
+ * the text, so a checkbox the text labels never hears its words.
39
+ */
40
+ inline?: boolean;
41
+ className?: string;
42
+ }
43
+
44
+ /**
45
+ * Long text cut to a few lines, with a Show more control under it that
46
+ * opens the rest and a Show less that closes it again. The control carries
47
+ * `aria-expanded` and names the text it controls.
48
+ *
49
+ * The cut is drawn, never made: the whole text stays in the page, so a
50
+ * screen reader reads all of it, a search finds it, and a checkbox it
51
+ * labels (`labelFor`) is named by every word. That is why the text is prose
52
+ * only; anything a reader acts on goes in `more`, which is hidden and
53
+ * `inert` while closed. When the text fits in its lines and there is no
54
+ * `more`, the control is not drawn (measured once the page is up, so a
55
+ * prerendered page shows it until then).
56
+ */
57
+ export function ExpandableText({
58
+ children,
59
+ lines = 3,
60
+ more,
61
+ moreLabel = "Show more",
62
+ lessLabel = "Show less",
63
+ labelFor,
64
+ defaultExpanded = false,
65
+ inline = false,
66
+ className,
67
+ }: ExpandableTextProps) {
68
+ const minted = useId();
69
+ const bodyId = `${minted}-text`;
70
+ const moreId = `${minted}-more`;
71
+ const bodyRef = useRef<HTMLElement>(null);
72
+ const [open, setOpen] = useState(defaultExpanded);
73
+ // Whether the text runs past its lines; unknown until measured.
74
+ const [overflows, setOverflows] = useState<boolean | null>(null);
75
+
76
+ useEffect(() => {
77
+ const body = bodyRef.current;
78
+ if (!body || open) return;
79
+ const measure = () => setOverflows(body.scrollHeight > body.clientHeight + 1);
80
+ measure();
81
+ if (typeof ResizeObserver === "undefined") return;
82
+ const observer = new ResizeObserver(measure);
83
+ observer.observe(body);
84
+ return () => observer.disconnect();
85
+ }, [open]);
86
+
87
+ const hasMore = more != null && more !== false;
88
+ const showControl = hasMore || open || overflows !== false;
89
+ const style = { "--expandable-lines": lines } as CSSProperties;
90
+ const bodyClass = ["expandable-text-body", !open && "is-clamped"].filter(Boolean).join(" ");
91
+
92
+ const control = showControl && (
93
+ <button
94
+ type="button"
95
+ className="expandable-text-toggle"
96
+ aria-expanded={open}
97
+ aria-controls={hasMore ? `${bodyId} ${moreId}` : bodyId}
98
+ onClick={() => setOpen((was) => !was)}
99
+ >
100
+ <span className="expandable-text-toggle-label">{open ? lessLabel : moreLabel}</span>
101
+ </button>
102
+ );
103
+
104
+ return (
105
+ <div
106
+ className={["expandable-text", inline && "is-inline", className].filter(Boolean).join(" ")}
107
+ >
108
+ {labelFor ? (
109
+ <label
110
+ ref={bodyRef as RefObject<HTMLLabelElement>}
111
+ id={bodyId}
112
+ htmlFor={labelFor}
113
+ className={bodyClass}
114
+ style={style}
115
+ >
116
+ {children}
117
+ </label>
118
+ ) : (
119
+ <div
120
+ ref={bodyRef as RefObject<HTMLDivElement>}
121
+ id={bodyId}
122
+ className={bodyClass}
123
+ style={style}
124
+ >
125
+ {children}
126
+ </div>
127
+ )}
128
+ {inline && control}
129
+ {hasMore && (
130
+ <div id={moreId} className="expandable-text-more" hidden={!open} inert={!open}>
131
+ {more}
132
+ </div>
133
+ )}
134
+ {!inline && control}
135
+ </div>
136
+ );
137
+ }
@@ -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
+ }