@wix/himalaya-cli 0.1952.0 → 0.1954.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.
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/auth-providers/wix/src/index.d.ts +5 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-auth.mjs +2 -1
- package/dist/cli.mjs +88 -27
- package/guides/one-app-section-mappings.md +3 -3
- package/guides/one-app-to-himi-app.md +3 -3
- package/package.json +2 -2
- package/templates/bare-fashion/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/beauty-salon/tier5-src/_shared/agenda-calendar.ts +95 -0
- package/templates/beauty-salon/tier5-src/_shared/booking-session.ts +10 -0
- package/templates/beauty-salon/tier5-src/_shared/class-sessions.ts +113 -0
- package/templates/beauty-salon/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/beauty-salon/tier5-src/himi-branded-lite-agenda/index.ts +13 -146
- package/templates/beauty-salon-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/beauty-salon-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/branded-lite/l10n/ar.json +5 -0
- package/templates/branded-lite/l10n/cs.json +5 -0
- package/templates/branded-lite/l10n/da.json +5 -0
- package/templates/branded-lite/l10n/de.json +5 -0
- package/templates/branded-lite/l10n/el.json +5 -0
- package/templates/branded-lite/l10n/es.json +5 -0
- package/templates/branded-lite/l10n/fi.json +5 -0
- package/templates/branded-lite/l10n/fr.json +5 -0
- package/templates/branded-lite/l10n/he.json +4 -0
- package/templates/branded-lite/l10n/hu.json +5 -0
- package/templates/branded-lite/l10n/id.json +5 -0
- package/templates/branded-lite/l10n/it.json +5 -0
- package/templates/branded-lite/l10n/ja.json +5 -0
- package/templates/branded-lite/l10n/ko.json +5 -0
- package/templates/branded-lite/l10n/lt.json +5 -0
- package/templates/branded-lite/l10n/nl.json +5 -0
- package/templates/branded-lite/l10n/no.json +5 -0
- package/templates/branded-lite/l10n/pl.json +5 -0
- package/templates/branded-lite/l10n/pt.json +5 -0
- package/templates/branded-lite/l10n/ru.json +5 -0
- package/templates/branded-lite/l10n/sv.json +5 -0
- package/templates/branded-lite/l10n/th.json +5 -0
- package/templates/branded-lite/l10n/tr.json +5 -0
- package/templates/branded-lite/l10n/uk.json +5 -0
- package/templates/branded-lite/l10n/vi.json +5 -0
- package/templates/branded-lite/l10n/zh.json +5 -0
- package/templates/branded-lite/recipes/class-calendar.json +707 -0
- package/templates/branded-lite/recipes/upcoming-sessions.json +280 -0
- package/templates/branded-lite/tier5-src/_shared/agenda-calendar.ts +95 -0
- package/templates/branded-lite/tier5-src/_shared/booking-session.ts +10 -0
- package/templates/branded-lite/tier5-src/_shared/class-calendar-section.ts +280 -0
- package/templates/branded-lite/tier5-src/_shared/class-sessions.ts +113 -0
- package/templates/branded-lite/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/branded-lite/tier5-src/_shared/upcoming-sessions-section.ts +121 -0
- package/templates/branded-lite/tier5-src/himi-branded-lite-agenda/index.ts +13 -146
- package/templates/brandy/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/community-club/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/community-club-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/community-club-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/conference/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/events-meetups/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/events-meetups-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/events-meetups-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/fitness-gym/tier5-src/_shared/agenda-calendar.ts +95 -0
- package/templates/fitness-gym/tier5-src/_shared/booking-session.ts +10 -0
- package/templates/fitness-gym/tier5-src/_shared/class-sessions.ts +113 -0
- package/templates/fitness-gym/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/fitness-gym/tier5-src/himi-branded-lite-agenda/index.ts +13 -146
- package/templates/gym-fitness/tier5-src/_shared/agenda-calendar.ts +95 -0
- package/templates/gym-fitness/tier5-src/_shared/booking-session.ts +10 -0
- package/templates/gym-fitness/tier5-src/_shared/class-sessions.ts +113 -0
- package/templates/gym-fitness/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/gym-fitness/tier5-src/himi-branded-lite-agenda/index.ts +13 -146
- package/templates/gym-fitness-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/gym-fitness-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/medical-services/tier5-src/_shared/booking-session.ts +10 -0
- package/templates/medical-services/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/nonprofit-cause/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/nonprofit-cause-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/nonprofit-cause-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/owner-lite/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/owner-lite/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/personal-fitness-trainer/tier5-src/_shared/agenda-calendar.ts +95 -0
- package/templates/personal-fitness-trainer/tier5-src/_shared/booking-session.ts +10 -0
- package/templates/personal-fitness-trainer/tier5-src/_shared/class-sessions.ts +113 -0
- package/templates/personal-fitness-trainer/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/personal-fitness-trainer/tier5-src/himi-branded-lite-agenda/index.ts +13 -146
- package/templates/podcast-creator/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/podcast-creator-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/podcast-creator-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/portfolio-creative/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/portfolio-creative-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/portfolio-creative-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/professional-services/tier5-src/_shared/booking-session.ts +10 -0
- package/templates/professional-services/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/restaurant/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/restaurant-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/restaurant-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/retail-store/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/retail-store-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/retail-store-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
- package/templates/salon-spa/tier5-src/_shared/agenda-calendar.ts +95 -0
- package/templates/salon-spa/tier5-src/_shared/booking-session.ts +10 -0
- package/templates/salon-spa/tier5-src/_shared/class-sessions.ts +113 -0
- package/templates/salon-spa/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/salon-spa/tier5-src/himi-branded-lite-agenda/index.ts +13 -146
- package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/yoga-studio/tier5-src/_shared/agenda-calendar.ts +95 -0
- package/templates/yoga-studio/tier5-src/_shared/booking-session.ts +10 -0
- package/templates/yoga-studio/tier5-src/_shared/class-sessions.ts +113 -0
- package/templates/yoga-studio/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/yoga-studio/tier5-src/himi-branded-lite-agenda/index.ts +13 -146
- package/templates/yoga-studio-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/yoga-studio-owner/tier5-src/_shared/owner-selected-site.ts +13 -0
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// A page's class calendar section as a registrable service: the Bookings Agenda's week strip and sessions inline on a page
|
|
2
|
+
// (the One App's `bookings_agenda_section`). The calendar pages week by week (or opens into the month), dots every day with a
|
|
3
|
+
// session and dims the days already gone, by the Agenda's own rules (`agenda-calendar.ts`). Under it, filter chips (All,
|
|
4
|
+
// the member's own Booked sessions, then each class), and the sessions of the selected day, or of the next day that has one,
|
|
5
|
+
// under that day's title. Each row is the Agenda row: time and length, the class, its coach, spots and place, and ONE control
|
|
6
|
+
// the member can use (`sessionControl` in booking-session.ts): Book (the Choose Time screen, on this session), View Course,
|
|
7
|
+
// Join Waitlist (the service screen, which owns the waitlist), the member's own place (Booked / On waitlist), or why there is
|
|
8
|
+
// none (Full, Not open yet, Closed). Booking, waitlist and cancel stay on the screens that own them; the section reads.
|
|
9
|
+
// limit -> at most N sessions of the day shown (the Agenda, one See All away, lists every one).
|
|
10
|
+
// A page worker registers it under a service name; the descriptor binds `$service:<serviceName>.*` (recipe class-calendar.json).
|
|
11
|
+
import { defineService } from "@himalaya/state";
|
|
12
|
+
import { addDays, dayKey, timeLabel, weekOf, type DayDecoration, type Weekday } from "@himalaya/time";
|
|
13
|
+
import { hostSessionFromGlobal } from "@himalaya/iap";
|
|
14
|
+
import type { WixService } from "@himalaya/wix-bookings";
|
|
15
|
+
import { copyParam, copyTemplate, stashCopy } from "./himi-copy.js";
|
|
16
|
+
import { formatWeekdayMonthDayLong } from "./engine-intl.js";
|
|
17
|
+
import { decorationsOf, keepsSelection, monthGridOf, selectionForRange, titledDays, windowFor } from "./agenda-calendar.js";
|
|
18
|
+
import { lengthLabel, placesIn, sessionControl, spotsLabel, type MemberPlace, type Session } from "./booking-session.js";
|
|
19
|
+
import { orderedSessions, readClassServices, readClassSessions } from "./class-sessions.js";
|
|
20
|
+
import type { MemberAccess } from "./member-access.js";
|
|
21
|
+
|
|
22
|
+
export interface ClassCalendarOptions {
|
|
23
|
+
/** Show at most this many sessions of the day shown. */
|
|
24
|
+
limit: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ClassCalendarRow {
|
|
28
|
+
id: string; title: string;
|
|
29
|
+
serviceId: string; sessionId: string; start: string;
|
|
30
|
+
/** "6:00 PM", and the length under it: "40 min". */
|
|
31
|
+
time: string; length: string;
|
|
32
|
+
/** "With Dana", "" when the session names no staff member. */
|
|
33
|
+
coach: string; noCoach: boolean;
|
|
34
|
+
/** "4 spots left" or "Full", "" when the site reports no capacity (and for a course). */
|
|
35
|
+
spots: string; noSpots: boolean;
|
|
36
|
+
place: string; noPlace: boolean;
|
|
37
|
+
/** A course session: tagged, and its control is View Course (a course is booked whole). */
|
|
38
|
+
notCourse: boolean;
|
|
39
|
+
// Exactly one control shows: the flags hide the others.
|
|
40
|
+
hideBook: boolean; hideWaitlist: boolean; hideCourse: boolean; hideBooked: boolean; hideOnWaitlist: boolean; hideClosed: boolean;
|
|
41
|
+
closedLabel: string;
|
|
42
|
+
/** "Join Waitlist": the one control label the scaffold's catalog has no key for, so the module's copy names it. */
|
|
43
|
+
waitlistLabel: string;
|
|
44
|
+
detailsA11y: string; bookA11y: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ClassCalendarFilter { id: string; label: string }
|
|
48
|
+
|
|
49
|
+
export interface ClassCalendarState {
|
|
50
|
+
status: "loading" | "ready" | "error";
|
|
51
|
+
today: string; selectedDate: string; rangeStart: string; rangeEnd: string;
|
|
52
|
+
decorations: DayDecoration[];
|
|
53
|
+
/** The day the rows are on: the selected day, or the next one with a session ("" with none). */
|
|
54
|
+
dayTitle: string; noDayTitle: boolean;
|
|
55
|
+
rows: ClassCalendarRow[];
|
|
56
|
+
/** "" (All), "booked" (the member's own sessions) or a class's service id. */
|
|
57
|
+
filterId: string;
|
|
58
|
+
filters: ClassCalendarFilter[];
|
|
59
|
+
/** The chips are hidden until there is something to filter by: an option besides All. */
|
|
60
|
+
hideFilters: boolean;
|
|
61
|
+
emptyText: string;
|
|
62
|
+
notLoading: boolean; notErrored: boolean; noRows: boolean; noEmpty: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The longest run of days one read covers: a far page replaces the loaded days rather than growing them. */
|
|
66
|
+
const MAX_DAYS = 120;
|
|
67
|
+
const DAY_MS = 86_400_000;
|
|
68
|
+
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
69
|
+
|
|
70
|
+
export function calendarRow(s: Session, place: MemberPlace | undefined): ClassCalendarRow {
|
|
71
|
+
const { control, closedLabel } = sessionControl(s, place);
|
|
72
|
+
const time = timeLabel(s.start);
|
|
73
|
+
const spots = spotsLabel(s);
|
|
74
|
+
const coach = s.staff ? copyTemplate("service.staffOne", "With {name}", { name: s.staff }) : "";
|
|
75
|
+
return {
|
|
76
|
+
id: s.key, title: s.title, serviceId: s.serviceId, sessionId: s.sessionId, start: s.start,
|
|
77
|
+
time, length: lengthLabel(s.start, s.end),
|
|
78
|
+
coach, noCoach: !coach, spots, noSpots: !spots, place: s.location, noPlace: !s.location,
|
|
79
|
+
notCourse: s.kind !== "course",
|
|
80
|
+
hideBook: control !== "book", hideWaitlist: control !== "waitlist", hideCourse: control !== "course",
|
|
81
|
+
hideBooked: control !== "booked", hideOnWaitlist: control !== "waitlisted", hideClosed: control !== "closed",
|
|
82
|
+
closedLabel,
|
|
83
|
+
waitlistLabel: copyParam("agenda.waitlistCta", "Join Waitlist"),
|
|
84
|
+
detailsA11y: s.staff
|
|
85
|
+
? copyTemplate("agenda.detailsA11y", "{title}, {time}, with {staff}", { title: s.title, time, staff: s.staff })
|
|
86
|
+
: [s.title, time].filter(Boolean).join(", "),
|
|
87
|
+
bookA11y: copyTemplate("agenda.bookA11y", "Book {title}, {time}", { title: s.title, time }),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const argOf = (p: unknown, key: string): string => {
|
|
92
|
+
const a = p as Record<string, unknown> | undefined;
|
|
93
|
+
const v = a?.[key] ?? (a?.args as Record<string, unknown> | undefined)?.[key] ?? (a?.params as Record<string, unknown> | undefined)?.[key];
|
|
94
|
+
return typeof v === "string" ? v.trim() : typeof v === "number" && Number.isFinite(v) ? String(v) : "";
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const filterOf = (p: unknown): string => {
|
|
98
|
+
const picked = p as { selectedIds?: unknown; selectedId?: unknown; id?: unknown } | undefined;
|
|
99
|
+
const raw = Array.isArray(picked?.selectedIds) ? picked.selectedIds[0] : picked?.selectedId ?? picked?.id;
|
|
100
|
+
return typeof raw === "string" ? raw : "";
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
export function registerClassCalendarSection(serviceName: string, options: ClassCalendarOptions) {
|
|
104
|
+
type View = Pick<ClassCalendarState, "today" | "selectedDate" | "rangeStart" | "rangeEnd">;
|
|
105
|
+
let view: View = { today: "", selectedDate: "", rangeStart: "", rangeEnd: "" };
|
|
106
|
+
let services: WixService[] | undefined;
|
|
107
|
+
let sessions: Session[] = [];
|
|
108
|
+
let places = new Map<string, MemberPlace>();
|
|
109
|
+
let member: MemberAccess | undefined;
|
|
110
|
+
let loaded = { start: "", end: "" };
|
|
111
|
+
let filterId = "";
|
|
112
|
+
/** The calendar's first weekday (load param `firstWeekday`, 0 = Sunday), so a month grid is the one it draws. */
|
|
113
|
+
let firstWeekday: Weekday = 0;
|
|
114
|
+
let status: ClassCalendarState["status"] = "loading";
|
|
115
|
+
// Only the newest read may answer: a page the member left must not paint over the one they are on.
|
|
116
|
+
let sequence = 0;
|
|
117
|
+
/** A forced read (the section appeared again, the member changed) has not committed yet: the places on screen are from before
|
|
118
|
+
* it, so a read that overtakes it is forced too, whatever it was asked for, and brings the member's current places. */
|
|
119
|
+
let forcePending = false;
|
|
120
|
+
|
|
121
|
+
const derive = (): ClassCalendarState => {
|
|
122
|
+
const signedIn = !!member?.email;
|
|
123
|
+
// A member's "Booked" choice does not survive a sign-out; a class that left the catalog is no choice either.
|
|
124
|
+
if ((filterId === "booked" && !signedIn) || (filterId && filterId !== "booked" && !(services ?? []).some((svc) => svc.id === filterId))) filterId = "";
|
|
125
|
+
const mine = (x: Session) => { const p = places.get(x.key)?.place; return p === "booked" || p === "waitlisted"; };
|
|
126
|
+
const shown = sessions.filter((x) => x.day >= view.today && (!filterId || (filterId === "booked" ? mine(x) : x.serviceId === filterId)));
|
|
127
|
+
const day = shown.find((x) => x.day >= view.selectedDate)?.day ?? "";
|
|
128
|
+
// A selected day with no session moves to the next day that has one ON THE SAME PAGE, so the calendar and the rows name the
|
|
129
|
+
// same day (the Agenda's rule). Never off the page: that would page the calendar away under the member's finger.
|
|
130
|
+
if (status === "ready" && day && day > view.selectedDate && day <= titledDays(view.rangeStart, view.rangeEnd).last) view = { ...view, selectedDate: day };
|
|
131
|
+
const rows = day ? shown.filter((x) => x.day === day).slice(0, options.limit).map((x) => calendarRow(x, places.get(x.key))) : [];
|
|
132
|
+
const classes = [...new Map((services ?? []).map((svc) => [svc.id, svc.name?.trim() || ""] as const)).entries()].filter(([, name]) => !!name);
|
|
133
|
+
const filters: ClassCalendarFilter[] = [
|
|
134
|
+
{ id: "", label: copyParam("collection.all", "All") },
|
|
135
|
+
...(signedIn ? [{ id: "booked", label: copyParam("agenda.bookedLabel", "Booked") }] : []),
|
|
136
|
+
...classes.map(([id, label]) => ({ id, label })),
|
|
137
|
+
];
|
|
138
|
+
const ready = status === "ready";
|
|
139
|
+
const empty = ready && !rows.length;
|
|
140
|
+
const date = day ? new Date(`${day}T12:00:00`) : undefined;
|
|
141
|
+
const dayTitle = date ? formatWeekdayMonthDayLong(date) : "";
|
|
142
|
+
return {
|
|
143
|
+
status, ...view,
|
|
144
|
+
decorations: ready ? decorationsOf(shown, view.today, view.rangeStart, view.rangeEnd) : [],
|
|
145
|
+
dayTitle, noDayTitle: !dayTitle,
|
|
146
|
+
rows, filterId, filters, hideFilters: !ready || filters.length < 2,
|
|
147
|
+
emptyText: !empty ? "" : (services ?? []).length === 0
|
|
148
|
+
? copyParam("agenda.noClassesText", "There are no classes on the schedule yet.")
|
|
149
|
+
: copyParam("agenda.emptyText", "There are no classes for 4 weeks from this day."),
|
|
150
|
+
notLoading: status !== "loading", notErrored: status !== "error", noRows: !rows.length, noEmpty: !empty,
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const covers = (need: { start: string; end: string }) => !!loaded.start && loaded.start <= need.start && loaded.end >= need.end;
|
|
155
|
+
|
|
156
|
+
/** Read what the current view needs (all of it with `force`: the page appeared again, the member may have booked). */
|
|
157
|
+
const ensure = async (force = false): Promise<ClassCalendarState | undefined> => {
|
|
158
|
+
force ||= forcePending;
|
|
159
|
+
const need = windowFor(view.today, view.rangeStart, view.rangeEnd, view.selectedDate);
|
|
160
|
+
if (!force && covers(need)) return derive();
|
|
161
|
+
const seq = ++sequence;
|
|
162
|
+
if (force) forcePending = true;
|
|
163
|
+
// Grow the loaded days when the new ones touch them (the member paged on); a far page reads its own days.
|
|
164
|
+
const touches = !force && !!loaded.start && need.start <= dayKey(addDays(loaded.end, 1)) && need.end >= dayKey(addDays(loaded.start, -1));
|
|
165
|
+
const union = { start: need.start < loaded.start ? need.start : loaded.start, end: need.end > loaded.end ? need.end : loaded.end };
|
|
166
|
+
const grown = touches && Math.round((Date.parse(union.end) - Date.parse(union.start)) / DAY_MS) <= MAX_DAYS;
|
|
167
|
+
const win = grown ? union : need;
|
|
168
|
+
// A grown window reads only the days it adds, as the Agenda's loader does; a forced or far read reads the whole window.
|
|
169
|
+
const parts = grown
|
|
170
|
+
? [
|
|
171
|
+
...(win.start < loaded.start ? [{ start: win.start, end: dayKey(addDays(loaded.start, -1)) }] : []),
|
|
172
|
+
...(win.end > loaded.end ? [{ start: dayKey(addDays(loaded.end, 1)), end: win.end }] : []),
|
|
173
|
+
]
|
|
174
|
+
: [win];
|
|
175
|
+
try {
|
|
176
|
+
if (force || !services) services = await readClassServices({ share: true });
|
|
177
|
+
const list = services;
|
|
178
|
+
const reads = await Promise.all(parts.map(async (part) => {
|
|
179
|
+
const inPart = await readClassSessions(list, part.start, part.end, { share: true });
|
|
180
|
+
return { inPart, ...(await placesIn(part.start, part.end, inPart)) };
|
|
181
|
+
}));
|
|
182
|
+
if (seq !== sequence) return undefined;
|
|
183
|
+
// The new days were read for another member than the loaded ones (a sign-in or out while paging): never mix two members'
|
|
184
|
+
// places, read the whole window for whoever is signed in now.
|
|
185
|
+
if (grown && reads.some((r) => (r.who?.email ?? "") !== (member?.email ?? ""))) return ensure(true);
|
|
186
|
+
// The member paged on while this read ran: commit it only if it still covers where they are now. Otherwise the days already
|
|
187
|
+
// loaded may (they paged back), unless this read was the one bringing the member's current places: then read again.
|
|
188
|
+
const now = windowFor(view.today, view.rangeStart, view.rangeEnd, view.selectedDate);
|
|
189
|
+
if (!(win.start <= now.start && win.end >= now.end)) return covers(now) && !force ? derive() : ensure(force);
|
|
190
|
+
sessions = grown ? orderedSessions([...sessions, ...reads.flatMap((r) => r.inPart)]) : reads[0]!.inPart;
|
|
191
|
+
places = grown ? new Map([...places, ...reads.flatMap((r) => [...r.found])]) : reads[0]!.found;
|
|
192
|
+
member = reads[0]?.who ?? member; loaded = win; status = "ready";
|
|
193
|
+
forcePending = false;
|
|
194
|
+
return derive();
|
|
195
|
+
} catch (error) {
|
|
196
|
+
if (seq !== sequence) return undefined;
|
|
197
|
+
forcePending = false;
|
|
198
|
+
console.warn("class_calendar_section: the schedule could not be read", error);
|
|
199
|
+
sessions = []; places = new Map(); loaded = { start: "", end: "" }; status = "error";
|
|
200
|
+
return derive();
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const initial: ClassCalendarState = {
|
|
205
|
+
status: "loading", today: "", selectedDate: "", rangeStart: "", rangeEnd: "", decorations: [], dayTitle: "", noDayTitle: true,
|
|
206
|
+
rows: [], filterId: "", filters: [], hideFilters: true, emptyText: "",
|
|
207
|
+
notLoading: false, notErrored: true, noRows: true, noEmpty: true,
|
|
208
|
+
};
|
|
209
|
+
type Actions = {
|
|
210
|
+
load: (state: ClassCalendarState, arg?: unknown) => Promise<ClassCalendarState | undefined>;
|
|
211
|
+
selectDate: (state: ClassCalendarState, arg?: unknown) => Promise<ClassCalendarState | undefined> | ClassCalendarState;
|
|
212
|
+
rangeChanged: (state: ClassCalendarState, arg?: unknown) => Promise<ClassCalendarState | undefined> | ClassCalendarState;
|
|
213
|
+
monthChanged: (state: ClassCalendarState, arg?: unknown) => Promise<ClassCalendarState | undefined> | ClassCalendarState;
|
|
214
|
+
setFilter: (state: ClassCalendarState, arg?: unknown) => ClassCalendarState;
|
|
215
|
+
retry: () => Promise<ClassCalendarState | undefined>;
|
|
216
|
+
clear: () => ClassCalendarState;
|
|
217
|
+
};
|
|
218
|
+
const service = defineService<ClassCalendarState, Actions>(serviceName, {
|
|
219
|
+
state: initial,
|
|
220
|
+
// The member's places are one member's: never written to disk and restored for the next person on the device.
|
|
221
|
+
notHydrated: Object.keys(initial) as Array<keyof ClassCalendarState>,
|
|
222
|
+
actions: {
|
|
223
|
+
load: async (_state, arg) => {
|
|
224
|
+
stashCopy(arg);
|
|
225
|
+
const today = dayKey(new Date());
|
|
226
|
+
// The calendar's first weekday comes with the section's appearance; a load without it (a sign-in elsewhere) keeps it.
|
|
227
|
+
const fw = argOf(arg, "firstWeekday");
|
|
228
|
+
if (/^[0-6]$/.test(fw)) firstWeekday = Number(fw) as Weekday;
|
|
229
|
+
// First appearance (or a new day): open on today's week. A re-appearance keeps the member's page and reads it again.
|
|
230
|
+
if (!view.today || view.today !== today) {
|
|
231
|
+
const week = weekOf(today, firstWeekday);
|
|
232
|
+
view = { today, selectedDate: today, rangeStart: week[0]!, rangeEnd: week[6]! };
|
|
233
|
+
}
|
|
234
|
+
return ensure(true);
|
|
235
|
+
},
|
|
236
|
+
retry: () => { status = "loading"; return ensure(true); },
|
|
237
|
+
// The member changed: the places (and a Booked choice) shown are the previous member's, so they go at once.
|
|
238
|
+
clear: () => { ++sequence; places = new Map(); member = undefined; filterId = ""; return derive(); },
|
|
239
|
+
selectDate: (state, arg) => {
|
|
240
|
+
const date = argOf(arg, "date");
|
|
241
|
+
// Past days are not selectable: the calendar dims them, and the section is what is still to come.
|
|
242
|
+
if (!DAY.test(date) || date === view.selectedDate || date < view.today) return state;
|
|
243
|
+
const page = titledDays(view.rangeStart, view.rangeEnd);
|
|
244
|
+
const span = Math.round((Date.parse(view.rangeEnd) - Date.parse(view.rangeStart)) / DAY_MS);
|
|
245
|
+
// A month grid's padding day belongs to the next month, and the grid moves there without reporting a page.
|
|
246
|
+
const grid = span > 7 && (date < page.first || date > page.last) ? monthGridOf(date, firstWeekday) : undefined;
|
|
247
|
+
view = { ...view, selectedDate: date, ...(grid ? { rangeStart: grid.start, rangeEnd: grid.end } : {}) };
|
|
248
|
+
return ensure();
|
|
249
|
+
},
|
|
250
|
+
rangeChanged: (state, arg) => {
|
|
251
|
+
const start = argOf(arg, "startDate"), end = argOf(arg, "endDate");
|
|
252
|
+
if (!DAY.test(start) || !DAY.test(end) || (start === view.rangeStart && end === view.rangeEnd)) return state;
|
|
253
|
+
// The selection follows the page, so the sessions under the calendar are about the days on screen.
|
|
254
|
+
const selectedDate = keepsSelection(view, start, end) ? view.selectedDate : selectionForRange(view.today, start, end, view.selectedDate);
|
|
255
|
+
view = { ...view, rangeStart: start, rangeEnd: end, selectedDate };
|
|
256
|
+
return ensure();
|
|
257
|
+
},
|
|
258
|
+
// An older binary has no week mode and reports only the month (1-12): its grid spans the month's whole weeks.
|
|
259
|
+
monthChanged: (state, arg) => {
|
|
260
|
+
const year = Number(argOf(arg, "year")), month = Number(argOf(arg, "month"));
|
|
261
|
+
if (!year || !month) return state;
|
|
262
|
+
const start = weekOf(new Date(year, month - 1, 1), firstWeekday)[0], end = weekOf(new Date(year, month, 0), firstWeekday)[6];
|
|
263
|
+
if (!start || !end || (start === view.rangeStart && end === view.rangeEnd)) return state;
|
|
264
|
+
const selectedDate = keepsSelection(view, start, end) ? view.selectedDate : selectionForRange(view.today, start, end, view.selectedDate);
|
|
265
|
+
view = { ...view, rangeStart: start, rangeEnd: end, selectedDate };
|
|
266
|
+
return ensure();
|
|
267
|
+
},
|
|
268
|
+
setFilter: (state, arg) => {
|
|
269
|
+
const next = filterOf(arg);
|
|
270
|
+
if (next === filterId || !derive().filters.some((f) => f.id === next)) return state;
|
|
271
|
+
filterId = next;
|
|
272
|
+
return derive();
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
// Signing in or out on another screen changes the member's places (and the Booked choice).
|
|
277
|
+
// Only once the section has appeared: a page worker registers its services at boot, for pages nobody has opened yet.
|
|
278
|
+
hostSessionFromGlobal().subscribe(() => { if (!view.today) return; void service.clear(); void service.load(); });
|
|
279
|
+
return service;
|
|
280
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// The site's class and course sessions, read the way the Bookings Agenda reads them: the CLASS and COURSE services (an
|
|
2
|
+
// appointment's availability is every free slot of a day, a booking grid rather than a schedule), then each service's
|
|
3
|
+
// sessions in a window. Shared by the Agenda screen and the page sections that show the same schedule inline (the class
|
|
4
|
+
// calendar and the upcoming sessions strip), so a session reads the same everywhere.
|
|
5
|
+
import { addDays, dayKey } from "@himalaya/time";
|
|
6
|
+
import { queryServiceAvailability, queryServices, type WixAvailabilityEntry, type WixService } from "@himalaya/wix-bookings";
|
|
7
|
+
import { compareText } from "./engine-intl.js";
|
|
8
|
+
import { sessionOf, type Session } from "./booking-session.js";
|
|
9
|
+
|
|
10
|
+
/** Services whose sessions are fixed events: a class's are each booked on their own, a course's are listed but the course is
|
|
11
|
+
* booked as a whole (on its service screen). */
|
|
12
|
+
const SESSION_TYPES = new Set(["CLASS", "COURSE"]);
|
|
13
|
+
|
|
14
|
+
/** How long a page's sections share one read: the sections a page shows together appear together, so the second one reuses the
|
|
15
|
+
* first one's catalog and availability instead of reading them again. Short, so a later appearance still reads fresh. */
|
|
16
|
+
export const SHARED_READ_MS = 5_000;
|
|
17
|
+
|
|
18
|
+
export interface ShareOptions {
|
|
19
|
+
/** Reuse a read another section of the page started or finished in the last SHARED_READ_MS. Off for the Agenda screen. */
|
|
20
|
+
share?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let sharedCatalog: { at: number; read: Promise<WixService[]> } | undefined;
|
|
24
|
+
|
|
25
|
+
/** Every visible class and course service of the site. Every page, not the first 100: a class past the first page would
|
|
26
|
+
* silently be missing. Bounded, so a misbehaving paging answer cannot loop forever. */
|
|
27
|
+
export async function readClassServices(options: ShareOptions = {}): Promise<WixService[]> {
|
|
28
|
+
if (!options.share) return readCatalog();
|
|
29
|
+
if (sharedCatalog && Date.now() - sharedCatalog.at < SHARED_READ_MS) return sharedCatalog.read;
|
|
30
|
+
const entry = { at: Date.now(), read: readCatalog() };
|
|
31
|
+
sharedCatalog = entry;
|
|
32
|
+
// A failed read is not shared: the next section reads again.
|
|
33
|
+
entry.read.catch(() => { if (sharedCatalog === entry) sharedCatalog = undefined; });
|
|
34
|
+
return entry.read;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function readCatalog(): Promise<WixService[]> {
|
|
38
|
+
const all: WixService[] = [];
|
|
39
|
+
for (let page = 0; page < 10; page++) {
|
|
40
|
+
const res = await queryServices({ query: { paging: { limit: 100, offset: page * 100 } } } as never);
|
|
41
|
+
const batch = res.services ?? [];
|
|
42
|
+
all.push(...batch);
|
|
43
|
+
if (batch.length < 100) break;
|
|
44
|
+
}
|
|
45
|
+
return all.filter((svc) => {
|
|
46
|
+
const raw = svc as WixService & { type?: string; hidden?: boolean };
|
|
47
|
+
return !!svc.id && SESSION_TYPES.has((raw.type ?? "").toUpperCase()) && raw.hidden !== true;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Sessions once each, by start then title: the order every schedule lists them in. */
|
|
52
|
+
export function orderedSessions(list: Session[]): Session[] {
|
|
53
|
+
const seen = new Set<string>();
|
|
54
|
+
return list
|
|
55
|
+
.filter((s) => (seen.has(s.key) ? false : (seen.add(s.key), true)))
|
|
56
|
+
.sort((a, b) => Date.parse(a.start) - Date.parse(b.start) || compareText(a.title, b.title));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Every session of `services` from the start of local day `start` through the end of local day `end`. Each service is its own
|
|
60
|
+
* call (the proven single-service availability query), so one service failing (a draft, a removed schedule) costs its own
|
|
61
|
+
* sessions, never the whole schedule; every service failing fails the read. */
|
|
62
|
+
export async function readClassSessions(services: readonly WixService[], start: string, end: string, options: ShareOptions = {}): Promise<Session[]> {
|
|
63
|
+
const read = options.share ? sharedAvailability : availability;
|
|
64
|
+
const settled = await Promise.allSettled(services.map((svc) => read(svc.id, start, end)));
|
|
65
|
+
const failures = settled.filter((r) => r.status === "rejected").length;
|
|
66
|
+
if (services.length && failures === services.length) throw (settled[0] as PromiseRejectedResult).reason;
|
|
67
|
+
const out: Session[] = [];
|
|
68
|
+
settled.forEach((r, i) => {
|
|
69
|
+
if (r.status !== "fulfilled") return;
|
|
70
|
+
for (const entry of r.value) {
|
|
71
|
+
const session = sessionOf(entry, services[i]!);
|
|
72
|
+
// A shared read may span more days than asked for: only the asked days are this read's.
|
|
73
|
+
if (session && session.day >= start && session.day <= end) out.push(session);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
return orderedSessions(out);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One service's availability from the start of local day `start` through the end of local day `end`. */
|
|
80
|
+
async function availability(serviceId: string, start: string, end: string): Promise<WixAvailabilityEntry[]> {
|
|
81
|
+
const from = new Date(`${start}T00:00:00`).toISOString();
|
|
82
|
+
const to = new Date(`${dayKey(addDays(end, 1))}T00:00:00`).toISOString();
|
|
83
|
+
return (await queryServiceAvailability(serviceId, from, to, { bookable: false })).availabilityEntries ?? [];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface Segment { start: string; end: string; at: number; read: Promise<WixAvailabilityEntry[]> }
|
|
87
|
+
const segments = new Map<string, Segment[]>();
|
|
88
|
+
|
|
89
|
+
/** `availability`, reusing the days another section of the page read in the last SHARED_READ_MS: only the days no recent read
|
|
90
|
+
* covers are fetched (the class calendar's weeks and the upcoming strip's month overlap almost entirely). */
|
|
91
|
+
async function sharedAvailability(serviceId: string, start: string, end: string): Promise<WixAvailabilityEntry[]> {
|
|
92
|
+
const now = Date.now();
|
|
93
|
+
const fresh = (segments.get(serviceId) ?? []).filter((x) => now - x.at < SHARED_READ_MS).sort((a, b) => (a.start < b.start ? -1 : 1));
|
|
94
|
+
const parts: Segment[] = [];
|
|
95
|
+
let day = start;
|
|
96
|
+
for (const x of fresh) {
|
|
97
|
+
if (day > end) break;
|
|
98
|
+
if (x.end < day || x.start > end) continue;
|
|
99
|
+
if (x.start > day) parts.push(fetchSegment(serviceId, day, dayKey(addDays(x.start, -1)), now));
|
|
100
|
+
parts.push(x);
|
|
101
|
+
day = dayKey(addDays(x.end, 1));
|
|
102
|
+
}
|
|
103
|
+
if (day <= end) parts.push(fetchSegment(serviceId, day, end, now));
|
|
104
|
+
segments.set(serviceId, [...fresh, ...parts.filter((x) => !fresh.includes(x))]);
|
|
105
|
+
return (await Promise.all(parts.map((x) => x.read))).flat();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function fetchSegment(serviceId: string, start: string, end: string, at: number): Segment {
|
|
109
|
+
const segment: Segment = { start, end, at, read: availability(serviceId, start, end) };
|
|
110
|
+
// A failed read is not shared: the next section reads those days again.
|
|
111
|
+
segment.read.catch(() => { segments.set(serviceId, (segments.get(serviceId) ?? []).filter((x) => x !== segment)); });
|
|
112
|
+
return segment;
|
|
113
|
+
}
|
|
@@ -118,6 +118,12 @@ export function formatDateMedium(date: Date, locale = appLocale(), timeZone?: st
|
|
|
118
118
|
return `${MONTHS_SHORT[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
+
/** `{ month: "short" }` — "Dec": a date block's month, under its day number. */
|
|
122
|
+
export function formatMonthShort(date: Date, locale = appLocale(), timeZone?: string): string {
|
|
123
|
+
if (hasIntl()) return dateFormat(locale, { month: "short" }, timeZone).format(date);
|
|
124
|
+
return MONTHS_SHORT[date.getMonth()]!;
|
|
125
|
+
}
|
|
126
|
+
|
|
121
127
|
/** `{ month: "short", year: "numeric" }` — "Jul 2026", without parsing a localized day.
|
|
122
128
|
* Like the other date helpers, an engine without Intl keeps the documented en-US fallback. */
|
|
123
129
|
export function formatMonthYear(date: Date, locale = "en-US", timeZone?: string): string {
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// A page's upcoming sessions section as a registrable service: the business's next class and course sessions (the One App's
|
|
2
|
+
// `platform_general_upcoming_section`, the Bookings member widget), read as the Agenda reads them (`class-sessions.ts`). Everyone
|
|
3
|
+
// sees the schedule; a signed-in member also sees their own place in it (Booked, On waitlist), from the same member-scoped read
|
|
4
|
+
// as the Agenda (`placesIn`). Each row is a date block, the class, the day and local times, and its coach; a tap opens the class
|
|
5
|
+
// on that session.
|
|
6
|
+
// limit -> at most N sessions (the source strip shows 3; View All, the source's CTA, always opens the Agenda),
|
|
7
|
+
// interval -> the source's time window from now: "day" (the rest of today), "week" (7 days) or "month" (a calendar month ahead).
|
|
8
|
+
// A page worker registers it under a service name; the descriptor binds `$service:<serviceName>.*` (recipe upcoming-sessions.json).
|
|
9
|
+
import { defineService } from "@himalaya/state";
|
|
10
|
+
import { addDays, dayKey } from "@himalaya/time";
|
|
11
|
+
import { hostSessionFromGlobal } from "@himalaya/iap";
|
|
12
|
+
import { copyParam, copyTemplate, stashCopy } from "./himi-copy.js";
|
|
13
|
+
import { appLocale } from "./app-locale.js";
|
|
14
|
+
import { formatClock, formatClockRange, formatMonthShort, formatWeekdayShort } from "./engine-intl.js";
|
|
15
|
+
import { placesIn, type MemberPlace, type Session } from "./booking-session.js";
|
|
16
|
+
import { readClassServices, readClassSessions } from "./class-sessions.js";
|
|
17
|
+
|
|
18
|
+
export type UpcomingSessionsInterval = "day" | "week" | "month";
|
|
19
|
+
|
|
20
|
+
export interface UpcomingSessionsOptions {
|
|
21
|
+
/** Show at most this many sessions. */
|
|
22
|
+
limit: number;
|
|
23
|
+
/** The source's time window from now. Default: "month". */
|
|
24
|
+
interval?: UpcomingSessionsInterval;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface UpcomingSessionRow {
|
|
28
|
+
id: string; title: string;
|
|
29
|
+
serviceId: string; sessionId: string; start: string;
|
|
30
|
+
/** The date block: "9" over "DEC". */
|
|
31
|
+
dayNumber: string; month: string;
|
|
32
|
+
/** "Wed, 6:00 PM – 6:40 PM", in the device's time zone. */
|
|
33
|
+
when: string;
|
|
34
|
+
/** "With Dana", "" when the session names no staff member. */
|
|
35
|
+
coach: string; noCoach: boolean;
|
|
36
|
+
/** The member's own place: "Booked" or "On waitlist", "" (and no badge) otherwise. */
|
|
37
|
+
place: string; noPlace: boolean;
|
|
38
|
+
a11y: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface UpcomingSessionsState {
|
|
42
|
+
status: "loading" | "ready" | "error";
|
|
43
|
+
rows: UpcomingSessionRow[];
|
|
44
|
+
emptyText: string;
|
|
45
|
+
notLoading: boolean; notErrored: boolean; noRows: boolean; noEmpty: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The date block's month, short and in capitals as the source draws it: "DEC". */
|
|
49
|
+
const monthShort = (date: Date): string => formatMonthShort(date).replace(/\.$/, "").toLocaleUpperCase(appLocale());
|
|
50
|
+
|
|
51
|
+
/** The last local day of the window that starts today. */
|
|
52
|
+
export function windowEnd(today: string, interval: UpcomingSessionsInterval): string {
|
|
53
|
+
if (interval === "day") return today;
|
|
54
|
+
if (interval === "week") return dayKey(addDays(today, 6));
|
|
55
|
+
const [y, m, d] = today.split("-").map(Number) as [number, number, number];
|
|
56
|
+
// The same day next month, or that month's last day (Jan 31 → Feb 28), then the day before it: a month of days.
|
|
57
|
+
const next = new Date(y, m, Math.min(d, new Date(y, m + 1, 0).getDate()));
|
|
58
|
+
return dayKey(addDays(next, -1));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function upcomingRow(s: Session, place: MemberPlace | undefined): UpcomingSessionRow {
|
|
62
|
+
const start = new Date(s.start), end = new Date(s.end);
|
|
63
|
+
const range = Date.parse(s.end) > Date.parse(s.start) ? formatClockRange(start, end) : formatClock(start);
|
|
64
|
+
const when = [formatWeekdayShort(start), range].filter(Boolean).join(", ");
|
|
65
|
+
const coach = s.staff ? copyTemplate("service.staffOne", "With {name}", { name: s.staff }) : "";
|
|
66
|
+
const label = place?.place === "booked" ? copyParam("agenda.bookedLabel", "Booked")
|
|
67
|
+
: place?.place === "waitlisted" ? copyParam("agenda.onWaitlistLabel", "On waitlist") : "";
|
|
68
|
+
return {
|
|
69
|
+
id: s.key, title: s.title, serviceId: s.serviceId, sessionId: s.sessionId, start: s.start,
|
|
70
|
+
dayNumber: String(start.getDate()), month: monthShort(start), when, coach, noCoach: !coach,
|
|
71
|
+
place: label, noPlace: !label,
|
|
72
|
+
a11y: [s.title, when, coach, label].filter(Boolean).join(", "),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function registerUpcomingSessionsSection(serviceName: string, options: UpcomingSessionsOptions) {
|
|
77
|
+
const interval: UpcomingSessionsInterval = options.interval === "day" || options.interval === "week" ? options.interval : "month";
|
|
78
|
+
const view = (status: UpcomingSessionsState["status"], rows: UpcomingSessionRow[]): UpcomingSessionsState => ({
|
|
79
|
+
status, rows,
|
|
80
|
+
emptyText: status === "ready" && !rows.length ? copyParam("upcomingSessions.emptyText", "There are no upcoming sessions.") : "",
|
|
81
|
+
notLoading: status !== "loading", notErrored: status !== "error",
|
|
82
|
+
noRows: !rows.length, noEmpty: !(status === "ready" && !rows.length),
|
|
83
|
+
});
|
|
84
|
+
// Only the newest load may answer: a guest read that finishes after the member signed in must not overwrite the member's places.
|
|
85
|
+
let sequence = 0;
|
|
86
|
+
const initial = view("loading", []);
|
|
87
|
+
/** The section appeared (its first load ran): only then does a sign-in or sign-out read it again. */
|
|
88
|
+
let appeared = false;
|
|
89
|
+
const service = defineService<UpcomingSessionsState, { load: (state: UpcomingSessionsState, arg?: unknown) => Promise<UpcomingSessionsState | undefined>; clear: () => UpcomingSessionsState }>(serviceName, {
|
|
90
|
+
state: initial,
|
|
91
|
+
// The Booked badges are one member's: never written to disk and restored for the next person on the device.
|
|
92
|
+
notHydrated: Object.keys(initial) as Array<keyof UpcomingSessionsState>,
|
|
93
|
+
actions: {
|
|
94
|
+
// The member changed: the badges shown are the previous member's, so they go at once.
|
|
95
|
+
clear: () => { ++sequence; return initial; },
|
|
96
|
+
load: async (_state, arg) => {
|
|
97
|
+
stashCopy(arg);
|
|
98
|
+
appeared = true;
|
|
99
|
+
const seq = ++sequence;
|
|
100
|
+
try {
|
|
101
|
+
const now = Date.now();
|
|
102
|
+
const today = dayKey(new Date(now));
|
|
103
|
+
const end = windowEnd(today, interval);
|
|
104
|
+
// Still to come: a session that already started is not upcoming. Only the shown sessions need the member's places.
|
|
105
|
+
const shown = (await readClassSessions(await readClassServices({ share: true }), today, end, { share: true })).filter((s) => Date.parse(s.start) > now).slice(0, options.limit);
|
|
106
|
+
const { found } = await placesIn(today, end, shown);
|
|
107
|
+
if (seq !== sequence) return undefined;
|
|
108
|
+
return view("ready", shown.map((s) => upcomingRow(s, found.get(s.key))));
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (seq !== sequence) return undefined;
|
|
111
|
+
console.warn("upcoming_sessions_section: the sessions could not be read", error);
|
|
112
|
+
return view("error", []);
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
// Signing in or out on another screen changes the member's Booked badges.
|
|
118
|
+
// Only once the section has appeared: a page worker registers its services at boot, for pages nobody has opened yet.
|
|
119
|
+
hostSessionFromGlobal().subscribe(() => { if (!appeared) return; void service.clear(); void service.load(); });
|
|
120
|
+
return service;
|
|
121
|
+
}
|