@rapidmx/web-client 0.22.0 → 0.24.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 (79) hide show
  1. package/apps/admin/mailboxes/[uid].tsx +2 -1
  2. package/apps/shared/components/admin/settings/MailboxCreateForm.tsx +2 -1
  3. package/apps/shared/components/admin/setup/SetupWizard.tsx +1 -1
  4. package/apps/shared/components/calendar/AppointmentQuickForm.tsx +2 -1
  5. package/apps/shared/components/calendar/EventDescriptionView.tsx +37 -5
  6. package/apps/shared/components/calendar/EventDetails.tsx +15 -6
  7. package/apps/shared/components/calendar/EventEditor.tsx +5 -2
  8. package/apps/shared/components/calendar/EventFormParts.tsx +45 -39
  9. package/apps/shared/components/calendar/EventQuickForm.tsx +3 -2
  10. package/apps/shared/components/calendar/FindATime.tsx +3 -2
  11. package/apps/shared/components/calendar/TimeComboBox.tsx +143 -0
  12. package/apps/shared/components/calendar/TimeGridView.tsx +3 -1
  13. package/apps/shared/components/calendar/eventFormat.ts +15 -0
  14. package/apps/shared/components/calendar/timePicker.ts +106 -0
  15. package/apps/shared/components/mail/ConversationList.tsx +18 -5
  16. package/apps/shared/components/mail/ConversationThreadPane.tsx +7 -2
  17. package/apps/shared/components/mail/MessageDetailPane.tsx +37 -18
  18. package/apps/shared/components/mail/invite/InviteRowChip.tsx +8 -12
  19. package/apps/shared/components/mail/invite/InviteRsvpPopover.tsx +2 -2
  20. package/apps/shared/components/mail/invite/inviteFormat.ts +6 -5
  21. package/apps/shared/components/mail/reading/conversationPrint.ts +76 -0
  22. package/apps/shared/components/mail/reading/printMessage.ts +44 -7
  23. package/apps/shared/keyboard/keymap.ts +1 -0
  24. package/apps/shared/mail/decryptedMessages.ts +116 -0
  25. package/apps/www/calendar/index.tsx +5 -2
  26. package/apps/www/index.tsx +11 -0
  27. package/apps/www/settings/profile/index.tsx +8 -12
  28. package/dist/apps/admin/mailboxes/[uid].js +2 -1
  29. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.js +2 -2
  30. package/dist/apps/shared/components/admin/setup/SetupWizard.d.ts +4 -4
  31. package/dist/apps/shared/components/admin/setup/SetupWizard.js +1 -1
  32. package/dist/apps/shared/components/calendar/AppointmentQuickForm.js +2 -1
  33. package/dist/apps/shared/components/calendar/EventDescriptionView.d.ts +6 -1
  34. package/dist/apps/shared/components/calendar/EventDescriptionView.js +34 -4
  35. package/dist/apps/shared/components/calendar/EventDetails.js +4 -4
  36. package/dist/apps/shared/components/calendar/EventEditor.js +5 -2
  37. package/dist/apps/shared/components/calendar/EventFormParts.d.ts +1 -1
  38. package/dist/apps/shared/components/calendar/EventFormParts.js +9 -3
  39. package/dist/apps/shared/components/calendar/EventQuickForm.js +3 -2
  40. package/dist/apps/shared/components/calendar/FindATime.js +3 -2
  41. package/dist/apps/shared/components/calendar/TimeComboBox.d.ts +25 -0
  42. package/dist/apps/shared/components/calendar/TimeComboBox.js +77 -0
  43. package/dist/apps/shared/components/calendar/TimeGridView.js +1 -1
  44. package/dist/apps/shared/components/calendar/eventFormat.d.ts +4 -0
  45. package/dist/apps/shared/components/calendar/eventFormat.js +13 -0
  46. package/dist/apps/shared/components/calendar/timePicker.d.ts +31 -0
  47. package/dist/apps/shared/components/calendar/timePicker.js +89 -0
  48. package/dist/apps/shared/components/mail/ConversationList.js +17 -4
  49. package/dist/apps/shared/components/mail/ConversationThreadPane.js +6 -2
  50. package/dist/apps/shared/components/mail/MessageDetailPane.js +31 -18
  51. package/dist/apps/shared/components/mail/invite/InviteRowChip.d.ts +2 -2
  52. package/dist/apps/shared/components/mail/invite/InviteRowChip.js +7 -9
  53. package/dist/apps/shared/components/mail/invite/InviteRsvpPopover.d.ts +1 -1
  54. package/dist/apps/shared/components/mail/invite/InviteRsvpPopover.js +2 -2
  55. package/dist/apps/shared/components/mail/invite/inviteFormat.js +6 -5
  56. package/dist/apps/shared/components/mail/reading/conversationPrint.d.ts +15 -0
  57. package/dist/apps/shared/components/mail/reading/conversationPrint.js +69 -0
  58. package/dist/apps/shared/components/mail/reading/printMessage.d.ts +7 -1
  59. package/dist/apps/shared/components/mail/reading/printMessage.js +33 -6
  60. package/dist/apps/shared/keyboard/keymap.d.ts +6 -0
  61. package/dist/apps/shared/keyboard/keymap.js +1 -0
  62. package/dist/apps/shared/mail/decryptedMessages.d.ts +27 -0
  63. package/dist/apps/shared/mail/decryptedMessages.js +97 -0
  64. package/dist/apps/www/calendar/index.js +5 -2
  65. package/dist/apps/www/index.js +10 -0
  66. package/dist/apps/www/settings/profile/index.js +6 -5
  67. package/dist/lib/auth/session.d.ts +14 -1
  68. package/dist/lib/auth/session.js +40 -3
  69. package/dist/lib/components/pickers/TimeZonePicker.d.ts +20 -0
  70. package/dist/lib/components/pickers/TimeZonePicker.js +100 -0
  71. package/dist/lib/util/api.d.ts +6 -0
  72. package/dist/lib/util/api.js +22 -1
  73. package/dist/lib/util/timeZone.d.ts +19 -1
  74. package/dist/lib/util/timeZone.js +46 -2
  75. package/lib/auth/session.ts +48 -3
  76. package/lib/components/pickers/TimeZonePicker.tsx +180 -0
  77. package/lib/util/api.ts +24 -1
  78. package/lib/util/timeZone.ts +50 -2
  79. package/package.json +1 -1
@@ -0,0 +1,100 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ ///////////////////////////////////////////////////////////////////////////////
3
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
4
+ // SPDX-License-Identifier: MPL-2.0
5
+ ///////////////////////////////////////////////////////////////////////////////
6
+ import { useEffect, useId, useMemo, useRef, useState } from "react";
7
+ import { compareTimeZones, describeTimeZone } from "../../util/timeZone.js";
8
+ /**
9
+ * A time zone chooser that lists zones as "Los Angeles, America (GMT-07:00)", west to east and then by city, and has a search box in the list: typing narrows it to the zones whose
10
+ * name or offset contains every word typed ("berlin", "gmt+9", "america indiana"). A button showing the chosen zone opens it; the arrow keys move
11
+ * through the list, Enter chooses, and Escape (or a click elsewhere) closes it without changing anything.
12
+ */
13
+ export default function TimeZonePicker({ id, "aria-label": label, "aria-describedby": describedBy, value, zones, onChange, at, className }) {
14
+ const listId = useId();
15
+ const root = useRef(null);
16
+ const trigger = useRef(null);
17
+ const search = useRef(null);
18
+ const selected = useRef(null);
19
+ const [open, setOpen] = useState(false);
20
+ const [query, setQuery] = useState("");
21
+ const [active, setActive] = useState(-1);
22
+ // Listed by the offsets shown (which move with daylight saving): west to east, then by city.
23
+ const entries = useMemo(() => [...zones]
24
+ .sort((a, b) => compareTimeZones(a, b, at))
25
+ .map((zone) => ({ zone, text: describeTimeZone(zone, at), haystack: `${describeTimeZone(zone, at)} ${zone.replace(/_/g, " ")}`.toLowerCase() })), [zones, at]);
26
+ const shown = useMemo(() => {
27
+ const words = query.toLowerCase().replace(/_/g, " ").split(/\s+/).filter(Boolean);
28
+ return words.length === 0 ? entries : entries.filter((entry) => words.every((word) => entry.haystack.includes(word)));
29
+ }, [entries, query]);
30
+ useEffect(() => {
31
+ if (!open) {
32
+ return undefined;
33
+ }
34
+ search.current?.focus();
35
+ selected.current?.scrollIntoView?.({ block: "center" });
36
+ const outside = (event) => {
37
+ if (!root.current?.contains(event.target)) {
38
+ close(false);
39
+ }
40
+ };
41
+ document.addEventListener("pointerdown", outside);
42
+ return () => document.removeEventListener("pointerdown", outside);
43
+ }, [open]);
44
+ function close(refocus) {
45
+ setOpen(false);
46
+ setQuery("");
47
+ setActive(-1);
48
+ if (refocus) {
49
+ trigger.current?.focus();
50
+ }
51
+ }
52
+ function choose(zone) {
53
+ if (zone !== value) {
54
+ onChange(zone);
55
+ }
56
+ close(true);
57
+ }
58
+ function move(step) {
59
+ setActive((index) => {
60
+ const from = index < 0 ? shown.findIndex((entry) => entry.zone === value) : index;
61
+ return Math.min(Math.max(from + step, 0), shown.length - 1);
62
+ });
63
+ }
64
+ function handleSearchKeyDown(event) {
65
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
66
+ event.preventDefault();
67
+ move(event.key === "ArrowDown" ? 1 : -1);
68
+ }
69
+ else if (event.key === "Enter") {
70
+ // Never the form's own submit.
71
+ event.preventDefault();
72
+ const entry = shown[active >= 0 ? active : 0];
73
+ if (entry && (active >= 0 || shown.length === 1)) {
74
+ choose(entry.zone);
75
+ }
76
+ }
77
+ else if (event.key === "Escape") {
78
+ event.stopPropagation();
79
+ close(true);
80
+ }
81
+ }
82
+ return (_jsxs("div", { ref: root, className: "relative inline-block max-w-full", children: [_jsxs("button", { ref: trigger, id: id, type: "button", role: "combobox", "aria-label": label, "aria-describedby": describedBy, "aria-haspopup": "listbox", "aria-expanded": open, "aria-controls": open ? listId : undefined, className: ["flex items-center justify-between gap-2 text-left", className].filter(Boolean).join(" "), onClick: () => setOpen((wasOpen) => !wasOpen), onKeyDown: (event) => {
83
+ if (event.key === "ArrowDown" && !open) {
84
+ event.preventDefault();
85
+ setOpen(true);
86
+ }
87
+ }, children: [_jsx("span", { className: "truncate", children: describeTimeZone(value, at) }), _jsx("span", { "aria-hidden": "true", className: "shrink-0 text-text-muted", children: "\u25BE" })] }), open && (_jsxs("div", { className: "absolute left-0 top-full z-30 mt-1 w-80 max-w-[90vw] rounded-md border border-border bg-surface shadow-lg", children: [_jsx("div", { className: "p-2", children: _jsx("input", { ref: search, type: "text", role: "searchbox", "aria-label": "Search time zones", "aria-controls": listId, "aria-activedescendant": active >= 0 ? `${listId}-${active}` : undefined, autoComplete: "off", placeholder: "Search", className: "w-full rounded-md border border-border bg-surface-alt px-3 py-1.5 text-sm text-text focus:border-primary focus:outline-none", value: query, onChange: (event) => {
88
+ setQuery(event.target.value);
89
+ setActive(-1);
90
+ }, onKeyDown: handleSearchKeyDown }) }), _jsxs("ul", { id: listId, role: "listbox", "aria-label": "Time zones", className: "max-h-60 overflow-y-auto pb-1", children: [shown.map((entry, index) => (_jsx("li", { id: `${listId}-${index}`, ref: entry.zone === value ? selected : undefined, role: "option", "aria-selected": entry.zone === value,
91
+ // Before the search box's blur or the outside-click check, which would otherwise close the list first.
92
+ onMouseDown: (event) => {
93
+ event.preventDefault();
94
+ choose(entry.zone);
95
+ }, className: [
96
+ "cursor-pointer px-3 py-1.5 text-sm hover:bg-surface-alt",
97
+ entry.zone === value ? "font-semibold text-primary-dark" : "",
98
+ index === active ? "bg-surface-alt" : "",
99
+ ].join(" "), children: entry.text }, entry.zone))), shown.length === 0 && _jsx("li", { className: "px-3 py-1.5 text-sm text-text-muted", children: "No time zones match." })] })] }))] }));
100
+ }
@@ -68,6 +68,12 @@ export declare function withCsrfHeader(headers: Record<string, string>, method?:
68
68
  * in one place, rather than repeated at every call site.
69
69
  */
70
70
  export declare function apiFetch<T = unknown>(path: string, init?: RequestInit): Promise<T>;
71
+ /**
72
+ * Registers what `apiFetch()` does when the server answers `401`: try to renew the signed-in session and, when that worked, send the request once
73
+ * more. `recovery` resolves whether the session was renewed. The app frame registers it while a session is open (`useSessionRefresh()`); pass
74
+ * `undefined` to remove it. A rejection counts as "not renewed".
75
+ */
76
+ export declare function setApiSessionRecovery(recovery: (() => Promise<boolean>) | undefined): void;
71
77
  /**
72
78
  * `fetch()` against auth-server's API — a *different* origin than this app, unlike `apiFetch()` above. Used
73
79
  * only for the handful of actions that must be issued by auth-server itself (e.g. admin impersonation, which
@@ -137,9 +137,30 @@ export async function apiFetch(path, init = {}) {
137
137
  headers.set("Content-Type", "application/json");
138
138
  applyCsrfHeader(headers, init.method);
139
139
  const credentials = apiBaseUrl ? "include" : init.credentials;
140
- const res = await fetch(apiUrl(path), { ...init, headers, credentials });
140
+ let res = await fetch(apiUrl(path), { ...init, headers, credentials });
141
+ // The access token has run out (a sleeping tab or laptop stops the timer that renews it in time): renew the session, and ask again once.
142
+ if (res.status === 401 && sessionRecovery && (await recoverSession())) {
143
+ res = await fetch(apiUrl(path), { ...init, headers, credentials });
144
+ }
141
145
  return decodeApiResponse(res, (error) => unauthorizedObserver?.(error));
142
146
  }
147
+ let sessionRecovery;
148
+ /**
149
+ * Registers what `apiFetch()` does when the server answers `401`: try to renew the signed-in session and, when that worked, send the request once
150
+ * more. `recovery` resolves whether the session was renewed. The app frame registers it while a session is open (`useSessionRefresh()`); pass
151
+ * `undefined` to remove it. A rejection counts as "not renewed".
152
+ */
153
+ export function setApiSessionRecovery(recovery) {
154
+ sessionRecovery = recovery;
155
+ }
156
+ async function recoverSession() {
157
+ try {
158
+ return await sessionRecovery();
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ }
143
164
  /**
144
165
  * `fetch()` against auth-server's API — a *different* origin than this app, unlike `apiFetch()` above. Used
145
166
  * only for the handful of actions that must be issued by auth-server itself (e.g. admin impersonation, which
@@ -6,7 +6,25 @@ export declare const DEFAULT_TIME_ZONE = "UTC";
6
6
  */
7
7
  export declare function deviceTimeZone(): string;
8
8
  /**
9
- * Every time zone the browser can name, for a picker: `Intl.supportedValuesOf("timeZone")` where there is one (it leaves out `UTC`,
9
+ * What `zone`'s clock is called and how far it is from UTC at `at`: `{ abbreviation: "PDT", offset: "-07:00" }`. `null` for a zone the runtime doesn't
10
+ * know. The abbreviation is the runtime's own (`GMT+1` where it has no name for a zone), the offset counts daylight saving on that date.
11
+ */
12
+ export declare function zoneClock(zone: string, at?: Date): {
13
+ abbreviation: string;
14
+ offset: string;
15
+ } | null;
16
+ /**
17
+ * A zone as a list or a line of text names it, city first, with how far its clock is from UTC: "Los Angeles, America (GMT-07:00)". Daylight saving
18
+ * is read at `at` (now, unless a date matters). A zone the runtime doesn't know is just its name.
19
+ */
20
+ export declare function describeTimeZone(zone: string, at?: Date): string;
21
+ /**
22
+ * Orders zones for a list: by how far their clocks are from UTC at `at` (the westernmost first), then by city, then by id. A zone the runtime
23
+ * doesn't know comes last.
24
+ */
25
+ export declare function compareTimeZones(a: string, b: string, at?: Date): number;
26
+ /**
27
+ * Every time zone the browser can name, for a picker (sorted by offset from UTC as it is now, then by city): `Intl.supportedValuesOf("timeZone")` where there is one (it leaves out `UTC`,
10
28
  * which is added), else just `extra` - the zones the caller already holds, such as a mailbox's current one.
11
29
  */
12
30
  export declare function timeZoneOptions(...extra: string[]): string[];
@@ -17,7 +17,50 @@ export function deviceTimeZone() {
17
17
  }
18
18
  }
19
19
  /**
20
- * Every time zone the browser can name, for a picker: `Intl.supportedValuesOf("timeZone")` where there is one (it leaves out `UTC`,
20
+ * What `zone`'s clock is called and how far it is from UTC at `at`: `{ abbreviation: "PDT", offset: "-07:00" }`. `null` for a zone the runtime doesn't
21
+ * know. The abbreviation is the runtime's own (`GMT+1` where it has no name for a zone), the offset counts daylight saving on that date.
22
+ */
23
+ export function zoneClock(zone, at = new Date()) {
24
+ try {
25
+ const part = (style) => new Intl.DateTimeFormat("en-US", { timeZone: zone, timeZoneName: style }).formatToParts(at).find((p) => p.type === "timeZoneName").value;
26
+ return { abbreviation: part("short"), offset: part("longOffset").replace("GMT", "") || "+00:00" };
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ /** A zone id split into its city and the region it is in: "America/Argentina/Buenos_Aires" is "Buenos Aires" in "America/Argentina"; "UTC" is in none. */
33
+ function zoneNames(zone) {
34
+ const parts = zone.split("/");
35
+ const city = parts.pop().replace(/_/g, " ");
36
+ return { city, region: parts.join("/").replace(/_/g, " ") };
37
+ }
38
+ /**
39
+ * A zone as a list or a line of text names it, city first, with how far its clock is from UTC: "Los Angeles, America (GMT-07:00)". Daylight saving
40
+ * is read at `at` (now, unless a date matters). A zone the runtime doesn't know is just its name.
41
+ */
42
+ export function describeTimeZone(zone, at = new Date()) {
43
+ const clock = zoneClock(zone, at);
44
+ if (!clock) {
45
+ return zone.replace(/_/g, " ");
46
+ }
47
+ const { city, region } = zoneNames(zone);
48
+ return `${city}${region ? `, ${region}` : ""} (GMT${clock.offset})`;
49
+ }
50
+ /**
51
+ * Orders zones for a list: by how far their clocks are from UTC at `at` (the westernmost first), then by city, then by id. A zone the runtime
52
+ * doesn't know comes last.
53
+ */
54
+ export function compareTimeZones(a, b, at = new Date()) {
55
+ const minutes = (zone) => {
56
+ const offset = zoneClock(zone, at)?.offset;
57
+ return offset ? (offset.startsWith("-") ? -1 : 1) * (Number(offset.slice(1, 3)) * 60 + Number(offset.slice(4, 6))) : Number.POSITIVE_INFINITY;
58
+ };
59
+ const byOffset = minutes(a) - minutes(b);
60
+ return (Number.isNaN(byOffset) ? 0 : byOffset) || zoneNames(a).city.localeCompare(zoneNames(b).city) || a.localeCompare(b);
61
+ }
62
+ /**
63
+ * Every time zone the browser can name, for a picker (sorted by offset from UTC as it is now, then by city): `Intl.supportedValuesOf("timeZone")` where there is one (it leaves out `UTC`,
21
64
  * which is added), else just `extra` - the zones the caller already holds, such as a mailbox's current one.
22
65
  */
23
66
  export function timeZoneOptions(...extra) {
@@ -28,5 +71,6 @@ export function timeZoneOptions(...extra) {
28
71
  catch {
29
72
  zones = [];
30
73
  }
31
- return [...new Set([DEFAULT_TIME_ZONE, ...zones, ...extra.filter(Boolean)])].sort((a, b) => a.localeCompare(b));
74
+ const now = new Date();
75
+ return [...new Set([DEFAULT_TIME_ZONE, ...zones, ...extra.filter(Boolean)])].sort((a, b) => compareTimeZones(a, b, now));
32
76
  }
@@ -15,7 +15,7 @@
15
15
  * sign-out already has.
16
16
  */
17
17
  import { useEffect, useRef } from "react";
18
- import { ApiRequestError, authApiFetch } from "../util/api.js";
18
+ import { ApiRequestError, authApiFetch, setApiSessionRecovery } from "../util/api.js";
19
19
  import { useApiClient } from "../util/apiClientContext.js";
20
20
 
21
21
  /** An access token's age at which it is refreshed. The token lives an hour; the margin leaves time to retry a failed refresh. */
@@ -76,6 +76,45 @@ export async function refreshSession(authServerUrl: string, force = false): Prom
76
76
  return locks ? locks.request(LOCK_NAME, run) : run();
77
77
  }
78
78
 
79
+ /** How long the outcome of a recovery is reused for: requests that fail together share one refresh, and a session that will not come back is not asked again at once. */
80
+ export const SESSION_RECOVERY_COOLDOWN_MS = 10 * 1000;
81
+
82
+ let recovery: Promise<boolean> | undefined;
83
+ let lastRecovery: { at: number; renewed: boolean } | undefined;
84
+
85
+ /**
86
+ * Renews the session because a request was refused for lack of one, whatever this browser's record of the last refresh says. Every request
87
+ * refused at about the same time shares one refresh, and its outcome is reused for `SESSION_RECOVERY_COOLDOWN_MS`. A refusal also clears the record of
88
+ * the last refresh, so the next regular check asks again (and sends the browser to sign-in if the refresh token is truly gone).
89
+ *
90
+ * @returns Whether the session was renewed.
91
+ */
92
+ export function recoverSession(authServerUrl: string): Promise<boolean> {
93
+ if (lastRecovery && Date.now() - lastRecovery.at < SESSION_RECOVERY_COOLDOWN_MS) {
94
+ return Promise.resolve(lastRecovery.renewed);
95
+ }
96
+ recovery ??= refreshSession(authServerUrl, true)
97
+ .then(
98
+ () => true,
99
+ () => {
100
+ writeTimestamp(() => localStorage, REFRESHED_AT_KEY, 0);
101
+ return false;
102
+ },
103
+ )
104
+ .then((renewed) => {
105
+ lastRecovery = { at: Date.now(), renewed };
106
+ recovery = undefined;
107
+ return renewed;
108
+ });
109
+ return recovery;
110
+ }
111
+
112
+ /** Forgets what recoveries have done (for tests). */
113
+ export function resetSessionRecovery(): void {
114
+ recovery = undefined;
115
+ lastRecovery = undefined;
116
+ }
117
+
79
118
  /** Whether `err` says auth-server rejected the refresh token itself, as opposed to a failure worth retrying. */
80
119
  function isAuthRejection(err: unknown): boolean {
81
120
  return err instanceof ApiRequestError && (err.status === 401 || err.status === 403);
@@ -129,7 +168,8 @@ export interface SessionRefreshOptions {
129
168
  * lifetime, or reopened later): attempts one silent refresh and reloads so the server renders the page with the new
130
169
  * cookie. If the refresh is refused (the refresh token expired or was revoked, or there was none), or a reload just
131
170
  * made still found no session, redirects to sign-in as `useRedirectIfUnauthenticated()` does.
132
- * - `userUid` set: refreshes once the token is `SESSION_REFRESH_AFTER_MS` old (and right away when this browser has no
171
+ * - `userUid` set: also renews the session when a request is refused for lack of one (`apiFetch()` asks `recoverSession()` and sends the request
172
+ * again), so a token that ran out while timers were stopped costs nothing. Refreshes once the token is `SESSION_REFRESH_AFTER_MS` old (and right away when this browser has no
133
173
  * record of a recent refresh, since the page's token age is unknown), checked every `SESSION_REFRESH_CHECK_MS` and
134
174
  * whenever the tab becomes visible or the network returns, because a sleeping laptop stops timers. A failure that is
135
175
  * not a rejection is simply retried at the next check. A rejection (`401`/`403`: the refresh token expired or was
@@ -169,7 +209,8 @@ export function useSessionRefresh(userUid: string | undefined, authServerUrl: st
169
209
  window.location.href = signInUrl(authServerUrl);
170
210
  return;
171
211
  }
172
- refreshSession(authServerUrl)
212
+ // Forced: the page has no session, so what this browser remembers of the last refresh says nothing about whether one is due.
213
+ refreshSession(authServerUrl, true)
173
214
  .then(() => {
174
215
  if (!cancelled) {
175
216
  writeTimestamp(() => sessionStorage, RELOADED_AT_KEY, Date.now());
@@ -190,6 +231,9 @@ export function useSessionRefresh(userUid: string | undefined, authServerUrl: st
190
231
  return;
191
232
  }
192
233
 
234
+ // A request the server refuses for lack of a session renews it (see `apiFetch()`), instead of waiting for the next check.
235
+ setApiSessionRecovery(() => recoverSession(authServerUrl));
236
+
193
237
  let leaving = false;
194
238
  let inFlight = false;
195
239
  const leave = async () => {
@@ -230,6 +274,7 @@ export function useSessionRefresh(userUid: string | undefined, authServerUrl: st
230
274
  window.addEventListener("online", check);
231
275
  return () => {
232
276
  cancelled = true;
277
+ setApiSessionRecovery(undefined);
233
278
  window.clearInterval(interval);
234
279
  document.removeEventListener("visibilitychange", onVisible);
235
280
  window.removeEventListener("online", check);
@@ -0,0 +1,180 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import React, { KeyboardEvent, useEffect, useId, useMemo, useRef, useState } from "react";
6
+ import { compareTimeZones, describeTimeZone } from "../../util/timeZone.js";
7
+
8
+ export interface TimeZonePickerProps {
9
+ id?: string;
10
+ "aria-label"?: string;
11
+ "aria-describedby"?: string;
12
+ /** The chosen zone (an IANA id). */
13
+ value: string;
14
+ /** The zones to choose between; the list orders them itself. */
15
+ zones: string[];
16
+ onChange: (zone: string) => void;
17
+ /** The date each zone's offset is read on (daylight saving); now unless a date matters. */
18
+ at?: Date;
19
+ className?: string;
20
+ }
21
+
22
+ /**
23
+ * A time zone chooser that lists zones as "Los Angeles, America (GMT-07:00)", west to east and then by city, and has a search box in the list: typing narrows it to the zones whose
24
+ * name or offset contains every word typed ("berlin", "gmt+9", "america indiana"). A button showing the chosen zone opens it; the arrow keys move
25
+ * through the list, Enter chooses, and Escape (or a click elsewhere) closes it without changing anything.
26
+ */
27
+ export default function TimeZonePicker({ id, "aria-label": label, "aria-describedby": describedBy, value, zones, onChange, at, className }: TimeZonePickerProps) {
28
+ const listId = useId();
29
+ const root = useRef<HTMLDivElement>(null);
30
+ const trigger = useRef<HTMLButtonElement>(null);
31
+ const search = useRef<HTMLInputElement>(null);
32
+ const selected = useRef<HTMLLIElement>(null);
33
+ const [open, setOpen] = useState(false);
34
+ const [query, setQuery] = useState("");
35
+ const [active, setActive] = useState(-1);
36
+
37
+ // Listed by the offsets shown (which move with daylight saving): west to east, then by city.
38
+ const entries = useMemo(
39
+ () =>
40
+ [...zones]
41
+ .sort((a, b) => compareTimeZones(a, b, at))
42
+ .map((zone) => ({ zone, text: describeTimeZone(zone, at), haystack: `${describeTimeZone(zone, at)} ${zone.replace(/_/g, " ")}`.toLowerCase() })),
43
+ [zones, at],
44
+ );
45
+ const shown = useMemo(() => {
46
+ const words = query.toLowerCase().replace(/_/g, " ").split(/\s+/).filter(Boolean);
47
+ return words.length === 0 ? entries : entries.filter((entry) => words.every((word) => entry.haystack.includes(word)));
48
+ }, [entries, query]);
49
+
50
+ useEffect(() => {
51
+ if (!open) {
52
+ return undefined;
53
+ }
54
+ search.current?.focus();
55
+ selected.current?.scrollIntoView?.({ block: "center" });
56
+ const outside = (event: PointerEvent) => {
57
+ if (!root.current?.contains(event.target as Node)) {
58
+ close(false);
59
+ }
60
+ };
61
+ document.addEventListener("pointerdown", outside);
62
+ return () => document.removeEventListener("pointerdown", outside);
63
+ }, [open]);
64
+
65
+ function close(refocus: boolean) {
66
+ setOpen(false);
67
+ setQuery("");
68
+ setActive(-1);
69
+ if (refocus) {
70
+ trigger.current?.focus();
71
+ }
72
+ }
73
+
74
+ function choose(zone: string) {
75
+ if (zone !== value) {
76
+ onChange(zone);
77
+ }
78
+ close(true);
79
+ }
80
+
81
+ function move(step: number) {
82
+ setActive((index) => {
83
+ const from = index < 0 ? shown.findIndex((entry) => entry.zone === value) : index;
84
+ return Math.min(Math.max(from + step, 0), shown.length - 1);
85
+ });
86
+ }
87
+
88
+ function handleSearchKeyDown(event: KeyboardEvent<HTMLInputElement>) {
89
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
90
+ event.preventDefault();
91
+ move(event.key === "ArrowDown" ? 1 : -1);
92
+ } else if (event.key === "Enter") {
93
+ // Never the form's own submit.
94
+ event.preventDefault();
95
+ const entry = shown[active >= 0 ? active : 0];
96
+ if (entry && (active >= 0 || shown.length === 1)) {
97
+ choose(entry.zone);
98
+ }
99
+ } else if (event.key === "Escape") {
100
+ event.stopPropagation();
101
+ close(true);
102
+ }
103
+ }
104
+
105
+ return (
106
+ <div ref={root} className="relative inline-block max-w-full">
107
+ <button
108
+ ref={trigger}
109
+ id={id}
110
+ type="button"
111
+ role="combobox"
112
+ aria-label={label}
113
+ aria-describedby={describedBy}
114
+ aria-haspopup="listbox"
115
+ aria-expanded={open}
116
+ aria-controls={open ? listId : undefined}
117
+ className={["flex items-center justify-between gap-2 text-left", className].filter(Boolean).join(" ")}
118
+ onClick={() => setOpen((wasOpen) => !wasOpen)}
119
+ onKeyDown={(event) => {
120
+ if (event.key === "ArrowDown" && !open) {
121
+ event.preventDefault();
122
+ setOpen(true);
123
+ }
124
+ }}
125
+ >
126
+ <span className="truncate">{describeTimeZone(value, at)}</span>
127
+ <span aria-hidden="true" className="shrink-0 text-text-muted">
128
+ &#9662;
129
+ </span>
130
+ </button>
131
+ {open && (
132
+ <div className="absolute left-0 top-full z-30 mt-1 w-80 max-w-[90vw] rounded-md border border-border bg-surface shadow-lg">
133
+ <div className="p-2">
134
+ <input
135
+ ref={search}
136
+ type="text"
137
+ role="searchbox"
138
+ aria-label="Search time zones"
139
+ aria-controls={listId}
140
+ aria-activedescendant={active >= 0 ? `${listId}-${active}` : undefined}
141
+ autoComplete="off"
142
+ placeholder="Search"
143
+ className="w-full rounded-md border border-border bg-surface-alt px-3 py-1.5 text-sm text-text focus:border-primary focus:outline-none"
144
+ value={query}
145
+ onChange={(event) => {
146
+ setQuery(event.target.value);
147
+ setActive(-1);
148
+ }}
149
+ onKeyDown={handleSearchKeyDown}
150
+ />
151
+ </div>
152
+ <ul id={listId} role="listbox" aria-label="Time zones" className="max-h-60 overflow-y-auto pb-1">
153
+ {shown.map((entry, index) => (
154
+ <li
155
+ key={entry.zone}
156
+ id={`${listId}-${index}`}
157
+ ref={entry.zone === value ? selected : undefined}
158
+ role="option"
159
+ aria-selected={entry.zone === value}
160
+ // Before the search box's blur or the outside-click check, which would otherwise close the list first.
161
+ onMouseDown={(event) => {
162
+ event.preventDefault();
163
+ choose(entry.zone);
164
+ }}
165
+ className={[
166
+ "cursor-pointer px-3 py-1.5 text-sm hover:bg-surface-alt",
167
+ entry.zone === value ? "font-semibold text-primary-dark" : "",
168
+ index === active ? "bg-surface-alt" : "",
169
+ ].join(" ")}
170
+ >
171
+ {entry.text}
172
+ </li>
173
+ ))}
174
+ {shown.length === 0 && <li className="px-3 py-1.5 text-sm text-text-muted">No time zones match.</li>}
175
+ </ul>
176
+ </div>
177
+ )}
178
+ </div>
179
+ );
180
+ }
package/lib/util/api.ts CHANGED
@@ -157,10 +157,33 @@ export async function apiFetch<T = unknown>(path: string, init: RequestInit = {}
157
157
  applyCsrfHeader(headers, init.method);
158
158
  const credentials = apiBaseUrl ? "include" : init.credentials;
159
159
 
160
- const res = await fetch(apiUrl(path), { ...init, headers, credentials });
160
+ let res = await fetch(apiUrl(path), { ...init, headers, credentials });
161
+ // The access token has run out (a sleeping tab or laptop stops the timer that renews it in time): renew the session, and ask again once.
162
+ if (res.status === 401 && sessionRecovery && (await recoverSession())) {
163
+ res = await fetch(apiUrl(path), { ...init, headers, credentials });
164
+ }
161
165
  return decodeApiResponse<T>(res, (error) => unauthorizedObserver?.(error));
162
166
  }
163
167
 
168
+ let sessionRecovery: (() => Promise<boolean>) | undefined;
169
+
170
+ /**
171
+ * Registers what `apiFetch()` does when the server answers `401`: try to renew the signed-in session and, when that worked, send the request once
172
+ * more. `recovery` resolves whether the session was renewed. The app frame registers it while a session is open (`useSessionRefresh()`); pass
173
+ * `undefined` to remove it. A rejection counts as "not renewed".
174
+ */
175
+ export function setApiSessionRecovery(recovery: (() => Promise<boolean>) | undefined): void {
176
+ sessionRecovery = recovery;
177
+ }
178
+
179
+ async function recoverSession(): Promise<boolean> {
180
+ try {
181
+ return await sessionRecovery!();
182
+ } catch {
183
+ return false;
184
+ }
185
+ }
186
+
164
187
  /**
165
188
  * `fetch()` against auth-server's API — a *different* origin than this app, unlike `apiFetch()` above. Used
166
189
  * only for the handful of actions that must be issued by auth-server itself (e.g. admin impersonation, which
@@ -19,7 +19,54 @@ export function deviceTimeZone(): string {
19
19
  }
20
20
 
21
21
  /**
22
- * Every time zone the browser can name, for a picker: `Intl.supportedValuesOf("timeZone")` where there is one (it leaves out `UTC`,
22
+ * What `zone`'s clock is called and how far it is from UTC at `at`: `{ abbreviation: "PDT", offset: "-07:00" }`. `null` for a zone the runtime doesn't
23
+ * know. The abbreviation is the runtime's own (`GMT+1` where it has no name for a zone), the offset counts daylight saving on that date.
24
+ */
25
+ export function zoneClock(zone: string, at: Date = new Date()): { abbreviation: string; offset: string } | null {
26
+ try {
27
+ const part = (style: "short" | "longOffset") =>
28
+ new Intl.DateTimeFormat("en-US", { timeZone: zone, timeZoneName: style }).formatToParts(at).find((p) => p.type === "timeZoneName")!.value;
29
+ return { abbreviation: part("short"), offset: part("longOffset").replace("GMT", "") || "+00:00" };
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ /** A zone id split into its city and the region it is in: "America/Argentina/Buenos_Aires" is "Buenos Aires" in "America/Argentina"; "UTC" is in none. */
36
+ function zoneNames(zone: string): { city: string; region: string } {
37
+ const parts = zone.split("/");
38
+ const city = parts.pop()!.replace(/_/g, " ");
39
+ return { city, region: parts.join("/").replace(/_/g, " ") };
40
+ }
41
+
42
+ /**
43
+ * A zone as a list or a line of text names it, city first, with how far its clock is from UTC: "Los Angeles, America (GMT-07:00)". Daylight saving
44
+ * is read at `at` (now, unless a date matters). A zone the runtime doesn't know is just its name.
45
+ */
46
+ export function describeTimeZone(zone: string, at: Date = new Date()): string {
47
+ const clock = zoneClock(zone, at);
48
+ if (!clock) {
49
+ return zone.replace(/_/g, " ");
50
+ }
51
+ const { city, region } = zoneNames(zone);
52
+ return `${city}${region ? `, ${region}` : ""} (GMT${clock.offset})`;
53
+ }
54
+
55
+ /**
56
+ * Orders zones for a list: by how far their clocks are from UTC at `at` (the westernmost first), then by city, then by id. A zone the runtime
57
+ * doesn't know comes last.
58
+ */
59
+ export function compareTimeZones(a: string, b: string, at: Date = new Date()): number {
60
+ const minutes = (zone: string) => {
61
+ const offset = zoneClock(zone, at)?.offset;
62
+ return offset ? (offset.startsWith("-") ? -1 : 1) * (Number(offset.slice(1, 3)) * 60 + Number(offset.slice(4, 6))) : Number.POSITIVE_INFINITY;
63
+ };
64
+ const byOffset = minutes(a) - minutes(b);
65
+ return (Number.isNaN(byOffset) ? 0 : byOffset) || zoneNames(a).city.localeCompare(zoneNames(b).city) || a.localeCompare(b);
66
+ }
67
+
68
+ /**
69
+ * Every time zone the browser can name, for a picker (sorted by offset from UTC as it is now, then by city): `Intl.supportedValuesOf("timeZone")` where there is one (it leaves out `UTC`,
23
70
  * which is added), else just `extra` - the zones the caller already holds, such as a mailbox's current one.
24
71
  */
25
72
  export function timeZoneOptions(...extra: string[]): string[] {
@@ -29,5 +76,6 @@ export function timeZoneOptions(...extra: string[]): string[] {
29
76
  } catch {
30
77
  zones = [];
31
78
  }
32
- return [...new Set([DEFAULT_TIME_ZONE, ...zones, ...extra.filter(Boolean)])].sort((a, b) => a.localeCompare(b));
79
+ const now = new Date();
80
+ return [...new Set([DEFAULT_TIME_ZONE, ...zones, ...extra.filter(Boolean)])].sort((a, b) => compareTimeZones(a, b, now));
33
81
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rapidmx/web-client",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "description": "RapidMX's webmail and admin console React UI for web-based clients.",
5
5
  "type": "module",
6
6
  "repository": "https://github.com/rapidmx/web-client",