@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atelic-action/ui",
3
- "version": "8.3.0",
3
+ "version": "8.5.0",
4
4
  "description": "Shared UI for the Atelic templates: site chrome, base styles, the component library, the access gate, and the app shell they install",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -58,6 +58,10 @@
58
58
  "types": "./dist/routing/basePath.d.ts",
59
59
  "default": "./dist/routing/basePath.js"
60
60
  },
61
+ "./scripts/contacts": {
62
+ "types": "./dist/scripts/check-contacts.d.ts",
63
+ "default": "./dist/scripts/check-contacts.js"
64
+ },
61
65
  "./sections": "./src/sections/index.ts",
62
66
  "./tokens": "./src/tokens/index.ts",
63
67
  "./styles/app.css": "./src/styles/app.css",
@@ -97,7 +101,7 @@
97
101
  },
98
102
  "scripts": {
99
103
  "build": "rm -rf dist && tsc -p tsconfig.server.json",
100
- "build:smoke": "node --input-type=module -e \"for (const entry of ['gate', 'gate/middleware', 'gate/request-link', 'gate/verify', 'vite', 'vite/private-chunks', 'artifact/readers', 'routing/base-path', 'monitoring/server']) await import('@atelic-action/ui/' + entry)\"",
104
+ "build:smoke": "node --input-type=module -e \"for (const entry of ['gate', 'gate/middleware', 'gate/request-link', 'gate/verify', 'vite', 'vite/private-chunks', 'artifact/readers', 'routing/base-path', 'monitoring/server', 'scripts/contacts']) await import('@atelic-action/ui/' + entry)\"",
101
105
  "prepack": "bun run build",
102
106
  "lint": "biome check .",
103
107
  "lint:fix": "biome check . --write",
@@ -108,20 +112,21 @@
108
112
  "storybook:build": "storybook build --output-dir storybook-static"
109
113
  },
110
114
  "dependencies": {
115
+ "@radix-ui/react-checkbox": "^1.1.2",
116
+ "@radix-ui/react-popover": "^1.1.15",
111
117
  "@radix-ui/react-tabs": "^1.2.1",
112
118
  "@sentry/browser": "^11.16.0",
113
119
  "@sentry/vite-plugin": "^11.16.0",
114
- "jose": "^6.2.12"
120
+ "jose": "^6.2.12",
121
+ "libphonenumber-js": "^1.13.17"
115
122
  },
116
123
  "peerDependencies": {
117
124
  "@radix-ui/react-accordion": "^1.2.12",
118
125
  "@radix-ui/react-alert-dialog": "^1.1.15",
119
126
  "@radix-ui/react-avatar": "^1.1.11",
120
- "@radix-ui/react-checkbox": "^1.1.2",
121
127
  "@radix-ui/react-dialog": "^1.1.15",
122
128
  "@radix-ui/react-dropdown-menu": "^2.1.16",
123
129
  "@radix-ui/react-label": "^2.1.8",
124
- "@radix-ui/react-popover": "^1.1.15",
125
130
  "@radix-ui/react-progress": "^1.1.8",
126
131
  "@radix-ui/react-select": "^2.2.6",
127
132
  "@radix-ui/react-separator": "^1.1.0",
@@ -158,9 +163,6 @@
158
163
  "@radix-ui/react-avatar": {
159
164
  "optional": true
160
165
  },
161
- "@radix-ui/react-checkbox": {
162
- "optional": true
163
- },
164
166
  "@radix-ui/react-dialog": {
165
167
  "optional": true
166
168
  },
@@ -170,9 +172,6 @@
170
172
  "@radix-ui/react-label": {
171
173
  "optional": true
172
174
  },
173
- "@radix-ui/react-popover": {
174
- "optional": true
175
- },
176
175
  "@radix-ui/react-progress": {
177
176
  "optional": true
178
177
  },
@@ -245,11 +244,9 @@
245
244
  "@radix-ui/react-accordion": "^1.2.12",
246
245
  "@radix-ui/react-alert-dialog": "^1.1.15",
247
246
  "@radix-ui/react-avatar": "^1.1.11",
248
- "@radix-ui/react-checkbox": "^1.1.2",
249
247
  "@radix-ui/react-dialog": "^1.1.15",
250
248
  "@radix-ui/react-dropdown-menu": "^2.1.16",
251
249
  "@radix-ui/react-label": "^2.1.8",
252
- "@radix-ui/react-popover": "^1.1.15",
253
250
  "@radix-ui/react-progress": "^1.1.8",
254
251
  "@radix-ui/react-select": "^2.2.6",
255
252
  "@radix-ui/react-separator": "^1.1.0",
@@ -1,7 +1,8 @@
1
1
  import { Mail, Star, UserRound } from "lucide-react";
2
- import type { ComponentProps, CSSProperties, Ref } from "react";
3
- import { breakableEmail } from "../lib/emailText";
2
+ import type { ComponentProps, CSSProperties, ReactNode, Ref } from "react";
4
3
  import { newTabProps } from "../lib/newTabProps";
4
+ import { EmailLink } from "../primitives/EmailLink";
5
+ import { PhoneLink } from "../primitives/PhoneLink";
5
6
  import type {
6
7
  Brand,
7
8
  FooterColumn,
@@ -257,6 +258,13 @@ export function Footer({
257
258
  ))}
258
259
  </dl>
259
260
  );
261
+ // With the hours in the brand column the link columns share one box, so
262
+ // the row is the brand column and that box: the two sit side by side or
263
+ // each takes a row, and the box alone decides four across or two by two
264
+ // (chrome.css). Anywhere else, and on a phone, the columns stand in the
265
+ // grid as they always have.
266
+ const wrapLinks = (links: ReactNode) =>
267
+ hoursInBrand ? <div className="footer-links">{links}</div> : links;
260
268
  const stars = (
261
269
  <span className="footer-stars" aria-hidden="true">
262
270
  {STARS.map((star) => (
@@ -346,8 +354,8 @@ export function Footer({
346
354
  ) : (
347
355
  <span className="nap-address">{addressLines}</span>
348
356
  ))}
349
- {phone && <a href={`tel:${phone.e164}`}>{phone.display}</a>}
350
- {email && <a href={`mailto:${email}`}>{breakableEmail(email)}</a>}
357
+ {phone && <PhoneLink phone={phone} />}
358
+ {email && <EmailLink email={email} />}
351
359
  </address>
352
360
  )}
353
361
  {hoursInBrand && (
@@ -369,23 +377,25 @@ export function Footer({
369
377
  {hoursList(hoursShown)}
370
378
  </div>
371
379
  )}
372
- {shown.map((column) => (
373
- <nav key={column.heading} className="footer-column" aria-label={column.heading}>
374
- {/* A heading by role rather than by element: a site's own bare
380
+ {wrapLinks(
381
+ shown.map((column) => (
382
+ <nav key={column.heading} className="footer-column" aria-label={column.heading}>
383
+ {/* A heading by role rather than by element: a site's own bare
375
384
  h2 rule (unlayered, so it beats any rule in the package's
376
385
  layer whatever its weight) is written for a page's section
377
386
  titles and would restyle these small labels. A div that says
378
387
  it is a heading keeps the outline and matches no such rule. */}
379
- {/* biome-ignore lint/a11y/useSemanticElements: an h2 element would take a site's bare h2 rules, see above */}
380
- <div className="footer-heading" role="heading" aria-level={headingLevel}>
381
- {column.heading}
382
- </div>
383
- {column.links.map((link, at) => (
384
- // biome-ignore lint/suspicious/noArrayIndexKey: two links may share a label and a page, so the place keeps the key unique; links never reorder
385
- <ColumnLink key={at} link={link} />
386
- ))}
387
- </nav>
388
- ))}
388
+ {/* biome-ignore lint/a11y/useSemanticElements: an h2 element would take a site's bare h2 rules, see above */}
389
+ <div className="footer-heading" role="heading" aria-level={headingLevel}>
390
+ {column.heading}
391
+ </div>
392
+ {column.links.map((link, at) => (
393
+ // biome-ignore lint/suspicious/noArrayIndexKey: two links may share a label and a page, so the place keeps the key unique; links never reorder
394
+ <ColumnLink key={at} link={link} />
395
+ ))}
396
+ </nav>
397
+ )),
398
+ )}
389
399
  </div>
390
400
  </div>
391
401
  </footer>
@@ -11,6 +11,7 @@ import {
11
11
  import { useDismiss } from "../hooks/useDismiss";
12
12
  import { type PageStop, useScrollSpy } from "../hooks/useScrollSpy";
13
13
  import { Button } from "../primitives/Button";
14
+ import { PhoneLink } from "../primitives/PhoneLink";
14
15
  import type {
15
16
  Brand,
16
17
  CallToAction,
@@ -325,10 +326,10 @@ export function SiteHeader({
325
326
  {barPhones.length > 0 && (
326
327
  <div className="nav-phones">
327
328
  {barPhones.map((phone) => (
328
- <a
329
+ <PhoneLink
329
330
  key={phone.e164}
330
331
  className="nav-phone"
331
- href={`tel:${phone.e164}`}
332
+ phone={phone}
332
333
  aria-label={phoneName(phone)}
333
334
  >
334
335
  <PhoneIcon size={17} aria-hidden="true" />
@@ -336,7 +337,7 @@ export function SiteHeader({
336
337
  {phone.label && <span className="nav-phone-label">{phone.label}</span>}
337
338
  <span className="nav-phone-number tel-number">{phone.display}</span>
338
339
  </span>
339
- </a>
340
+ </PhoneLink>
340
341
  ))}
341
342
  </div>
342
343
  )}
@@ -351,16 +352,16 @@ export function SiteHeader({
351
352
  </span>
352
353
  )}
353
354
  {barPhones[0] && (
354
- <a
355
+ <PhoneLink
355
356
  className="nav-call"
356
- href={`tel:${barPhones[0].e164}`}
357
+ phone={barPhones[0]}
357
358
  // An icon alone: a number with no label is named "Call" and the number.
358
359
  aria-label={
359
360
  barPhones[0].label ? phoneName(barPhones[0]) : `Call ${barPhones[0].display}`
360
361
  }
361
362
  >
362
363
  <PhoneIcon size={19} aria-hidden="true" />
363
- </a>
364
+ </PhoneLink>
364
365
  )}
365
366
  {hasMenu && (
366
367
  <button
@@ -3,6 +3,8 @@ import { useEffect, useId, useRef, useState } from "react";
3
3
  import { newTabProps } from "../lib/newTabProps";
4
4
  import { telText } from "../lib/phoneText";
5
5
  import { Button } from "../primitives/Button";
6
+ import { EmailLink } from "../primitives/EmailLink";
7
+ import { PhoneLink } from "../primitives/PhoneLink";
6
8
  import type {
7
9
  Brand,
8
10
  CallToAction,
@@ -51,7 +53,8 @@ export interface SiteMenuProps {
51
53
  /**
52
54
  * The phone, email, and address block at the foot of the dark sheet. The
53
55
  * light sheet draws its one phone as a card when `phones` is empty, and
54
- * leaves the email and the address out, as its design does.
56
+ * leaves the email and the address out, as its design does. Either sheet
57
+ * sets the phone with its `menuLabel`, else "Call".
55
58
  */
56
59
  contact?: MenuContact;
57
60
  /**
@@ -273,15 +276,15 @@ export function SiteMenu({
273
276
  const words = menuPhoneLabel(line);
274
277
  return (
275
278
  // The words and the number are one name, spaced as they read.
276
- <a
279
+ <PhoneLink
277
280
  key={line.e164}
278
281
  className="mm-phone-card"
279
- href={`tel:${line.e164}`}
282
+ phone={line}
280
283
  aria-label={`${words} ${line.display}`}
281
284
  >
282
285
  <span className="mm-phone-label">{words}</span>
283
286
  <span className="mm-phone-number tel-number">{line.display}</span>
284
- </a>
287
+ </PhoneLink>
285
288
  );
286
289
  })}
287
290
  </div>
@@ -417,25 +420,25 @@ function ContactBlock({
417
420
  {phones
418
421
  ? phones.map((line) => (
419
422
  <span key={line.e164}>
420
- <a className="mm-contact-link" href={`tel:${line.e164}`}>
423
+ <PhoneLink className="mm-contact-link" phone={line}>
421
424
  {menuPhoneLabel(line).toUpperCase()}&nbsp;&nbsp;{line.display}
422
- </a>
425
+ </PhoneLink>
423
426
  <br />
424
427
  </span>
425
428
  ))
426
429
  : phone && (
427
430
  <>
428
- <a className="mm-contact-link" href={`tel:${phone.e164}`}>
431
+ <PhoneLink className="mm-contact-link" phone={phone}>
429
432
  {menuPhoneLabel(phone).toUpperCase()}&nbsp;&nbsp;{phone.display}
430
- </a>
433
+ </PhoneLink>
431
434
  <br />
432
435
  </>
433
436
  )}
434
437
  {email && (
435
438
  <>
436
- <a className="mm-contact-link" href={`mailto:${email}`}>
439
+ <EmailLink className="mm-contact-link" email={email}>
437
440
  {email}
438
- </a>
441
+ </EmailLink>
439
442
  <br />
440
443
  </>
441
444
  )}
@@ -1,6 +1,7 @@
1
1
  import { Phone as PhoneIcon } from "lucide-react";
2
2
  import { useEffect, useRef, useState } from "react";
3
3
  import { newTabProps } from "../lib/newTabProps";
4
+ import { PhoneLink } from "../primitives/PhoneLink";
4
5
  import type { CallToAction, Phone } from "../types";
5
6
 
6
7
  export interface StickyCTABarProps {
@@ -21,15 +22,21 @@ export interface StickyCTABarProps {
21
22
  /** The call shortcut's accessible name. Defaults to "Call us". */
22
23
  callLabel?: string;
23
24
  /**
24
- * Hears the room the bar takes at the foot of the screen, in pixels: its
25
- * measured height while it shows, and 0 while it is hidden (scrolled
26
- * above its threshold, or on a desktop, where the stylesheet hides it).
27
- * `SiteShell` pads the page's closing bar by it, so the copyright and the
28
- * credit are never under the bar. A listener swapped in is told the
25
+ * Hears the room the bar reserves at the foot of the page, in pixels: its
26
+ * measured height wherever it can show, from the first measure, whether
27
+ * or not it has slid in yet, and 0 on a desktop, where the stylesheet
28
+ * hides it. `SiteShell` pads the page's closing bar by it, so the
29
+ * copyright and the credit are never under the bar, even on a page whose
30
+ * bar slides in only once scrolled and a jump straight to its end: the
31
+ * page is already as long as it will be when the bar shows, so its
32
+ * arrival moves nothing under the reader. A listener swapped in is told the
29
33
  * current height at once and the one it replaced gets 0; no listener
30
34
  * hears one value twice. A listener made anew each render that sets state
31
35
  * should store a plain number (or be memoized): each new function hears
32
- * the height once, and a state equal to it stops the renders.
36
+ * the height once, and a state equal to it stops the renders. One that
37
+ * stores an object is cut off after three arrivals with nothing measured
38
+ * between: the listener leaving still hears 0, and the one arriving
39
+ * waits for the next measure.
33
40
  */
34
41
  onSpaceChange?: (pixels: number) => void;
35
42
  }
@@ -72,15 +79,19 @@ export function StickyCTABar({
72
79
  return () => window.removeEventListener("scroll", onScroll);
73
80
  }, [threshold, fromTop]);
74
81
 
75
- // The bar's real height while it shows, measured again whenever it changes
76
- // size (a phone turned, a font loading, a label wrapping), never assumed.
77
- // Hidden by the stylesheet its height reads 0, so a desktop reserves nothing.
82
+ // The bar's real height, measured again whenever it changes size (a phone
83
+ // turned, a font loading, a label wrapping), never assumed. It is reported
84
+ // while the bar waits below the screen too (its slide is a transform, which
85
+ // leaves its height as it is), so the space at the page's end is reserved
86
+ // from the start and never grows as the bar slides in, where a jump to the
87
+ // end would stop short of it. Hidden by the stylesheet its height reads 0,
88
+ // so a desktop reserves nothing.
78
89
  // biome-ignore lint/correctness/useExhaustiveDependencies: tell reads only refs
79
90
  useEffect(() => {
80
91
  const bar = barRef.current;
81
92
  if (!bar || !listening) return;
82
93
  const report = () => {
83
- heightRef.current = show ? bar.offsetHeight : 0;
94
+ heightRef.current = bar.offsetHeight;
84
95
  arrivalsRef.current = 0;
85
96
  tell(spaceRef.current, heightRef.current);
86
97
  };
@@ -91,12 +102,12 @@ export function StickyCTABar({
91
102
  return () => {
92
103
  sizes?.disconnect();
93
104
  window.removeEventListener("resize", report);
94
- // A final 0 on unmount, on hiding, and when the listener goes, so no
95
- // foot padding outlives the bar.
105
+ // A final 0 on unmount and when the listener goes, so no foot padding
106
+ // outlives the bar.
96
107
  heightRef.current = -1;
97
108
  tell(spaceRef.current, 0);
98
109
  };
99
- }, [show, listening]);
110
+ }, [listening]);
100
111
 
101
112
  // A listener swapped in is told the current height, and the one it
102
113
  // replaced gets 0, unless either already heard that value. A function made
@@ -114,7 +125,14 @@ export function StickyCTABar({
114
125
  const previous = previousRef.current;
115
126
  previousRef.current = onSpaceChange;
116
127
  if (previous === onSpaceChange) return;
117
- if (onSpaceChange && arrivalsRef.current >= 3) return;
128
+ if (onSpaceChange && arrivalsRef.current >= 3) {
129
+ // Past the cap the outgoing one still gives back any space it holds;
130
+ // only the arrival waits. Only a listener told a height is told 0, so
131
+ // a looping listener hears it once: the function its 0 makes was
132
+ // never told anything, and the next swap tells no one.
133
+ if (previous && (toldRef.current.get(previous) ?? 0) > 0) tell(previous, 0);
134
+ return;
135
+ }
118
136
  arrivalsRef.current += 1;
119
137
  // The outgoing one gives its space back, the bar measured or not (a
120
138
  // listener taken away leaves the measuring off by now).
@@ -140,9 +158,9 @@ export function StickyCTABar({
140
158
  {primaryCTA.label}
141
159
  </a>
142
160
  {phone && (
143
- <a className="btn btn-ghost btn-call" href={`tel:${phone.e164}`} aria-label={callLabel}>
161
+ <PhoneLink className="btn btn-ghost btn-call" phone={phone} aria-label={callLabel}>
144
162
  <PhoneIcon size={18} aria-hidden="true" />
145
- </a>
163
+ </PhoneLink>
146
164
  )}
147
165
  </div>
148
166
  );
@@ -1,4 +1,5 @@
1
1
  import { type FormEvent, useEffect, useId, useRef, useState } from "react";
2
+ import { EmailLink } from "../primitives/EmailLink";
2
3
 
3
4
  type Status = "idle" | "sending" | "sent" | "failed";
4
5
 
@@ -179,7 +180,7 @@ export function GateLogin({
179
180
  <p className="gate-fine">
180
181
  {builtBy && `Built by ${builtBy}`}
181
182
  {builtBy && contactEmail && " · "}
182
- {contactEmail && <a href={`mailto:${contactEmail}`}>{contactEmail}</a>}
183
+ {contactEmail && <EmailLink email={contactEmail}>{contactEmail}</EmailLink>}
183
184
  </p>
184
185
  )}
185
186
  </>
@@ -0,0 +1,225 @@
1
+ import * as Checkbox from "@radix-ui/react-checkbox";
2
+ import * as Popover from "@radix-ui/react-popover";
3
+ import { Check, ChevronDown } from "lucide-react";
4
+ import { type KeyboardEvent, type ReactNode, useEffect, useId, useRef, useState } from "react";
5
+
6
+ /** One choice: its submitted value, and the words shown when they differ. */
7
+ export interface MultiSelectOption {
8
+ value: string;
9
+ label?: string;
10
+ }
11
+
12
+ export interface MultiSelectProps {
13
+ /** The field's label, and the first half of the button's accessible name. */
14
+ label: ReactNode;
15
+ /** A quiet note beside the label, such as "(check all that apply)". */
16
+ hint?: ReactNode;
17
+ /** The choices, as plain strings or as values with their own words. */
18
+ options: (string | MultiSelectOption)[];
19
+ /**
20
+ * The name each chosen value is submitted under in a form, once per value,
21
+ * as checkboxes are, so `FormData.getAll(name)` reads them in the options'
22
+ * order. Nothing is submitted without it.
23
+ */
24
+ name?: string;
25
+ /** Chosen on first render, and again when the form resets. */
26
+ defaultValue?: string[];
27
+ /** The button's words while nothing is chosen. */
28
+ placeholder?: string;
29
+ /** How many chosen labels the button lists before it counts them instead. Defaults to 2. */
30
+ listed?: number;
31
+ /** The button's words for more chosen than `listed`. */
32
+ countLabel?: (count: number) => string;
33
+ /** Called with the chosen values, in the options' order, on every change. */
34
+ onChange?: (values: string[]) => void;
35
+ /** The button's id; minted when left out. */
36
+ id?: string;
37
+ className?: string;
38
+ }
39
+
40
+ const optionOf = (option: string | MultiSelectOption) =>
41
+ typeof option === "string"
42
+ ? { value: option, label: option }
43
+ : { value: option.value, label: option.label ?? option.value };
44
+
45
+ const defaultCount = (count: number) => `${count} chosen`;
46
+
47
+ /**
48
+ * A closed control that names what is chosen and opens to a list of
49
+ * checkboxes, any number of which may be ticked: a form question with more
50
+ * than one answer ("Which services?").
51
+ *
52
+ * Built on Radix: the button is a Popover trigger (`aria-expanded`, and a
53
+ * popup it controls), and each choice is a Radix Checkbox (`role="checkbox"`
54
+ * with `aria-checked`). Checkboxes and not a multi select listbox, because a
55
+ * screen reader announces a checkbox's state the same way everywhere, where
56
+ * a listbox's `aria-multiselectable` selected state is read unevenly; and
57
+ * not cmdk's list, whose options mark the highlighted one `aria-selected`,
58
+ * which in a multi select says a choice is chosen when it is only under the
59
+ * cursor. Radix closes the list on a click outside (leaving focus where the
60
+ * press put it) and on Escape (focus back on the button); Enter in the list
61
+ * closes it too, back on the button, and never sends the form. There is no
62
+ * Done button. Opening lands on the first choice, Space ticks one, the
63
+ * arrows, Home, and End move between them, and Tab keeps to the open list,
64
+ * the last choice wrapping to the first, as the popover's focus scope does.
65
+ *
66
+ * The list renders in place, not in a portal, so it stays under the page's
67
+ * `.atelic-ui` root and its rules reach it. The chosen values are submitted
68
+ * as hidden inputs beside the button, which stay in the form while the list
69
+ * is closed, and a form's reset puts back `defaultValue`. The button lists
70
+ * the chosen labels, up to `listed`, then counts them.
71
+ */
72
+ export function MultiSelect({
73
+ label,
74
+ hint,
75
+ options,
76
+ name,
77
+ defaultValue = [],
78
+ placeholder = "Choose one or more",
79
+ listed = 2,
80
+ countLabel = defaultCount,
81
+ onChange,
82
+ id,
83
+ className,
84
+ }: MultiSelectProps) {
85
+ const minted = useId();
86
+ const buttonId = id ?? `${minted}-button`;
87
+ const labelTextId = `${minted}-label`;
88
+ const hintId = `${minted}-hint`;
89
+ // The label's words and its hint are named apart, so the name joins them
90
+ // with a space even where a page's HTML has dropped the one between them.
91
+ const labelledBy = hint ? `${labelTextId} ${hintId}` : labelTextId;
92
+ const valueId = `${minted}-value`;
93
+ const buttonRef = useRef<HTMLButtonElement>(null);
94
+ const listRef = useRef<HTMLDivElement>(null);
95
+ const [open, setOpen] = useState(false);
96
+ const choices = options.map(optionOf);
97
+ // Chosen values are always held in the options' order, whatever order they came in.
98
+ const inOrder = (values: string[]) =>
99
+ choices.flatMap((choice) => (values.includes(choice.value) ? [choice.value] : []));
100
+ const [chosen, setChosen] = useState<string[]>(() => inOrder(defaultValue));
101
+ // Read by the handlers, so a reset and a tick in one turn never see a stale list.
102
+ const chosenNow = useRef(chosen);
103
+ chosenNow.current = chosen;
104
+ // The values the form resets to, as first rendered.
105
+ const resetTo = useRef(chosen);
106
+
107
+ useEffect(() => {
108
+ const form = buttonRef.current?.form;
109
+ if (!form) return;
110
+ const onReset = () => {
111
+ setOpen(false);
112
+ chosenNow.current = resetTo.current;
113
+ setChosen(resetTo.current);
114
+ };
115
+ form.addEventListener("reset", onReset);
116
+ return () => form.removeEventListener("reset", onReset);
117
+ }, []);
118
+
119
+ const toggle = (value: string, on: boolean) => {
120
+ const set = new Set(chosenNow.current);
121
+ if (set.has(value) === on) return;
122
+ if (on) set.add(value);
123
+ else set.delete(value);
124
+ const values = inOrder([...set]);
125
+ chosenNow.current = values;
126
+ setChosen(values);
127
+ onChange?.(values);
128
+ };
129
+
130
+ const onListKey = (event: KeyboardEvent<HTMLDivElement>) => {
131
+ const all = Array.from(
132
+ listRef.current?.querySelectorAll<HTMLButtonElement>('[role="checkbox"]') ?? [],
133
+ );
134
+ const at = all.indexOf(event.target as HTMLButtonElement);
135
+ if (at < 0) return;
136
+ const moveTo = (index: number) => {
137
+ event.preventDefault();
138
+ all[(index + all.length) % all.length]?.focus();
139
+ };
140
+ if (event.key === "ArrowDown") moveTo(at + 1);
141
+ else if (event.key === "ArrowUp") moveTo(at - 1);
142
+ else if (event.key === "Home") moveTo(0);
143
+ else if (event.key === "End") moveTo(all.length - 1);
144
+ else if (event.key === "Enter") {
145
+ // A checkbox never takes Enter; here it means done, and never sends the form.
146
+ event.preventDefault();
147
+ setOpen(false);
148
+ }
149
+ };
150
+
151
+ const chosenLabels = choices.filter((c) => chosen.includes(c.value)).map((c) => c.label);
152
+ const summary =
153
+ chosenLabels.length === 0
154
+ ? placeholder
155
+ : chosenLabels.length <= listed
156
+ ? chosenLabels.join(", ")
157
+ : countLabel(chosenLabels.length);
158
+
159
+ return (
160
+ <div className={["multi-select", className].filter(Boolean).join(" ")}>
161
+ <label htmlFor={buttonId} className="multi-select-label">
162
+ <span id={labelTextId}>{label}</span>
163
+ {hint && (
164
+ <>
165
+ {" "}
166
+ <small id={hintId}>{hint}</small>
167
+ </>
168
+ )}
169
+ </label>
170
+ <Popover.Root open={open} onOpenChange={setOpen}>
171
+ <Popover.Trigger asChild>
172
+ <button
173
+ ref={buttonRef}
174
+ id={buttonId}
175
+ type="button"
176
+ className="multi-select-button"
177
+ data-empty={chosenLabels.length === 0 || undefined}
178
+ aria-labelledby={`${labelledBy} ${valueId}`}
179
+ onKeyDown={(event) => {
180
+ if (event.key === "ArrowDown" && !open) {
181
+ event.preventDefault();
182
+ setOpen(true);
183
+ }
184
+ }}
185
+ >
186
+ <span id={valueId} className="multi-select-value">
187
+ {summary}
188
+ </span>
189
+ <ChevronDown className="multi-select-chevron" size={18} aria-hidden="true" />
190
+ </button>
191
+ </Popover.Trigger>
192
+ <Popover.Content
193
+ ref={listRef}
194
+ className="multi-select-list"
195
+ side="bottom"
196
+ align="start"
197
+ sideOffset={4}
198
+ aria-labelledby={labelledBy}
199
+ onKeyDown={onListKey}
200
+ >
201
+ {choices.map((choice, index) => {
202
+ // By position, not value: a value may hold a space or repeat.
203
+ const boxId = `${minted}-choice-${index}`;
204
+ return (
205
+ <div key={boxId} className="multi-select-option">
206
+ <Checkbox.Root
207
+ id={boxId}
208
+ className="multi-select-box"
209
+ checked={chosen.includes(choice.value)}
210
+ onCheckedChange={(state) => toggle(choice.value, state === true)}
211
+ >
212
+ <Checkbox.Indicator className="multi-select-tick">
213
+ <Check size={14} strokeWidth={3} aria-hidden="true" />
214
+ </Checkbox.Indicator>
215
+ </Checkbox.Root>
216
+ <label htmlFor={boxId}>{choice.label}</label>
217
+ </div>
218
+ );
219
+ })}
220
+ </Popover.Content>
221
+ </Popover.Root>
222
+ {name && chosen.map((value) => <input key={value} type="hidden" name={name} value={value} />)}
223
+ </div>
224
+ );
225
+ }
@@ -25,6 +25,7 @@ export {
25
25
  export { GateLogin, type GateLoginProps } from "./GateLogin";
26
26
  export { Hint, type HintProps } from "./Hint";
27
27
  export { IconList, type IconListItem, type IconListProps } from "./IconList";
28
+ export { MultiSelect, type MultiSelectOption, type MultiSelectProps } from "./MultiSelect";
28
29
  export { NotFound, type NotFoundProps } from "./NotFound";
29
30
  export { Rank, type RankProps } from "./Rank";
30
31
  export {