@semics-tech/emdash-events 1.0.0-rc.0 → 1.0.0-rc.1

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.
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The booking page's attendee signing list (T133, R95; Suite Pro). Events Pro's `public/booking`
3
+ * describes each seat of a waiver booking (`seat`, `signing`, `signs`, `email`, `minor`) and whether
4
+ * names may still be changed (`signingList.editable`, until `attendeeEditCutoffHours` before the
5
+ * start); Free sends none of it, so `signingRows` is null and the page shows nothing new.
6
+ *
7
+ * The list's forms post back to `/booking` (no JavaScript needed). `handleAttendeeAction` calls the
8
+ * Pro routes with the cookie's access token, never a form field, and redeems what they mint with
9
+ * e-sign in-process:
10
+ *
11
+ * - Sign now (`intent=sign-now`): `public/booking/attendees/sign` mints one inline intent for the
12
+ * seat (the attendee signs for themselves on this device; a minor's guardian signs for them), which
13
+ * `startDoorSigning` redeems before sending the browser to e-sign's signing page.
14
+ * - Resend (`intent=resend`, emailed adults): `public/booking/attendees/resend` mints a `resend`
15
+ * intent; e-sign emails the open envelope's invitation again (rate limited by Events Pro).
16
+ * - Save (`intent=attendees`): `public/booking/attendees` stores the corrected names and emails and
17
+ * mints, per changed seat, a `replace` intent (e-sign voids the old envelope) and, for an emailed
18
+ * adult, the new invitation's intent, redeemed in that order.
19
+ *
20
+ * Every outcome is a redirect to `/booking?ref=` with a code, never a typed value. Web APIs only (R35).
21
+ */
22
+ import { callPublicRoute, type PublicRouteContext } from "./call";
23
+ import { BOOKING_PATH } from "./checkout-form";
24
+ import { type ReceiptOptions, startDoorSigning } from "./receipt";
25
+ import type { BookingView } from "./widget";
26
+
27
+ /** What Events Pro adds to each attendee of a waiver booking's `public/booking` answer. */
28
+ export interface SigningAttendee {
29
+ name: string;
30
+ seat?: string;
31
+ email?: string;
32
+ minor?: boolean;
33
+ signing?: "signed" | "waiting";
34
+ /** `email`: an adult e-sign invites by email; `inline`: signed on the buyer's device. */
35
+ signs?: "inline" | "email";
36
+ }
37
+
38
+ export interface SigningRow {
39
+ seat: string;
40
+ name: string;
41
+ email: string;
42
+ minor: boolean;
43
+ signed: boolean;
44
+ canSign: boolean;
45
+ canResend: boolean;
46
+ canEdit: boolean;
47
+ }
48
+
49
+ export interface AttendeeEdit {
50
+ seat: string;
51
+ name: string;
52
+ email?: string;
53
+ }
54
+
55
+ /** Statuses in which a waiver can still be signed: the hold's, and a confirmed booking's pending seats. */
56
+ const OPEN = ["awaiting_signature", "awaiting_payment", "confirmed"];
57
+ const SEAT = /^[0-9]{1,3}$/;
58
+ const CODE = /^[A-Z_]{1,40}$/;
59
+ const MAX_TEXT = 254;
60
+ /** Issue codes of a refused save the page explains itself; any other issue is an invalid entry. */
61
+ const ISSUE_CODES = ["ATTENDEE_SIGNED", "WAIVER_EMAIL_REQUIRED", "WAIVER_TOO_MANY_EMAILS", "RATE_LIMITED"];
62
+
63
+ /** The list's rows, or null when the answer has no signing list (Free, or not a waiver booking). */
64
+ export function signingRows(booking: BookingView): SigningRow[] | null {
65
+ const list = booking.signingList;
66
+ if (!list) return null;
67
+ const open = OPEN.includes(booking.status);
68
+ const rows: SigningRow[] = [];
69
+ for (const a of booking.attendees as SigningAttendee[]) {
70
+ if (typeof a.seat !== "string" || !SEAT.test(a.seat) || !a.signing) continue;
71
+ const signed = a.signing === "signed";
72
+ const waiting = open && !signed;
73
+ rows.push({
74
+ seat: a.seat,
75
+ name: a.name,
76
+ email: a.email ?? "",
77
+ minor: a.minor === true,
78
+ signed,
79
+ canSign: waiting,
80
+ canResend: waiting && a.signs === "email",
81
+ canEdit: waiting && list.editable === true,
82
+ });
83
+ }
84
+ return rows.length > 0 ? rows : null;
85
+ }
86
+
87
+ const text = (form: FormData, key: string): string | undefined => {
88
+ const value = form.get(key);
89
+ return typeof value === "string" ? value.trim().slice(0, MAX_TEXT) : undefined;
90
+ };
91
+
92
+ /** The edit form's values for the editable seats (`name:<seat>`, `email:<seat>`); a minor has no email. */
93
+ export function readAttendeeEdits(form: FormData, rows: readonly SigningRow[]): AttendeeEdit[] {
94
+ return rows
95
+ .filter((r) => r.canEdit)
96
+ .map((r) => {
97
+ const name = text(form, `name:${r.seat}`) ?? r.name;
98
+ if (r.minor) return { seat: r.seat, name };
99
+ return { seat: r.seat, name, email: text(form, `email:${r.seat}`) ?? r.email };
100
+ });
101
+ }
102
+
103
+ const post = <T>(ctx: PublicRouteContext, pluginId: string | undefined, path: string, body: unknown) =>
104
+ callPublicRoute<T>(ctx, { method: "POST", path, body, ...(pluginId ? { pluginId } : {}) });
105
+
106
+ function back(ref: string, key: "error" | "attendees", value: string): { location: string } {
107
+ const query = new URLSearchParams({ ref });
108
+ query.set(key, key === "error" && !CODE.test(value) ? "INTERNAL" : value);
109
+ return { location: `${BOOKING_PATH}?${query}` };
110
+ }
111
+
112
+ interface Minted {
113
+ intent?: unknown;
114
+ lookup?: unknown;
115
+ intents?: Array<{ token?: unknown }>;
116
+ }
117
+
118
+ /**
119
+ * Handles the list's posts (`intent` = `sign-now`, `resend` or `attendees`); null for any other
120
+ * form. `booking` is the page's fresh `public/booking` answer, so only offered actions are sent.
121
+ */
122
+ export async function handleAttendeeAction(
123
+ ctx: PublicRouteContext,
124
+ form: FormData,
125
+ access: { ref: string; token: string },
126
+ options: ReceiptOptions,
127
+ booking: BookingView,
128
+ ): Promise<{ location: string } | null> {
129
+ const intent = form.get("intent");
130
+ if (intent !== "sign-now" && intent !== "resend" && intent !== "attendees") return null;
131
+ const { ref } = access;
132
+ if (!options.esignPluginId) return back(ref, "error", "ESIGN_NOT_CONFIGURED");
133
+ const rows = signingRows(booking) ?? [];
134
+ const auth = { bookingRef: ref, accessToken: access.token };
135
+
136
+ if (intent === "attendees") {
137
+ const attendees = readAttendeeEdits(form, rows);
138
+ if (attendees.length === 0) return back(ref, "error", "ATTENDEES_LOCKED");
139
+ const saved = await post<Minted>(ctx, options.pluginId, "public/booking/attendees", { ...auth, attendees });
140
+ if (!saved.ok) {
141
+ const issue = saved.error.issues?.find((i) => ISSUE_CODES.includes(String(i.code)));
142
+ if (issue) return back(ref, "error", String(issue.code));
143
+ return back(ref, "error", saved.error.code === "BAD_REQUEST" ? "ATTENDEE_INVALID" : saved.error.code);
144
+ }
145
+ // In order: each changed seat's `replace` (void the old envelope) before its new invitation.
146
+ for (const minted of saved.data.intents ?? []) {
147
+ const redeemed = await post(ctx, options.esignPluginId, "public/envelopes/from-intent", {
148
+ intent: minted.token,
149
+ });
150
+ if (!redeemed.ok) return back(ref, "error", "ATTENDEES_UNSENT");
151
+ }
152
+ return back(ref, "attendees", "saved");
153
+ }
154
+
155
+ const seat = form.get("seat");
156
+ const row = rows.find((r) => r.seat === seat);
157
+ if (!row || !(intent === "resend" ? row.canResend : row.canSign)) return back(ref, "error", "BAD_REQUEST");
158
+ if (intent === "resend") {
159
+ const minted = await post<Minted>(ctx, options.pluginId, "public/booking/attendees/resend", { ...auth, seat });
160
+ if (!minted.ok) return back(ref, "error", minted.error.code);
161
+ const sent = await post(ctx, options.esignPluginId, "public/envelopes/from-intent", { intent: minted.data.intent });
162
+ return sent.ok ? back(ref, "attendees", "resent") : back(ref, "error", "SIGNING_UNAVAILABLE");
163
+ }
164
+ const minted = await post<Minted>(ctx, options.pluginId, "public/booking/attendees/sign", { ...auth, seat });
165
+ if (!minted.ok) return back(ref, "error", minted.error.code);
166
+ const started = await startDoorSigning(ctx, minted.data.intent, options, minted.data.lookup);
167
+ if ("location" in started) return started;
168
+ if ("signed" in started) return { location: `${BOOKING_PATH}?ref=${ref}&waiver=signed` };
169
+ return back(ref, "error", started.error);
170
+ }
@@ -0,0 +1,245 @@
1
+ /**
2
+ * The booking form's day-then-time picker (T130, EV-FR-17): pure helpers for `<BookingWidget>`.
3
+ *
4
+ * An event with a slot schedule, or with more than one start on a local day, is booked by picking a
5
+ * day on a month calendar, then one of that day's times. The page renders both the calendar and, for
6
+ * visitors without JavaScript, a plain `<select>` of the same month's dates grouped by day
7
+ * (`<optgroup>`); `src/client/picker.ts` swaps one for the other. Days are the event's local days
8
+ * (`timezone`, else UTC), so a slot at 23:30 in New York sits on that evening's day, and both runs of a
9
+ * repeated DST hour stay on their day.
10
+ *
11
+ * Paging: `public/event` answers up to 200 upcoming open slots from `from` (closed ones never), with
12
+ * `more` when there are further ones. The widget shows one month, starting at its `booking_from.<eventId>` query
13
+ * parameter (a local `YYYY-MM-DD`, today when absent or past); it asks the core from that day's earliest
14
+ * possible local midnight (UTC+14) and skips what falls before the day. A truncated answer's last day
15
+ * may be partial, so it is left for the next page, which starts on it.
16
+ */
17
+ import { translator } from "../../i18n/index";
18
+ import { anchorId, WIDGET_PARAMS } from "./widget";
19
+
20
+ /** The query parameter holding the first local day the picker shows (prefix: one per widget). */
21
+ export const PICKER_PARAM = "booking_from";
22
+
23
+ /**
24
+ * One widget's `booking_from` parameter, keyed by its event (`booking_from.<eventId>`, T134), so two
25
+ * pickers on a page page independently, with or without JavaScript (paging is a plain link).
26
+ */
27
+ export const pickerParam = (eventId: string) => `${PICKER_PARAM}.${eventId.replace(/[^A-Za-z0-9_-]/g, "_")}`;
28
+
29
+ const DAY_KEY = /^(\d{4})-(\d{2})-(\d{2})$/;
30
+ const HOUR = 3_600_000;
31
+ /** The earliest a local midnight can be, relative to UTC midnight of the same date (UTC+14). */
32
+ const EARLIEST_OFFSET = 14 * HOUR;
33
+
34
+ export interface PickerOccurrence {
35
+ id: string;
36
+ startsAt: string;
37
+ endsAt?: string | null;
38
+ available?: number | null;
39
+ }
40
+
41
+ export interface PickerSlot {
42
+ id: string;
43
+ /** The start's local time (`09:30`). */
44
+ time: string;
45
+ /** "3 places left" or "Full"; empty when the core does not say. */
46
+ places: string;
47
+ full: boolean;
48
+ /** What a screen reader hears: time and places. */
49
+ label: string;
50
+ }
51
+
52
+ export interface PickerDay {
53
+ /** The local day, `YYYY-MM-DD`. */
54
+ key: string;
55
+ /** Day of the month. */
56
+ day: number;
57
+ /** The full date ("Wednesday 4 November 2026"). */
58
+ label: string;
59
+ /** The day button's accessible name: the date, plus "fully booked" when no slot has room. */
60
+ buttonLabel: string;
61
+ slots: PickerSlot[];
62
+ /** Some slot has room. */
63
+ open: boolean;
64
+ }
65
+
66
+ /** A calendar cell: a day of the month (with no slots: `slots` is empty), or `null` before/after it. */
67
+ export type PickerCell = PickerDay | null;
68
+
69
+ export interface PickerView {
70
+ month: { key: string; label: string };
71
+ weekdays: Array<{ short: string; long: string }>;
72
+ /** Weeks of seven cells, Monday first. */
73
+ weeks: PickerCell[][];
74
+ /** The month's days that have slots, earliest first. */
75
+ days: PickerDay[];
76
+ /** The day button that takes focus first (roving tabindex): the first open day, else the first day. */
77
+ focusDay?: string;
78
+ /** `booking_from` values for the earlier and later pages. */
79
+ prev?: string;
80
+ next?: string;
81
+ }
82
+
83
+ function formatter(locale: string, zone: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
84
+ try {
85
+ return new Intl.DateTimeFormat(locale, { ...options, timeZone: zone });
86
+ } catch {
87
+ return new Intl.DateTimeFormat(locale, { ...options, timeZone: "UTC" });
88
+ }
89
+ }
90
+
91
+ const pad = (n: number) => String(n).padStart(2, "0");
92
+
93
+ /** The local day (`YYYY-MM-DD`) of an instant in a zone (UTC for an unknown zone). */
94
+ export function localDay(ms: number, zone: string): string {
95
+ const parts = formatter("en-US", zone, { year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(ms);
96
+ const get = (type: string) => Number(parts.find((p) => p.type === type)?.value);
97
+ return `${get("year")}-${pad(get("month"))}-${pad(get("day"))}`;
98
+ }
99
+
100
+ /** A real calendar date `YYYY-MM-DD` as UTC midnight (ms), else `null`. */
101
+ function dayMs(key: string | null | undefined): number | null {
102
+ const m = DAY_KEY.exec(key ?? "");
103
+ if (!m) return null;
104
+ const ms = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
105
+ return new Date(ms).toISOString().slice(0, 10) === key ? ms : null;
106
+ }
107
+
108
+ const keyOf = (ms: number) => new Date(ms).toISOString().slice(0, 10);
109
+ const monthFirst = (month: string, delta = 0) => {
110
+ const [y, m] = month.split("-").map(Number) as [number, number];
111
+ return keyOf(Date.UTC(y, m - 1 + delta, 1));
112
+ };
113
+
114
+ /** Whether the form books through the picker: a slot schedule, or two starts on one local day. */
115
+ export function usesPicker(
116
+ event: { occurrences?: PickerOccurrence[]; slots?: boolean; timezone?: string } | undefined,
117
+ zone = event?.timezone ?? "UTC",
118
+ ): boolean {
119
+ if (!event) return false;
120
+ if (event.slots === true) return true;
121
+ const seen = new Set<string>();
122
+ for (const o of event.occurrences ?? []) {
123
+ const day = localDay(Date.parse(o.startsAt), zone);
124
+ if (seen.has(day)) return true;
125
+ seen.add(day);
126
+ }
127
+ return false;
128
+ }
129
+
130
+ /** The occurrences grouped by local day, earliest first, with their times and places left. */
131
+ export function groupByDay(occurrences: readonly PickerOccurrence[], zone: string, locale: string): PickerDay[] {
132
+ const { t, plural } = translator(locale);
133
+ const time = formatter(locale, zone, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
134
+ const date = formatter(locale, "UTC", { dateStyle: "full" });
135
+ const days = new Map<string, PickerDay>();
136
+ const sorted = occurrences
137
+ .map((o) => ({ o, ms: Date.parse(o.startsAt) }))
138
+ .filter(({ ms }) => Number.isFinite(ms))
139
+ .sort((a, b) => a.ms - b.ms);
140
+ for (const { o, ms } of sorted) {
141
+ const key = localDay(ms, zone);
142
+ let day = days.get(key);
143
+ if (!day) {
144
+ const label = date.format(dayMs(key) ?? ms);
145
+ day = { key, day: Number(key.slice(8)), label, buttonLabel: label, slots: [], open: false };
146
+ days.set(key, day);
147
+ }
148
+ const known = typeof o.available === "number";
149
+ const full = known && (o.available as number) <= 0;
150
+ const places = !known ? "" : full ? t("widget.picker.full") : plural("widget.picker.left", o.available as number);
151
+ const at = time.format(ms);
152
+ day.slots.push({ id: o.id, time: at, places, full, label: places ? `${at}, ${places}` : at });
153
+ if (!full) day.open = true;
154
+ }
155
+ for (const day of days.values()) {
156
+ if (!day.open) day.buttonLabel = t("widget.picker.dayFull", { date: day.label });
157
+ }
158
+ return [...days.values()];
159
+ }
160
+
161
+ /** The `from` to ask `public/event` for, for a `booking_from` day: its earliest possible local midnight. */
162
+ export function pickerFetchFrom(start: string | null | undefined): string | undefined {
163
+ const ms = dayMs(start);
164
+ return ms === null ? undefined : new Date(ms - EARLIEST_OFFSET).toISOString();
165
+ }
166
+
167
+ /**
168
+ * A link to another page of one event's picker: the current page's query without widget errors (other
169
+ * widgets' pages kept), and that widget's anchor.
170
+ */
171
+ export function pickerHref(url: URL, start: string, eventId: string): string {
172
+ const next = new URL(url.href);
173
+ for (const name of Object.values(WIDGET_PARAMS)) next.searchParams.delete(name);
174
+ next.searchParams.set(pickerParam(eventId), start);
175
+ return `${next.pathname}${next.search}#${anchorId(eventId)}`;
176
+ }
177
+
178
+ export interface PickerOptions {
179
+ zone: string;
180
+ locale: string;
181
+ /** The `booking_from` parameter (a local `YYYY-MM-DD`), if any. */
182
+ start: string | null | undefined;
183
+ now: number;
184
+ /** `public/event` said there are more slots after the ones it sent. */
185
+ more?: boolean;
186
+ }
187
+
188
+ /** One month of the picker: its calendar, its days with slots, and the paging links. */
189
+ export function pickerView(occurrences: readonly PickerOccurrence[], opts: PickerOptions): PickerView {
190
+ const today = localDay(opts.now, opts.zone);
191
+ const asked = dayMs(opts.start) === null ? today : (opts.start as string);
192
+ const start = asked > today ? asked : today;
193
+ const startMonth = start.slice(0, 7);
194
+
195
+ const grouped = groupByDay(occurrences, opts.zone, opts.locale).filter((d) => d.key >= start);
196
+ const partial = opts.more && grouped.length > 1 ? grouped.pop() : undefined;
197
+ const month = grouped.some((d) => d.key.startsWith(startMonth))
198
+ ? startMonth
199
+ : (grouped[0]?.key.slice(0, 7) ?? startMonth);
200
+ const days = grouped.filter((d) => d.key.startsWith(month));
201
+ const following = monthFirst(month, 1);
202
+
203
+ let next: string | undefined;
204
+ if (partial?.key.startsWith(month)) next = partial.key;
205
+ else if (partial || grouped.some((d) => d.key >= following)) next = following;
206
+
207
+ let prev: string | undefined;
208
+ if (start > today) {
209
+ const back = start > monthFirst(startMonth) ? monthFirst(startMonth) : monthFirst(startMonth, -1);
210
+ prev = back > today ? back : today;
211
+ }
212
+
213
+ const [y, m] = month.split("-").map(Number) as [number, number];
214
+ const first = Date.UTC(y, m - 1, 1);
215
+ const length = new Date(Date.UTC(y, m, 0)).getUTCDate();
216
+ const byDay = new Map(days.map((d) => [d.day, d]));
217
+ const date = formatter(opts.locale, "UTC", { dateStyle: "full" });
218
+ const cells: PickerCell[] = Array.from({ length: (new Date(first).getUTCDay() + 6) % 7 }, () => null);
219
+ for (let d = 1; d <= length; d++) {
220
+ const key = `${month}-${pad(d)}`;
221
+ const label = date.format(Date.UTC(y, m - 1, d));
222
+ cells.push(byDay.get(d) ?? { key, day: d, label, buttonLabel: label, slots: [], open: false });
223
+ }
224
+ while (cells.length % 7 !== 0) cells.push(null);
225
+ const weeks = Array.from({ length: cells.length / 7 }, (_, i) => cells.slice(i * 7, i * 7 + 7));
226
+
227
+ const short = formatter(opts.locale, "UTC", { weekday: "short" });
228
+ const long = formatter(opts.locale, "UTC", { weekday: "long" });
229
+ // 5 January 2026 is a Monday.
230
+ const weekdays = Array.from({ length: 7 }, (_, i) => {
231
+ const ms = Date.UTC(2026, 0, 5 + i);
232
+ return { short: short.format(ms), long: long.format(ms) };
233
+ });
234
+
235
+ const focus = days.find((d) => d.open) ?? days[0];
236
+ return {
237
+ month: { key: month, label: formatter(opts.locale, "UTC", { month: "long", year: "numeric" }).format(first) },
238
+ weekdays,
239
+ weeks,
240
+ days,
241
+ ...(focus ? { focusDay: focus.key } : {}),
242
+ ...(prev ? { prev } : {}),
243
+ ...(next ? { next } : {}),
244
+ };
245
+ }
@@ -26,7 +26,12 @@ export interface PublicEvent {
26
26
  minPerOrder?: number | null;
27
27
  maxPerOrder?: number | null;
28
28
  }>;
29
+ /** Upcoming open dates, earliest first: up to 200 from the asked `from` (T130). */
29
30
  occurrences?: Array<{ id: string; startsAt: string; endsAt?: string | null; available?: number | null }>;
31
+ /** More dates follow the ones sent: ask again `from` a later day (T130). */
32
+ more?: boolean;
33
+ /** The event sells slots of a schedule (T129): the form uses the day-then-time picker (T130). */
34
+ slots?: boolean;
30
35
  /** Public Turnstile site key, when the site owner configured one. */
31
36
  turnstileSiteKey?: string;
32
37
  /** True when the event requires a signed waiver (T066): the booking form then asks for attendees. */
@@ -39,6 +44,14 @@ export interface PublicEvent {
39
44
  questions?: PublicQuestion[];
40
45
  }
41
46
 
47
+ /**
48
+ * Ticket type names by id from a `public/event` answer, for `<BookingStatus>` (T134): the booking's
49
+ * lines carry only ids (UUIDs for types made in the editor). A hidden type is not listed there.
50
+ */
51
+ export function ticketNames(event: Pick<PublicEvent, "ticketTypes"> | undefined): Record<string, string> {
52
+ return Object.fromEntries((event?.ticketTypes ?? []).map((t) => [t.id, t.name]));
53
+ }
54
+
42
55
  /** One custom question as `public/event` lists it (EV-FR-15). */
43
56
  export interface PublicQuestion {
44
57
  id: string;
@@ -68,6 +81,12 @@ export interface BookingView {
68
81
  * receipt-lookup request for each, which the suite's reconciliation sends to e-sign.
69
82
  */
70
83
  waiver?: { refs: string[]; lookups?: Record<string, string> };
84
+ /**
85
+ * Events Pro (T133): a waiver booking's attendee signing list. Each attendee then also carries
86
+ * `seat`, `signing`, `signs`, `email` and `minor` (`SigningAttendee` in `lib/attendees.ts`);
87
+ * `editable` says whether names and emails may still be changed, until `editUntil`.
88
+ */
89
+ signingList?: { editable: boolean; editUntil?: string };
71
90
  }
72
91
 
73
92
  /** A custom question's field is `q:<question id>` (T080). */
@@ -263,11 +282,13 @@ const STATUSES = [
263
282
  "held",
264
283
  "awaiting_signature",
265
284
  "awaiting_payment",
285
+ "awaiting_approval",
266
286
  "confirmed",
267
287
  "expired",
268
288
  "cancelled",
269
289
  "refunded",
270
290
  "refunded_unavailable",
291
+ "declined",
271
292
  ] as const;
272
293
 
273
294
  /** A booking status for people, in the locale's language; an unknown status is shown as it is. */
@@ -104,7 +104,9 @@ function showErrors(form: HTMLFormElement, bad: readonly BookingField[]): void {
104
104
  }
105
105
  const first = bad[0] && form.querySelector<HTMLElement>(`[data-field="${bad[0]}"]`);
106
106
  if (!first) return;
107
- const target = first.matches("fieldset") ? first.querySelector<HTMLElement>("input:not([disabled])") : first;
107
+ // A fieldset: its first live input, or the day picker's focusable day (T130).
108
+ const live = 'input:not([disabled]), button[tabindex="0"]'; // i18n-ignore
109
+ const target = first.matches("fieldset") ? first.querySelector<HTMLElement>(live) : first;
108
110
  target?.focus();
109
111
  }
110
112
 
@@ -0,0 +1,143 @@
1
+ /**
2
+ * The booking form's day-then-time picker (T130, EV-FR-17). `<BookingWidget>` renders the month
3
+ * calendar (`[data-picker]`, hidden) beside a plain `<select name="occurrenceId">` grouped by day
4
+ * (`[data-picker-fallback]`), so the form works without this script. With it, the calendar replaces the
5
+ * select: a day button (`data-day`) shows that day's times (`[data-times]`, a radio group of buttons,
6
+ * full ones `aria-disabled`), and choosing a time sets the select, which is what the form posts.
7
+ *
8
+ * Keyboard: roving tabindex over the day buttons (arrows by a day, up and down by a week, Home/End; to
9
+ * the next day that has slots), and over a day's times (arrows, wrapping, skipping full ones). Text
10
+ * only comes from the page's markup; this script writes none. Self-contained (no imports).
11
+ */
12
+
13
+ const DELTAS: Record<string, number> = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: 7, ArrowUp: -7 };
14
+
15
+ /** The day (of `days`, ascending) a key moves to from `current`, or `null` to stay. */
16
+ export function stepDay(days: readonly number[], current: number, key: string, rtl: boolean): number | null {
17
+ // i18n-ignore
18
+ if (key === "Home") return days[0] ?? null;
19
+ // i18n-ignore
20
+ if (key === "End") return days[days.length - 1] ?? null;
21
+ let delta = DELTAS[key];
22
+ if (delta === undefined) return null;
23
+ if (rtl && Math.abs(delta) === 1) delta = -delta;
24
+ const target = current + delta;
25
+ const found = delta > 0 ? days.find((d) => d >= target) : [...days].reverse().find((d) => d <= target);
26
+ return found ?? null;
27
+ }
28
+
29
+ /** The time (index into `open`) a key moves to from `current`, wrapping and skipping full ones. */
30
+ export function stepRadio(open: readonly boolean[], current: number, key: string, rtl: boolean): number | null {
31
+ let delta = DELTAS[key];
32
+ if (delta === undefined) return null;
33
+ delta = Math.sign(delta);
34
+ if (rtl && (key === "ArrowLeft" || key === "ArrowRight")) delta = -delta;
35
+ const n = open.length;
36
+ for (let i = 1; i <= n; i++) {
37
+ const at = (((current + delta * i) % n) + n) % n;
38
+ if (open[at] && at !== current) return at;
39
+ }
40
+ return null;
41
+ }
42
+
43
+ const isRtl = (el: Element) => getComputedStyle(el).direction === "rtl";
44
+
45
+ /** Wire one picker. Safe to call twice. */
46
+ export function enhancePicker(picker: HTMLElement): void {
47
+ if (picker.dataset.enhanced) return;
48
+ const form = picker.closest("form");
49
+ const select = form?.querySelector<HTMLSelectElement>('select[name="occurrenceId"]');
50
+ if (!form || !select) return;
51
+ picker.dataset.enhanced = "1";
52
+ const fallback = form.querySelector<HTMLElement>("[data-picker-fallback]");
53
+ if (fallback) fallback.hidden = true;
54
+ select.required = false;
55
+ picker.hidden = false;
56
+
57
+ const dayButtons = Array.from(picker.querySelectorAll<HTMLButtonElement>("button[data-day]"));
58
+ const groups = Array.from(picker.querySelectorAll<HTMLElement>("[data-times]"));
59
+ const hint = picker.querySelector<HTMLElement>("[data-picker-hint]");
60
+ const radios = (group: HTMLElement) => Array.from(group.querySelectorAll<HTMLButtonElement>('[role="radio"]'));
61
+ const isOpen = (b: HTMLElement) => b.getAttribute("aria-disabled") !== "true";
62
+
63
+ const setSelect = (value: string) => {
64
+ if (select.value === value) return;
65
+ select.value = value;
66
+ select.dispatchEvent(new Event("change", { bubbles: true }));
67
+ };
68
+
69
+ const chooseTime = (button: HTMLButtonElement, focus: boolean) => {
70
+ if (!isOpen(button)) return;
71
+ for (const group of groups) {
72
+ for (const r of radios(group)) {
73
+ const on = r === button;
74
+ r.setAttribute("aria-checked", on ? "true" : "false");
75
+ if (group.contains(button)) r.tabIndex = on ? 0 : -1;
76
+ }
77
+ }
78
+ if (focus) button.focus();
79
+ setSelect(button.dataset.occurrence ?? "");
80
+ };
81
+
82
+ const showDay = (button: HTMLButtonElement, focus: boolean) => {
83
+ const key = button.dataset.day ?? "";
84
+ for (const b of dayButtons) {
85
+ b.setAttribute("aria-pressed", b === button ? "true" : "false");
86
+ b.tabIndex = b === button ? 0 : -1;
87
+ }
88
+ if (focus) button.focus();
89
+ let keep = false;
90
+ for (const group of groups) {
91
+ const mine = group.dataset.times === key;
92
+ group.hidden = !mine;
93
+ if (mine) keep = radios(group).some((r) => r.dataset.occurrence === select.value);
94
+ }
95
+ if (hint) hint.hidden = true;
96
+ if (!keep) {
97
+ for (const group of groups) for (const r of radios(group)) r.setAttribute("aria-checked", "false");
98
+ setSelect("");
99
+ }
100
+ };
101
+
102
+ for (const button of dayButtons) {
103
+ button.addEventListener("click", () => showDay(button, false));
104
+ button.addEventListener("keydown", (event) => {
105
+ const days = dayButtons.map((b) => Number(b.dataset.n));
106
+ const to = stepDay(days, Number(button.dataset.n), event.key, isRtl(picker));
107
+ if (to === null) return;
108
+ event.preventDefault();
109
+ const target = dayButtons.find((b) => Number(b.dataset.n) === to);
110
+ if (target) {
111
+ for (const b of dayButtons) b.tabIndex = b === target ? 0 : -1;
112
+ target.focus();
113
+ }
114
+ });
115
+ }
116
+ for (const group of groups) {
117
+ const list = radios(group);
118
+ for (const [i, radio] of list.entries()) {
119
+ radio.addEventListener("click", () => chooseTime(radio, false));
120
+ radio.addEventListener("keydown", (event) => {
121
+ const to = stepRadio(list.map(isOpen), i, event.key, isRtl(picker));
122
+ if (to === null) return;
123
+ event.preventDefault();
124
+ const target = list[to];
125
+ if (target) chooseTime(target, true);
126
+ });
127
+ }
128
+ }
129
+
130
+ // A value the browser kept (back/forward, a failed submit): show its day and time.
131
+ const kept =
132
+ select.value && picker.querySelector<HTMLButtonElement>(`[data-occurrence="${CSS.escape(select.value)}"]`);
133
+ const keptDay =
134
+ kept && dayButtons.find((b) => b.dataset.day === kept.closest<HTMLElement>("[data-times]")?.dataset.times);
135
+ if (kept && keptDay) {
136
+ showDay(keptDay, false);
137
+ chooseTime(kept, false);
138
+ }
139
+ }
140
+
141
+ if (typeof document !== "undefined") {
142
+ for (const picker of document.querySelectorAll<HTMLElement>("[data-picker]")) enhancePicker(picker);
143
+ }