@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
@@ -1,21 +1,156 @@
1
- import { type FormEvent, type ReactNode, useId, useState } from "react";
1
+ import { Check } from "lucide-react";
2
+ import {
3
+ type FormEvent,
4
+ type ReactNode,
5
+ type RefObject,
6
+ useEffect,
7
+ useId,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ } from "react";
12
+ import { MultiSelect } from "../components/MultiSelect";
13
+ import {
14
+ addressLine,
15
+ type ContactFormField,
16
+ type ContactFormRefusals,
17
+ type ContactFormShape,
18
+ type ContactFormValues,
19
+ checkContactForm,
20
+ contactFormBody,
21
+ firstRefused,
22
+ isZIP,
23
+ readContactForm,
24
+ } from "../lib/contactForm";
25
+ import { type GooglePlacesOptions, googlePlacesProvider } from "../lib/googlePlaces";
2
26
  import { isHoneypotFilled } from "../lib/honeypot";
27
+ import { newTabProps } from "../lib/newTabProps";
3
28
  import { trackEvent } from "../lib/trackEvent";
29
+ import {
30
+ type AddressParts,
31
+ type AddressProvider,
32
+ AddressSearch,
33
+ } from "../primitives/AddressSearch";
4
34
  import { Button } from "../primitives/Button";
35
+ import { EmailLink } from "../primitives/EmailLink";
36
+ import { ExpandableText } from "../primitives/ExpandableText";
37
+ import { GoogleMapsAttribution } from "../primitives/GoogleMapsAttribution";
38
+ import { PhoneLink } from "../primitives/PhoneLink";
5
39
  import { useWithBase } from "../routing/BasePathProvider";
6
40
 
41
+ /** Every word the form draws that is not a visitor's, each with a neutral default. */
42
+ export interface ContactFormLabels {
43
+ name: string;
44
+ firstName: string;
45
+ lastName: string;
46
+ email: string;
47
+ phone: string;
48
+ topic: string;
49
+ message: string;
50
+ /** The address search's label, when the form has a provider. */
51
+ addressSearch: string;
52
+ street: string;
53
+ city: string;
54
+ state: string;
55
+ zip: string;
56
+ services: string;
57
+ /** Beside the services label, such as "(check all that apply)". None by default. */
58
+ servicesHint?: string;
59
+ /** Beside the label of an optional phone and an optional address. */
60
+ optional: string;
61
+ /** The services button's words for more chosen than it lists. */
62
+ servicesCount: (count: number) => string;
63
+ /** The address suggestions' accessible name. */
64
+ suggestions: string;
65
+ showMore: string;
66
+ showLess: string;
67
+ submit: string;
68
+ sending: string;
69
+ }
70
+
71
+ /** A placeholder for each text field that takes one; none by default but the two pickers'. */
72
+ export type ContactFormPlaceholders = Partial<
73
+ Record<Exclude<ContactFormField, "state"> | "addressSearch" | "services", string>
74
+ >;
75
+
76
+ /** The property address block: an optional search over street, city, state, and ZIP. */
77
+ export interface ContactFormAddress {
78
+ /** Refuse a send without every part and a ZIP code. Optional by default. */
79
+ required?: boolean;
80
+ /** Looks addresses up as they are typed and fills the four fields; without it, the fields stand alone. */
81
+ provider?: AddressProvider;
82
+ /**
83
+ * A Maps JavaScript API key: the search then offers Google's addresses
84
+ * (`googlePlacesProvider`) under the "Google Maps" attribution Google's
85
+ * terms ask for. `provider` wins when both are given; with neither, the
86
+ * fields stand alone.
87
+ */
88
+ googlePlacesKey?: string;
89
+ /** Google's options beside the key: the countries, a point to prefer, the types, the language. */
90
+ googlePlacesOptions?: Omit<GooglePlacesOptions, "apiKey">;
91
+ /** Under the suggestions, for a provider whose terms ask for it; with `googlePlacesKey`, Google's by default. */
92
+ attribution?: ReactNode;
93
+ /** Draws the state as a select of these; a text field when left out. */
94
+ states?: string[];
95
+ /** The state chosen before anyone picks; the first of `states` when left out. */
96
+ defaultState?: string;
97
+ }
98
+
99
+ /** A consent checkbox under the message, its words cut short behind Show more. */
100
+ export interface ContactFormConsent {
101
+ /** The consent wording, verbatim, as prose: it is the checkbox's whole label. */
102
+ text: ReactNode;
103
+ /** Links shown once the wording is opened (terms, privacy policy). */
104
+ links?: { label: string; href: string; newTab?: boolean }[];
105
+ /** The lines shown while closed. Defaults to 2. */
106
+ lines?: number;
107
+ /** Show more at the end of the last line rather than under the wording (`ExpandableText`'s `inline`). */
108
+ inline?: boolean;
109
+ }
110
+
111
+ /** The thanks that replaces the form once a message is sent. */
112
+ export interface ContactFormThanks {
113
+ /** The heading; a function of what was sent, to greet by name. */
114
+ title: ReactNode | ((values: ContactFormValues) => ReactNode);
115
+ /**
116
+ * The line under it. Defaults to the form's `successMessage`; `null` or
117
+ * `false` draws none, no element at all.
118
+ */
119
+ lead?: ReactNode | ((values: ContactFormValues) => ReactNode);
120
+ /**
121
+ * What was sent, read back: the labels of its rows (services, topic,
122
+ * address, and how to reach the visitor), or false for none. Shown by
123
+ * default, each row only when the form drew its field and it was filled.
124
+ */
125
+ summary?: false | Partial<Record<"services" | "topic" | "address" | "contact", string>>;
126
+ /** The steps that follow, as a numbered list. */
127
+ steps?: string[];
128
+ /** The heading over the steps. */
129
+ stepsHeading?: string;
130
+ /** The words of the control that brings the form back. */
131
+ again?: string;
132
+ /** The level the heading is read at. Defaults to 3. */
133
+ headingLevel?: 2 | 3 | 4 | 5;
134
+ }
135
+
7
136
  export interface ContactFormProps {
8
137
  /**
9
138
  * POST target for a real form backend (e.g. "/api/contact"). The body is
10
139
  * JSON: { name, email, topic, message, company } where company is the
11
- * honeypot and must be relayed verbatim. When omitted, the form falls
12
- * back to a mailto handoff via toEmail.
140
+ * honeypot and must be relayed verbatim. Those five keys are always
141
+ * there, so a relay that reads only them keeps working whatever else the
142
+ * form draws: with `splitName`, `name` is the first and last joined, and
143
+ * with `services`, `topic` is the chosen services joined by commas. Each
144
+ * opt in field adds its own keys only when it is drawn: `firstName` and
145
+ * `lastName`; `phone`; `address`, { street, city, state, zip }; `services`,
146
+ * an array of the chosen values; `consent`, a boolean. When omitted, the
147
+ * form falls back to a mailto handoff via toEmail.
13
148
  */
14
149
  endpoint?: string;
15
150
  /** Destination inbox for the mailto fallback (required without endpoint). */
16
151
  toEmail?: string;
17
- /** Options for the topic select. */
18
- topics: string[];
152
+ /** Options for the topic select; no select when left out, or when `services` is set. */
153
+ topics?: string[];
19
154
  /** Message shown after a successful submit (or after the mail draft opens). */
20
155
  successMessage: string;
21
156
  /** Message shown when the endpoint submission fails. */
@@ -30,25 +165,93 @@ export interface ContactFormProps {
30
165
  * It is passed nothing, so no personal data can ride along.
31
166
  */
32
167
  onLead?: () => void;
168
+ /** First and last name as two fields, side by side, in place of the one name. */
169
+ splitName?: boolean;
170
+ /** A phone field beside the email, optional or required. None when left out. */
171
+ phone?: "optional" | "required";
172
+ /** The property address: street, city, state, and ZIP, under an address search when given a provider. */
173
+ address?: ContactFormAddress;
174
+ /** A multi select of these services in place of the topic select. */
175
+ services?: string[];
176
+ /** A consent checkbox under the message. */
177
+ consent?: ContactFormConsent;
178
+ /** The form's words, each replacing its neutral default. */
179
+ labels?: Partial<ContactFormLabels>;
180
+ placeholders?: ContactFormPlaceholders;
181
+ /** The message under each refused field, each replacing its neutral default. */
182
+ errorText?: Partial<Record<ContactFormField, string>>;
183
+ /**
184
+ * A count of the fields to fix, over the form, after a refused send: true
185
+ * for the default words, or a function of the count for the site's own.
186
+ */
187
+ errorSummary?: boolean | ((count: number) => string);
188
+ /** Replaces the form with a thanks once a message is sent; by default the thanks shows over the cleared form. */
189
+ thanks?: ContactFormThanks;
190
+ /**
191
+ * Whether a phone number is one to accept. Defaults to `isPhoneNumber`: a
192
+ * ten digit North American number typed any common way (a leading 1
193
+ * aside), or a full international one starting with + and its country code.
194
+ */
195
+ validatePhone?: (value: string) => boolean;
33
196
  }
34
197
 
35
198
  function sendLead() {
36
199
  trackEvent("generate_lead", { form_name: "contact" });
37
200
  }
38
201
 
39
- interface FieldErrors {
40
- name?: boolean;
41
- email?: boolean;
42
- message?: boolean;
43
- }
44
-
45
202
  type Status = "idle" | "sending" | "sent" | "failed";
46
203
 
47
- const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
204
+ const LABELS: ContactFormLabels = {
205
+ name: "Your name",
206
+ firstName: "First name",
207
+ lastName: "Last name",
208
+ email: "Email",
209
+ phone: "Phone",
210
+ topic: "What can we help with?",
211
+ message: "Message",
212
+ addressSearch: "Address",
213
+ street: "Street address",
214
+ city: "City",
215
+ state: "State",
216
+ zip: "ZIP",
217
+ services: "Services",
218
+ optional: "(optional)",
219
+ servicesCount: (count) => `${count} chosen`,
220
+ suggestions: "Address suggestions",
221
+ showMore: "Show more",
222
+ showLess: "Show less",
223
+ submit: "Send Message",
224
+ sending: "Sending…",
225
+ };
226
+
227
+ const ERRORS: Record<ContactFormField, string> = {
228
+ name: "Please enter your name.",
229
+ firstName: "Please enter your first name.",
230
+ lastName: "Please enter your last name.",
231
+ phone: "Please enter a phone number with its area code.",
232
+ email: "Please enter a valid email.",
233
+ street: "Please enter the street address.",
234
+ city: "Please enter the city.",
235
+ state: "Please enter the state.",
236
+ zip: "Please enter a 5 digit ZIP code.",
237
+ message: "Please add a short message.",
238
+ };
239
+
240
+ const countWords = (count: number) =>
241
+ count === 1
242
+ ? "One field needs fixing before this can be sent."
243
+ : `${count} fields need fixing before this can be sent.`;
48
244
 
49
245
  /**
50
246
  * Contact form with client validation and a honeypot. POSTs to `endpoint`
51
247
  * when one is configured; otherwise hands off to the visitor's mail app.
248
+ *
249
+ * With no opt in prop it is the form it always was: a name, an email, the
250
+ * topic select, and a message. The opt in props add a service business's
251
+ * fields: a split name, a phone, the property address (with an address
252
+ * search when the site gives it a provider), a multi select of services in
253
+ * place of the topic, a consent line cut short behind Show more, a count of
254
+ * the fields to fix, and a thanks that replaces the form once it is sent.
52
255
  */
53
256
  export function ContactForm({
54
257
  endpoint,
@@ -58,51 +261,146 @@ export function ContactForm({
58
261
  errorMessage = "Something went wrong sending your message. Please try again.",
59
262
  footnote,
60
263
  onLead = sendLead,
264
+ splitName = false,
265
+ phone,
266
+ address,
267
+ services,
268
+ consent,
269
+ labels: labelProps,
270
+ placeholders = {},
271
+ errorText,
272
+ errorSummary,
273
+ thanks,
274
+ validatePhone,
61
275
  }: ContactFormProps) {
62
276
  const withBase = useWithBase();
63
- const [errors, setErrors] = useState<FieldErrors>({});
277
+ const labels = { ...LABELS, ...labelProps };
278
+ const errorWords = { ...ERRORS, ...errorText };
279
+ const shape: ContactFormShape = {
280
+ splitName,
281
+ phone: phone ?? "off",
282
+ address: address ? (address.required ? "required" : "optional") : "off",
283
+ services: Boolean(services),
284
+ consent: Boolean(consent),
285
+ };
286
+ // An empty list of topics is no topic select, as no list is.
287
+ const hasTopic = Boolean(topics?.length) && !services;
288
+ const startAddress = (): AddressParts => ({
289
+ street: "",
290
+ city: "",
291
+ state: address?.defaultState ?? address?.states?.[0] ?? "",
292
+ zip: "",
293
+ });
294
+
295
+ // Google's provider, made once per key and options, so the search keeps
296
+ // one session across renders.
297
+ const googleKey = address?.provider ? undefined : address?.googlePlacesKey;
298
+ const googleOptions = JSON.stringify(address?.googlePlacesOptions ?? {});
299
+ const google = useMemo(
300
+ () =>
301
+ googleKey
302
+ ? googlePlacesProvider({ apiKey: googleKey, ...JSON.parse(googleOptions) })
303
+ : undefined,
304
+ [googleKey, googleOptions],
305
+ );
306
+ const addressProvider = address?.provider ?? google;
307
+ const addressAttribution =
308
+ address?.attribution ?? (google ? <GoogleMapsAttribution /> : undefined);
309
+ const [errors, setErrors] = useState<ContactFormRefusals>({});
64
310
  const [status, setStatus] = useState<Status>("idle");
311
+ const [place, setPlace] = useState<AddressParts>(startAddress);
312
+ // Whether a chosen suggestion's parts are still on their way.
313
+ const choosing = useRef(false);
314
+ const [sentValues, setSentValues] = useState<ContactFormValues | null>(null);
315
+ const formRef = useRef<HTMLFormElement>(null);
316
+ const thanksRef = useRef<HTMLDivElement>(null);
317
+ // Where focus goes once the form or the thanks is drawn: the thanks's
318
+ // heading when it replaces the form, the first field when the form comes back.
319
+ const [focusOn, setFocusOn] = useState<"thanks" | "form" | null>(null);
65
320
  // Ids from useId, so two forms on one page never share a label's target.
66
321
  const uid = useId();
67
- const ids = {
68
- name: `${uid}-name`,
69
- email: `${uid}-email`,
70
- topic: `${uid}-topic`,
71
- message: `${uid}-message`,
72
- company: `${uid}-company`,
73
- };
322
+ const idOf = (key: string) => `${uid}-${key}`;
323
+
324
+ useEffect(() => {
325
+ if (focusOn === "thanks") thanksRef.current?.focus();
326
+ if (focusOn === "form") {
327
+ const first = formRef.current?.elements.namedItem(splitName ? "firstName" : "name");
328
+ if (first instanceof HTMLElement) first.focus();
329
+ }
330
+ if (focusOn) setFocusOn(null);
331
+ }, [focusOn, splitName]);
332
+
74
333
  // A refused field says so and why: aria-invalid, and its message as its
75
334
  // description, only while it is refused.
76
- const refused = (field: keyof FieldErrors) =>
335
+ const refused = (field: ContactFormField) =>
77
336
  errors[field]
78
- ? { "aria-invalid": true as const, "aria-describedby": `${ids[field]}-error` }
337
+ ? { "aria-invalid": true as const, "aria-describedby": `${idOf(field)}-error` }
79
338
  : {};
339
+ const fieldClass = (field: ContactFormField) =>
340
+ ["field", errors[field] && "invalid"].filter(Boolean).join(" ");
341
+ const optionalHint = (on: boolean) =>
342
+ on && (
343
+ <>
344
+ {" "}
345
+ <small className="field-hint">{labels.optional}</small>
346
+ </>
347
+ );
348
+ const errorLine = (field: ContactFormField) => (
349
+ <span className="err" id={`${idOf(field)}-error`}>
350
+ {errorWords[field]}
351
+ </span>
352
+ );
353
+ const textField = (
354
+ field: ContactFormField,
355
+ input: {
356
+ type?: string;
357
+ autoComplete?: string;
358
+ inputMode?: "tel" | "numeric";
359
+ required?: boolean;
360
+ hint?: boolean;
361
+ value?: string;
362
+ onChange?: (value: string) => void;
363
+ },
364
+ ) => (
365
+ <div className={fieldClass(field)}>
366
+ <label htmlFor={idOf(field)}>
367
+ {labels[field]}
368
+ {optionalHint(Boolean(input.hint))}
369
+ </label>
370
+ <input
371
+ id={idOf(field)}
372
+ name={field}
373
+ type={input.type ?? "text"}
374
+ autoComplete={input.autoComplete}
375
+ inputMode={input.inputMode}
376
+ placeholder={placeholders[field as keyof ContactFormPlaceholders]}
377
+ required={input.required}
378
+ {...(input.onChange && {
379
+ value: input.value,
380
+ onChange: (event) => input.onChange?.(event.target.value),
381
+ })}
382
+ {...refused(field)}
383
+ />
384
+ {errorLine(field)}
385
+ </div>
386
+ );
80
387
 
81
388
  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
82
389
  event.preventDefault();
83
390
  if (status === "sending") return;
84
391
  const form = event.currentTarget;
85
- const data = new FormData(form);
86
- const name = String(data.get("name") ?? "").trim();
87
- const email = String(data.get("email") ?? "").trim();
88
- const topic = String(data.get("topic") ?? "");
89
- const message = String(data.get("message") ?? "").trim();
90
- const company = String(data.get("company") ?? "");
91
-
92
- const nextErrors: FieldErrors = {
93
- name: !name,
94
- email: !EMAIL_PATTERN.test(email),
95
- message: !message,
96
- };
392
+ const values = readContactForm(new FormData(form), shape);
393
+ const nextErrors = checkContactForm(values, shape, validatePhone);
97
394
  setErrors(nextErrors);
98
- const firstRefused = (["name", "email", "message"] as const).find((field) => nextErrors[field]);
99
- if (firstRefused) {
395
+ const first = firstRefused(nextErrors);
396
+ if (first) {
100
397
  setStatus("idle");
101
398
  // Focus goes to the first field to fix, where its message is read.
102
- const field = form.elements.namedItem(firstRefused);
399
+ const field = form.elements.namedItem(first);
103
400
  if (field instanceof HTMLElement) field.focus();
104
401
  return;
105
402
  }
403
+ const { name, email, topic, message, company } = values;
106
404
 
107
405
  if (!endpoint) {
108
406
  if (!toEmail) {
@@ -110,8 +408,16 @@ export function ContactForm({
110
408
  return;
111
409
  }
112
410
  const subject = encodeURIComponent(`Website inquiry: ${topic}`);
113
- const body = encodeURIComponent(`${name} (${email}) wrote:\n\n${message}`);
411
+ const extra = [
412
+ shape.phone !== "off" && values.phone && `Phone: ${values.phone}`,
413
+ shape.address !== "off" && addressLine(values.address),
414
+ ].filter(Boolean);
415
+ const body = encodeURIComponent(
416
+ `${name} (${email}) wrote:\n\n${message}${extra.length ? `\n\n${extra.join("\n")}` : ""}`,
417
+ );
418
+ setSentValues(values);
114
419
  setStatus("sent");
420
+ if (thanks) setFocusOn("thanks");
115
421
  window.location.href = `mailto:${toEmail}?subject=${subject}&body=${body}`;
116
422
  return;
117
423
  }
@@ -121,11 +427,14 @@ export function ContactForm({
121
427
  const response = await fetch(withBase(endpoint), {
122
428
  method: "POST",
123
429
  headers: { "Content-Type": "application/json" },
124
- body: JSON.stringify({ name, email, topic, message, company }),
430
+ body: JSON.stringify(contactFormBody(values, shape)),
125
431
  });
126
432
  if (!response.ok) throw new Error(`status ${response.status}`);
433
+ setSentValues(values);
127
434
  setStatus("sent");
128
435
  form.reset();
436
+ setPlace(startAddress());
437
+ if (thanks) setFocusOn("thanks");
129
438
  // The conversion: only a relay the endpoint accepted counts, never a
130
439
  // press of the button, a failed send, or a honeypot catch (which the
131
440
  // relay answers with the same success so the bot never learns). No
@@ -136,8 +445,45 @@ export function ContactForm({
136
445
  }
137
446
  }
138
447
 
448
+ if (thanks && status === "sent" && sentValues) {
449
+ return (
450
+ <ContactThanks
451
+ thanks={thanks}
452
+ values={sentValues}
453
+ successMessage={successMessage}
454
+ shape={shape}
455
+ hasTopic={hasTopic}
456
+ titleRef={thanksRef}
457
+ onAgain={() => {
458
+ // Back to a fresh form, whichever way it was sent: the address the
459
+ // form holds goes with the rest of the last visitor's words.
460
+ setStatus("idle");
461
+ setErrors({});
462
+ setSentValues(null);
463
+ setPlace(startAddress());
464
+ setFocusOn("form");
465
+ }}
466
+ />
467
+ );
468
+ }
469
+
470
+ const refusedCount = Object.values(errors).filter(Boolean).length;
471
+ const summaryWords = typeof errorSummary === "function" ? errorSummary : countWords;
472
+ const states = address?.states;
473
+ // A state a provider hands back that the list lacks is still offered, so a pick is never lost.
474
+ const stateOptions =
475
+ states && place.state && !states.includes(place.state) ? [...states, place.state] : states;
476
+ // A hand edit to an address field drops a pick still being read, so the
477
+ // late pick never writes over what the visitor typed.
478
+ const setPart = (part: keyof AddressParts) => (value: string) => {
479
+ choosing.current = false;
480
+ setPlace((was) => ({ ...was, [part]: value }));
481
+ };
482
+ const addressOptional = shape.address === "optional";
483
+ const searchShown = Boolean(addressProvider);
484
+
139
485
  return (
140
- <form onSubmit={handleSubmit} noValidate>
486
+ <form ref={formRef} onSubmit={handleSubmit} noValidate>
141
487
  {/* One shot status: the thanks or the failure is announced once when it
142
488
  appears (Component Rules 14). The region is always drawn, so a screen
143
489
  reader is already watching it when the words arrive. */}
@@ -145,63 +491,315 @@ export function ContactForm({
145
491
  {status === "sent" && <span className="form-success">{successMessage}</span>}
146
492
  {status === "failed" && <span className="form-error">{errorMessage}</span>}
147
493
  </output>
148
- <div className={["field", errors.name && "invalid"].filter(Boolean).join(" ")}>
149
- <label htmlFor={ids.name}>Your name</label>
150
- <input
151
- id={ids.name}
152
- name="name"
153
- type="text"
154
- autoComplete="name"
155
- required
156
- {...refused("name")}
494
+ {errorSummary && refusedCount > 0 && (
495
+ <div className="form-alert" role="alert">
496
+ {summaryWords(refusedCount)}
497
+ </div>
498
+ )}
499
+ {splitName ? (
500
+ <div className="field-row">
501
+ {textField("firstName", { autoComplete: "given-name", required: true })}
502
+ {textField("lastName", { autoComplete: "family-name", required: true })}
503
+ </div>
504
+ ) : (
505
+ textField("name", { autoComplete: "name", required: true })
506
+ )}
507
+ {(() => {
508
+ const emailField = textField("email", {
509
+ type: "email",
510
+ autoComplete: "email",
511
+ required: true,
512
+ });
513
+ if (shape.phone === "off") return emailField;
514
+ return (
515
+ <div className="field-row">
516
+ {textField("phone", {
517
+ type: "tel",
518
+ autoComplete: "tel",
519
+ inputMode: "tel",
520
+ required: shape.phone === "required",
521
+ hint: shape.phone === "optional",
522
+ })}
523
+ {emailField}
524
+ </div>
525
+ );
526
+ })()}
527
+ {address && (
528
+ <>
529
+ {searchShown && (
530
+ <AddressSearch
531
+ className="field"
532
+ provider={addressProvider}
533
+ label={labels.addressSearch}
534
+ hint={addressOptional ? labels.optional : undefined}
535
+ placeholder={placeholders.addressSearch ?? "Start typing an address"}
536
+ attribution={addressAttribution}
537
+ listLabel={labels.suggestions}
538
+ onChoose={() => {
539
+ choosing.current = true;
540
+ }}
541
+ onPick={(picked) => {
542
+ // A hand edit came first: the form keeps it, and the search
543
+ // goes back to what was typed (8.6.0).
544
+ if (!choosing.current) return false;
545
+ choosing.current = false;
546
+ // A pick with no state keeps the one the field shows, so a state
547
+ // select and what it submits never part ways.
548
+ setPlace((was) => ({ ...picked, state: picked.state || was.state }));
549
+ // Only a field the pick filled with a valid value stops being refused.
550
+ const filled: Record<keyof AddressParts, boolean> = {
551
+ street: Boolean(picked.street),
552
+ city: Boolean(picked.city),
553
+ state: Boolean(picked.state),
554
+ zip: isZIP(picked.zip),
555
+ };
556
+ setErrors((was) => ({
557
+ ...was,
558
+ ...Object.fromEntries(
559
+ (Object.keys(filled) as (keyof AddressParts)[])
560
+ .filter((part) => filled[part])
561
+ .map((part) => [part, undefined]),
562
+ ),
563
+ }));
564
+ }}
565
+ />
566
+ )}
567
+ {textField("street", {
568
+ autoComplete: "address-line1",
569
+ required: !addressOptional,
570
+ hint: addressOptional && !searchShown,
571
+ value: place.street,
572
+ onChange: setPart("street"),
573
+ })}
574
+ <div className="field-row field-row-3">
575
+ {textField("city", {
576
+ autoComplete: "address-level2",
577
+ required: !addressOptional,
578
+ value: place.city,
579
+ onChange: setPart("city"),
580
+ })}
581
+ {stateOptions ? (
582
+ <div className={fieldClass("state")}>
583
+ <label htmlFor={idOf("state")}>{labels.state}</label>
584
+ <select
585
+ id={idOf("state")}
586
+ name="state"
587
+ autoComplete="address-level1"
588
+ required={!addressOptional}
589
+ value={place.state}
590
+ onChange={(event) => setPart("state")(event.target.value)}
591
+ {...refused("state")}
592
+ >
593
+ {stateOptions.map((state) => (
594
+ <option key={state}>{state}</option>
595
+ ))}
596
+ </select>
597
+ {errorLine("state")}
598
+ </div>
599
+ ) : (
600
+ textField("state", {
601
+ autoComplete: "address-level1",
602
+ required: !addressOptional,
603
+ value: place.state,
604
+ onChange: setPart("state"),
605
+ })
606
+ )}
607
+ {textField("zip", {
608
+ autoComplete: "postal-code",
609
+ inputMode: "numeric",
610
+ required: !addressOptional,
611
+ value: place.zip,
612
+ onChange: setPart("zip"),
613
+ })}
614
+ </div>
615
+ </>
616
+ )}
617
+ {services ? (
618
+ <MultiSelect
619
+ className="field"
620
+ label={labels.services}
621
+ hint={labels.servicesHint}
622
+ name="services"
623
+ options={services}
624
+ placeholder={placeholders.services}
625
+ countLabel={labels.servicesCount}
157
626
  />
158
- <span className="err" id={`${ids.name}-error`}>
159
- Please enter your name.
160
- </span>
161
- </div>
162
- <div className={["field", errors.email && "invalid"].filter(Boolean).join(" ")}>
163
- <label htmlFor={ids.email}>Email</label>
164
- <input
165
- id={ids.email}
166
- name="email"
167
- type="email"
168
- autoComplete="email"
627
+ ) : (
628
+ hasTopic && (
629
+ <div className="field">
630
+ <label htmlFor={idOf("topic")}>{labels.topic}</label>
631
+ <select id={idOf("topic")} name="topic">
632
+ {topics?.map((topic) => (
633
+ <option key={topic}>{topic}</option>
634
+ ))}
635
+ </select>
636
+ </div>
637
+ )
638
+ )}
639
+ <div className={fieldClass("message")}>
640
+ <label htmlFor={idOf("message")}>{labels.message}</label>
641
+ <textarea
642
+ id={idOf("message")}
643
+ name="message"
644
+ placeholder={placeholders.message}
169
645
  required
170
- {...refused("email")}
646
+ {...refused("message")}
171
647
  />
172
- <span className="err" id={`${ids.email}-error`}>
173
- Please enter a valid email.
174
- </span>
175
- </div>
176
- <div className="field">
177
- <label htmlFor={ids.topic}>What can we help with?</label>
178
- <select id={ids.topic} name="topic">
179
- {topics.map((topic) => (
180
- <option key={topic}>{topic}</option>
181
- ))}
182
- </select>
183
- </div>
184
- <div className={["field", errors.message && "invalid"].filter(Boolean).join(" ")}>
185
- <label htmlFor={ids.message}>Message</label>
186
- <textarea id={ids.message} name="message" required {...refused("message")} />
187
- <span className="err" id={`${ids.message}-error`}>
188
- Please add a short message.
189
- </span>
648
+ {errorLine("message")}
190
649
  </div>
650
+ {consent && (
651
+ <div className="contact-consent">
652
+ <input
653
+ id={idOf("consent")}
654
+ className="contact-consent-box"
655
+ type="checkbox"
656
+ name="consent"
657
+ value="yes"
658
+ />
659
+ <ExpandableText
660
+ labelFor={idOf("consent")}
661
+ lines={consent.lines ?? 2}
662
+ inline={consent.inline}
663
+ moreLabel={labels.showMore}
664
+ lessLabel={labels.showLess}
665
+ more={
666
+ consent.links?.length ? (
667
+ <span className="contact-consent-links">
668
+ {consent.links.map((link) => (
669
+ <a
670
+ key={link.href + link.label}
671
+ href={withBase(link.href)}
672
+ {...newTabProps(link.href, link.newTab)}
673
+ >
674
+ {link.label}
675
+ </a>
676
+ ))}
677
+ </span>
678
+ ) : undefined
679
+ }
680
+ >
681
+ {consent.text}
682
+ </ExpandableText>
683
+ </div>
684
+ )}
191
685
  {/* Honeypot: visually hidden and skipped by keyboard/screen readers;
192
686
  bots that fill it are quietly dropped by the backend. */}
193
687
  <div className="hp-field" aria-hidden="true">
194
- <label htmlFor={ids.company}>Company</label>
195
- <input id={ids.company} name="company" type="text" tabIndex={-1} autoComplete="off" />
688
+ <label htmlFor={idOf("company")}>Company</label>
689
+ <input id={idOf("company")} name="company" type="text" tabIndex={-1} autoComplete="off" />
196
690
  </div>
197
691
  <Button type="submit" size="lg" arrow style={{ width: "100%" }}>
198
- {status === "sending" ? "Sending…" : "Send Message"}
692
+ {status === "sending" ? labels.sending : labels.submit}
199
693
  </Button>
200
- {footnote && (
201
- <p className="muted form-footnote" style={{ fontSize: "0.82rem", marginTop: 14 }}>
202
- {footnote}
203
- </p>
204
- )}
694
+ {footnote && <p className="muted form-footnote">{footnote}</p>}
205
695
  </form>
206
696
  );
207
697
  }
698
+
699
+ interface ContactThanksProps {
700
+ thanks: ContactFormThanks;
701
+ values: ContactFormValues;
702
+ successMessage: string;
703
+ shape: ContactFormShape;
704
+ hasTopic: boolean;
705
+ titleRef: RefObject<HTMLDivElement | null>;
706
+ onAgain: () => void;
707
+ }
708
+
709
+ /** The thanks that replaces the form: the heading, the lead, what was sent, and what comes next. */
710
+ function ContactThanks({
711
+ thanks,
712
+ values,
713
+ successMessage,
714
+ shape,
715
+ hasTopic,
716
+ titleRef,
717
+ onAgain,
718
+ }: ContactThanksProps) {
719
+ const level = thanks.headingLevel ?? 3;
720
+ const read = (words: ReactNode | ((values: ContactFormValues) => ReactNode)) =>
721
+ typeof words === "function" ? words(values) : words;
722
+ const labels =
723
+ thanks.summary === false
724
+ ? null
725
+ : {
726
+ services: "Services",
727
+ topic: "Topic",
728
+ address: "Address",
729
+ contact: "Contact",
730
+ ...thanks.summary,
731
+ };
732
+ const rows: { label: string; value: ReactNode }[] = [];
733
+ if (labels) {
734
+ const { address } = values;
735
+ if (shape.services && values.services.length > 0)
736
+ rows.push({ label: labels.services, value: values.services.join(", ") });
737
+ if (hasTopic && values.topic) rows.push({ label: labels.topic, value: values.topic });
738
+ // A state alone, left at its default, is not an address.
739
+ if (shape.address !== "off" && (address.street || address.city || address.zip))
740
+ rows.push({ label: labels.address, value: addressLine(address) });
741
+ // The visitor's own number and address, read back as links (Component Rules 17).
742
+ const reach = [
743
+ values.phone && <PhoneLink key="phone" phone={values.phone} />,
744
+ values.email && (
745
+ <EmailLink key="email" email={values.email}>
746
+ {values.email}
747
+ </EmailLink>
748
+ ),
749
+ ].filter(Boolean);
750
+ if (reach.length)
751
+ rows.push({
752
+ label: labels.contact,
753
+ value: reach.flatMap((link, at) => (at ? [", ", link] : [link])),
754
+ });
755
+ }
756
+
757
+ return (
758
+ <div className="contact-thanks">
759
+ <div className="contact-thanks-mark" aria-hidden="true">
760
+ <Check size={26} strokeWidth={2.5} />
761
+ </div>
762
+ {/* biome-ignore lint/a11y/useSemanticElements: a heading element would take a site's bare heading rules (Component Rules 21) */}
763
+ <div
764
+ ref={titleRef}
765
+ className="contact-thanks-title"
766
+ role="heading"
767
+ aria-level={level}
768
+ tabIndex={-1}
769
+ >
770
+ {read(thanks.title)}
771
+ </div>
772
+ {thanks.lead !== null && thanks.lead !== false && (
773
+ <p className="contact-thanks-lead">{read(thanks.lead ?? successMessage)}</p>
774
+ )}
775
+ {rows.length > 0 && (
776
+ <dl className="contact-thanks-summary">
777
+ {rows.map((row) => (
778
+ <div key={row.label}>
779
+ <dt>{row.label}</dt>
780
+ <dd>{row.value}</dd>
781
+ </div>
782
+ ))}
783
+ </dl>
784
+ )}
785
+ {thanks.steps && thanks.steps.length > 0 && (
786
+ <>
787
+ {thanks.stepsHeading && (
788
+ // biome-ignore lint/a11y/useSemanticElements: a heading element would take a site's bare heading rules (Component Rules 21)
789
+ <div className="contact-thanks-steps-head" role="heading" aria-level={level + 1}>
790
+ {thanks.stepsHeading}
791
+ </div>
792
+ )}
793
+ <ol className="contact-thanks-steps">
794
+ {thanks.steps.map((step) => (
795
+ <li key={step}>{step}</li>
796
+ ))}
797
+ </ol>
798
+ </>
799
+ )}
800
+ <button type="button" className="contact-thanks-again" onClick={onAgain}>
801
+ {thanks.again ?? "Send another message"}
802
+ </button>
803
+ </div>
804
+ );
805
+ }