@vermeulen.solutions/eventual 0.18.7 → 0.19.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,199 @@
1
+ /**
2
+ * Month grid and date formatting for the event views. Moved from the Astro showcase
3
+ * (examples/astro-events/src/lib/calendar.ts); calendar links and ICS now come from Core's feed.
4
+ */
5
+ import type { PublicEvent } from "../feed";
6
+ import { civilDate } from "../event-list";
7
+
8
+ const SUNDAY_FIRST_REGIONS = new Set(["US", "CA", "JP", "KR", "TW", "IL", "SA", "PH"]);
9
+
10
+ export interface CalendarCell {
11
+ date: string;
12
+ inMonth: boolean;
13
+ dayNumber: number;
14
+ events: PublicEvent[];
15
+ }
16
+
17
+ export function normalizeLocale(value: string | undefined): string {
18
+ try {
19
+ return Intl.getCanonicalLocales(value || "en-GB")[0] ?? "en-GB";
20
+ } catch {
21
+ return "en-GB";
22
+ }
23
+ }
24
+
25
+ export function normalizeTimeZone(value: string | undefined): string {
26
+ try {
27
+ new Intl.DateTimeFormat("en", { timeZone: value || "UTC" });
28
+ return value || "UTC";
29
+ } catch {
30
+ return "UTC";
31
+ }
32
+ }
33
+
34
+ export function isMonthKey(value: string | null | undefined): value is string {
35
+ return Boolean(value && /^\d{4}-(0[1-9]|1[0-2])$/.test(value) && Number(value.slice(0, 4)) >= 1000);
36
+ }
37
+
38
+ export function addMonths(value: string, amount: number): string {
39
+ const [year, month] = value.split("-").map(Number);
40
+ const date = new Date(Date.UTC(year!, month! - 1 + amount, 1));
41
+ return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
42
+ }
43
+
44
+ /** The month a given instant falls in, in a time zone ("2026-11"). */
45
+ export function monthOf(now: Date, timeZone: string): string {
46
+ return localDate(now.toISOString(), timeZone).slice(0, 7);
47
+ }
48
+
49
+ /** Whole weeks around a month, starting on the locale's first day of the week. */
50
+ export function calendarRange(month: string, locale: string): { from: string; through: string } {
51
+ const [year, monthNumber] = month.split("-").map(Number);
52
+ const first = new Date(Date.UTC(year!, monthNumber! - 1, 1));
53
+ const last = new Date(Date.UTC(year!, monthNumber!, 0));
54
+ const offset = (first.getUTCDay() - firstDayOfWeek(locale) + 7) % 7;
55
+ const from = new Date(Date.UTC(year!, monthNumber! - 1, 1 - offset));
56
+ const cells = Math.ceil((offset + last.getUTCDate()) / 7) * 7;
57
+ const through = new Date(from);
58
+ through.setUTCDate(through.getUTCDate() + cells - 1);
59
+ return { from: dateKey(from), through: dateKey(through) };
60
+ }
61
+
62
+ export function monthDateRange(month: string): { from: string; through: string } {
63
+ const [year, monthNumber] = month.split("-").map(Number);
64
+ const last = new Date(Date.UTC(year!, monthNumber!, 0));
65
+ return {
66
+ from: `${month}-01`,
67
+ through: `${month}-${String(last.getUTCDate()).padStart(2, "0")}`,
68
+ };
69
+ }
70
+
71
+ /** 0 = Sunday … 6 = Saturday. */
72
+ export function firstDayOfWeek(locale: string): number {
73
+ try {
74
+ const localeObject = new Intl.Locale(locale) as Intl.Locale & {
75
+ getWeekInfo?: () => { firstDay: number };
76
+ weekInfo?: { firstDay: number };
77
+ };
78
+ const firstDay = localeObject.getWeekInfo?.().firstDay ?? localeObject.weekInfo?.firstDay;
79
+ if (firstDay && firstDay >= 1 && firstDay <= 7) return firstDay % 7;
80
+ const region = localeObject.region?.toUpperCase();
81
+ if (region && SUNDAY_FIRST_REGIONS.has(region)) return 0;
82
+ } catch {
83
+ // Invalid locales use the documented Monday-first fallback.
84
+ }
85
+ return 1;
86
+ }
87
+
88
+ export function weekdayHeadings(locale: string, width: "short" | "long" = "short"): string[] {
89
+ const first = firstDayOfWeek(locale);
90
+ return Array.from({ length: 7 }, (_, index) => {
91
+ const date = new Date(Date.UTC(2023, 0, 1 + first + index));
92
+ return new Intl.DateTimeFormat(locale, { weekday: width, timeZone: "UTC" }).format(date);
93
+ });
94
+ }
95
+
96
+ export function buildCalendar(month: string, locale: string, events: PublicEvent[]): CalendarCell[][] {
97
+ const range = calendarRange(month, locale);
98
+ const [year, monthNumber] = month.split("-").map(Number);
99
+ const first = new Date(`${range.from}T00:00:00Z`);
100
+ const last = new Date(`${range.through}T00:00:00Z`);
101
+ const days = Math.round((last.getTime() - first.getTime()) / 86_400_000) + 1;
102
+ const cells: CalendarCell[] = [];
103
+ for (let index = 0; index < days; index += 1) {
104
+ const date = new Date(first);
105
+ date.setUTCDate(first.getUTCDate() + index);
106
+ const key = dateKey(date);
107
+ cells.push({
108
+ date: key,
109
+ inMonth: date.getUTCMonth() === monthNumber! - 1 && date.getUTCFullYear() === year,
110
+ dayNumber: date.getUTCDate(),
111
+ events: events.filter((event) => eventTouchesDate(event, key)),
112
+ });
113
+ }
114
+ const weeks: CalendarCell[][] = [];
115
+ for (let index = 0; index < cells.length; index += 7) weeks.push(cells.slice(index, index + 7));
116
+ return weeks;
117
+ }
118
+
119
+ export function eventTouchesDate(event: PublicEvent, date: string): boolean {
120
+ const start = eventStartDate(event);
121
+ const end = eventEndDate(event);
122
+ return Boolean(start && end && start <= date && end >= date);
123
+ }
124
+
125
+ /** The event's first and last calendar day where it takes place (all-day ends are inclusive). */
126
+ export function eventStartDate(event: PublicEvent): string {
127
+ return event.allDay ? event.start.slice(0, 10) : localDate(event.start, event.timezone);
128
+ }
129
+
130
+ export function eventEndDate(event: PublicEvent): string {
131
+ return event.allDay ? event.end.slice(0, 10) : localDate(event.end, event.timezone);
132
+ }
133
+
134
+ export function displayDate(value: string, locale: string, timeZone: string, allDay: boolean, style: "medium" | "full" = "medium"): string {
135
+ const date = allDay ? new Date(`${value.slice(0, 10)}T00:00:00Z`) : new Date(value);
136
+ try {
137
+ return new Intl.DateTimeFormat(locale, { dateStyle: style, timeZone: allDay ? "UTC" : timeZone }).format(date);
138
+ } catch {
139
+ return value.slice(0, 10);
140
+ }
141
+ }
142
+
143
+ /** "18:15–19:15 CET"; empty for all-day events. Each end shows its zone when the two differ. */
144
+ export function eventTimeRange(event: PublicEvent, locale: string): string {
145
+ if (event.allDay) return "";
146
+ try {
147
+ const time = new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit", timeZone: event.timezone });
148
+ const zoneFormat = new Intl.DateTimeFormat(locale, { timeZone: event.timezone, timeZoneName: "short" });
149
+ const start = new Date(event.start);
150
+ const end = new Date(event.end);
151
+ const zoneName = (date: Date) => zoneFormat.formatToParts(date).find((part) => part.type === "timeZoneName")?.value ?? event.timezone;
152
+ const startZone = zoneName(start);
153
+ const endZone = zoneName(end);
154
+ return startZone === endZone
155
+ ? `${time.format(start)}–${time.format(end)} ${startZone}`
156
+ : `${time.format(start)} ${startZone}–${time.format(end)} ${endZone}`;
157
+ } catch {
158
+ return "";
159
+ }
160
+ }
161
+
162
+ /** Start and end time ("18:15", "19:15") and the zone ("CET") for a compact time column; null for all-day events. */
163
+ export function eventTimeParts(event: PublicEvent, locale: string): { start: string; end: string; zone: string } | null {
164
+ if (event.allDay) return null;
165
+ try {
166
+ const time = new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit", timeZone: event.timezone });
167
+ const zone = new Intl.DateTimeFormat(locale, { timeZone: event.timezone, timeZoneName: "short" })
168
+ .formatToParts(new Date(event.start)).find((part) => part.type === "timeZoneName")?.value ?? event.timezone;
169
+ return { start: time.format(new Date(event.start)), end: time.format(new Date(event.end)), zone };
170
+ } catch {
171
+ return null;
172
+ }
173
+ }
174
+
175
+ export function monthLabel(month: string, locale: string): string {
176
+ const [year, monthNumber] = month.split("-").map(Number);
177
+ return new Intl.DateTimeFormat(locale, { month: "long", year: "numeric", timeZone: "UTC" })
178
+ .format(new Date(Date.UTC(year!, monthNumber! - 1, 1)));
179
+ }
180
+
181
+ export function addCalendarDay(value: string): string {
182
+ const date = new Date(`${value}T00:00:00Z`);
183
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(date.getTime())) return "";
184
+ date.setUTCDate(date.getUTCDate() + 1);
185
+ return dateKey(date);
186
+ }
187
+
188
+ function localDate(instant: string, timezone: string): string {
189
+ if (!Number.isFinite(new Date(instant).getTime())) return "";
190
+ try {
191
+ return civilDate(instant, timezone);
192
+ } catch {
193
+ return "";
194
+ }
195
+ }
196
+
197
+ export function dateKey(date: Date): string {
198
+ return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(date.getUTCDate()).padStart(2, "0")}`;
199
+ }
@@ -0,0 +1,122 @@
1
+ import { bindMessages, localeDirection, resolveLocale, type Bound } from "@vermeulen.solutions/eventual-locales";
2
+
3
+ /**
4
+ * Every visible string of the event pages (EventBrowser, EventDetail). English is
5
+ * the source; other languages ship in @vermeulen.solutions/eventual-locales
6
+ * (catalogs/core-site/<lang>.json, flat dotted keys over this tree). Leaves written as
7
+ * ["template", "arg", …] become functions; templates use ICU syntax ({count, plural, …}).
8
+ */
9
+ const en = {
10
+ pageTitle: ["Events – {month}", "month"],
11
+ intro: "Browse the month in the format that suits you.",
12
+ views: {
13
+ label: "View",
14
+ list: "List",
15
+ timeline: "Timeline",
16
+ cards: "Cards",
17
+ schedule: "Schedule",
18
+ dates: "Date strip",
19
+ month: "Month",
20
+ locations: "Locations",
21
+ },
22
+ month: {
23
+ navigation: "Choose a month",
24
+ previous: ["Previous month: {month}", "month"],
25
+ next: ["Next month: {month}", "month"],
26
+ current: "This month",
27
+ events: ["Events in {month}", "month"],
28
+ },
29
+ filter: {
30
+ label: "Category",
31
+ all: "All categories",
32
+ apply: "Show",
33
+ active: ["Showing: {category}", "category"],
34
+ clear: "Show all categories",
35
+ },
36
+ count: ["{count, plural, one {# event} other {# events}}", "count"],
37
+ notice: {
38
+ unavailable: "Events are temporarily unavailable.",
39
+ unavailableDetail: "The events could not be loaded. Please try again later.",
40
+ tryAgain: "Try again",
41
+ empty: "No events are scheduled for this month.",
42
+ emptyFiltered: "No events in this category this month.",
43
+ notFound: "This event is unavailable or has been removed.",
44
+ },
45
+ event: {
46
+ allDay: "All day",
47
+ organizer: ["Organized by {name}", "name"],
48
+ directions: "Directions",
49
+ details: "Event details",
50
+ website: "Event website",
51
+ joinOnline: "Join online",
52
+ categories: "Categories",
53
+ locationToConfirm: "Location to be confirmed",
54
+ originally: ["Originally {date}", "date"],
55
+ back: "Back to events",
56
+ },
57
+ status: {
58
+ cancelled: "Cancelled",
59
+ postponed: "Postponed",
60
+ rescheduled: "Rescheduled",
61
+ },
62
+ calendar: {
63
+ add: "Add to calendar",
64
+ addFor: ["Add to calendar: {title}", "title"],
65
+ google: "Google Calendar",
66
+ outlook: "Outlook",
67
+ office365: "Office 365",
68
+ ics: "Download iCal file",
69
+ subscribe: "Subscribe to calendar",
70
+ },
71
+ dates: {
72
+ jump: "Jump to a date",
73
+ },
74
+ newTab: "(opens in a new tab)",
75
+ } as const;
76
+
77
+ /** English source; its dotted paths are the keys of the core-site catalogs. */
78
+ export const EVENT_PAGES_EN = en;
79
+
80
+ export type EventPageText = Bound<typeof en>;
81
+
82
+ // Each import becomes its own chunk, loaded per language.
83
+ const catalogs: Record<string, () => Promise<{ default: Record<string, string> }>> = {
84
+ fr: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/fr.json", { with: { type: "json" } }),
85
+ de: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/de.json", { with: { type: "json" } }),
86
+ nl: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/nl.json", { with: { type: "json" } }),
87
+ es: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/es.json", { with: { type: "json" } }),
88
+ it: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/it.json", { with: { type: "json" } }),
89
+ pt: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/pt.json", { with: { type: "json" } }),
90
+ "pt-BR": () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/pt-BR.json", { with: { type: "json" } }),
91
+ pl: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/pl.json", { with: { type: "json" } }),
92
+ cs: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/cs.json", { with: { type: "json" } }),
93
+ sv: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/sv.json", { with: { type: "json" } }),
94
+ da: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/da.json", { with: { type: "json" } }),
95
+ nb: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/nb.json", { with: { type: "json" } }),
96
+ fi: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/fi.json", { with: { type: "json" } }),
97
+ ja: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/ja.json", { with: { type: "json" } }),
98
+ "zh-CN": () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/zh-CN.json", { with: { type: "json" } }),
99
+ ko: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/ko.json", { with: { type: "json" } }),
100
+ tr: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/tr.json", { with: { type: "json" } }),
101
+ uk: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/uk.json", { with: { type: "json" } }),
102
+ ar: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/ar.json", { with: { type: "json" } }),
103
+ he: () => import("@vermeulen.solutions/eventual-locales/catalogs/core-site/he.json", { with: { type: "json" } }),
104
+ };
105
+
106
+ /** The page texts in a language (English when there is no catalog), and its writing direction. */
107
+ export async function eventPageText(locale: string | undefined): Promise<{ text: EventPageText; lang: string; dir: "ltr" | "rtl" }> {
108
+ const wanted = resolveLocale(locale ?? "en", Object.keys(catalogs));
109
+ let catalog: Record<string, string> | undefined;
110
+ try {
111
+ catalog = wanted !== "en" ? (await catalogs[wanted]?.())?.default : undefined;
112
+ } catch {
113
+ catalog = undefined;
114
+ }
115
+ // The texts are English until that language's catalog exists: then lang and dir are English too.
116
+ const lang = catalog ? wanted : "en";
117
+ return {
118
+ text: bindMessages(en, catalog, lang) as EventPageText,
119
+ lang,
120
+ dir: localeDirection(lang) === "rtl" ? "rtl" : "ltr",
121
+ };
122
+ }
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Event pages for EmDash sites: loaders that run in the site's page, and the data the
3
+ * EventBrowser and EventDetail components render. A page sets `Astro.response.status` from the
4
+ * loader (502 when the feed fails, 404 for an unknown event), which a component cannot do.
5
+ *
6
+ * const data = await loadEventBrowser(Astro.url, { pluginId: "r_…", locale: "fr" });
7
+ * Astro.response.status = data.status;
8
+ */
9
+ import { fetchPublicFeed, serializeJsonLd, eventToJsonLd, type PublicEvent } from "../feed";
10
+ import { safeWebUrl, type CalendarLinks } from "../event-details";
11
+ import { eventPageUrl } from "../event-list";
12
+ import { buildCalendar, calendarRange, displayDate, eventEndDate, eventStartDate, eventTimeRange, monthDateRange, monthLabel, monthOf, normalizeLocale, normalizeTimeZone, weekdayHeadings, type CalendarCell } from "./grid";
13
+ import { EVENT_VIEWS, adjacentMonth, eventBrowserHref, eventBrowserState, eventRange, offeredViews, type EventBrowserState, type EventView } from "./state";
14
+ import { absoluteCalendarLinks, calendarSubscriptionUrl, decodeRouteParam, safeImageUrl } from "./links";
15
+ import { descriptionExcerpt, descriptionHtml } from "./description";
16
+ import { eventPageText, type EventPageText } from "./i18n";
17
+
18
+ export * from "./grid";
19
+ export * from "./state";
20
+ export * from "./links";
21
+ export { descriptionExcerpt, descriptionHtml } from "./description";
22
+ export { eventPageText, EVENT_PAGES_EN, type EventPageText } from "./i18n";
23
+ export type { PublicEvent } from "../feed";
24
+
25
+ export interface EventPagesOptions {
26
+ /** Installed plugin ID: `eventual` for a config install, `r_…` for a Registry install. */
27
+ pluginId?: string;
28
+ /** Origin of the EmDash site that serves the feed (default: the page's own). */
29
+ origin?: string;
30
+ /** Page language: texts, dates and the feed's content language (default "en"). */
31
+ locale?: string;
32
+ /** Content language for the feed when it differs from `locale` (default: its language part). */
33
+ contentLocale?: string;
34
+ /** Only events translated into the content language (default false: others show with a language prefix). */
35
+ strict?: boolean;
36
+ /** Time zone for "this month" and "today" (default UTC). Event times use each event's own zone. */
37
+ timeZone?: string;
38
+ /** Address of the events page; detail pages are `<basePath>/<slug>` (default "/events"). */
39
+ basePath?: string;
40
+ /** "detail" links to the package's detail page; "cms" to the entry's own public URL when it has one. */
41
+ linkTo?: "detail" | "cms";
42
+ /** Views offered, in order, and the default one. */
43
+ views?: readonly EventView[];
44
+ defaultView?: EventView;
45
+ /** Fixed values instead of the query string. */
46
+ view?: EventView;
47
+ month?: string;
48
+ category?: string;
49
+ /** For tests: the current time. */
50
+ now?: Date;
51
+ }
52
+
53
+ export interface DateGroup {
54
+ date: string;
55
+ id: string;
56
+ label: string;
57
+ weekday: string;
58
+ day: string;
59
+ events: PublicEvent[];
60
+ }
61
+
62
+ export interface LocationGroup {
63
+ location: string;
64
+ directionsUrl: string;
65
+ events: PublicEvent[];
66
+ }
67
+
68
+ export interface EventBrowserData {
69
+ status: 200 | 502;
70
+ pageTitle: string;
71
+ description: string;
72
+ text: EventPageText;
73
+ lang: string;
74
+ dir: "ltr" | "rtl";
75
+ locale: string;
76
+ origin: string;
77
+ pluginId: string;
78
+ basePath: string;
79
+ linkTo: "detail" | "cms";
80
+ state: EventBrowserState;
81
+ views: Array<{ view: EventView; label: string; href: string; current: boolean }>;
82
+ monthTitle: string;
83
+ previous: { href: string; label: string };
84
+ next: { href: string; label: string };
85
+ current: { href: string; label: string; isCurrent: boolean };
86
+ clearHref: string;
87
+ categories: string[];
88
+ events: PublicEvent[];
89
+ weeks: CalendarCell[][];
90
+ weekdays: { short: string[]; long: string[] };
91
+ dateGroups: DateGroup[];
92
+ locationGroups: LocationGroup[];
93
+ today: string;
94
+ subscriptionUrl: string;
95
+ }
96
+
97
+ export interface EventDetailData {
98
+ status: 200 | 404 | 502;
99
+ pageTitle: string;
100
+ description: string;
101
+ text: EventPageText;
102
+ lang: string;
103
+ dir: "ltr" | "rtl";
104
+ locale: string;
105
+ origin: string;
106
+ pluginId: string;
107
+ backHref: string;
108
+ event?: PublicEvent;
109
+ jsonLd?: string;
110
+ dateText?: string;
111
+ timeText?: string;
112
+ imageUrl?: string;
113
+ websiteUrl?: string;
114
+ directionsUrl?: string;
115
+ onlineUrl?: string;
116
+ descriptionHtml?: string;
117
+ calendarLinks?: CalendarLinks;
118
+ subscriptionUrl?: string;
119
+ }
120
+
121
+ interface Resolved {
122
+ locale: string;
123
+ contentLocale: string;
124
+ timeZone: string;
125
+ origin: string;
126
+ pluginId: string;
127
+ basePath: string;
128
+ linkTo: "detail" | "cms";
129
+ now: Date;
130
+ }
131
+
132
+ function resolve(url: URL, options: EventPagesOptions): Resolved {
133
+ const locale = normalizeLocale(options.locale ?? "en");
134
+ return {
135
+ locale,
136
+ contentLocale: options.contentLocale ?? locale.split("-")[0]!,
137
+ timeZone: normalizeTimeZone(options.timeZone ?? "UTC"),
138
+ origin: safeWebUrl(options.origin ?? "") || url.origin,
139
+ pluginId: options.pluginId || "eventual",
140
+ basePath: (options.basePath ?? "/events").replace(/\/+$/, "") || "/events",
141
+ linkTo: options.linkTo ?? "detail",
142
+ now: options.now ?? new Date(),
143
+ };
144
+ }
145
+
146
+ /** The events page: fetches one month (or the weeks around it for the month view). */
147
+ export async function loadEventBrowser(url: URL, options: EventPagesOptions = {}): Promise<EventBrowserData> {
148
+ const settings = resolve(url, options);
149
+ const state = eventBrowserState(url.searchParams, monthOf(settings.now, settings.timeZone), options);
150
+ const range = state.view === "month" ? calendarRange(state.month, settings.locale) : monthDateRange(state.month);
151
+ let events: PublicEvent[] | null = null;
152
+ try {
153
+ const feed = await fetchPublicFeed(settings.origin, range.from, range.through, state.category, {
154
+ locale: settings.contentLocale,
155
+ strict: options.strict ?? false,
156
+ publicUrls: settings.linkTo === "cms",
157
+ pluginId: settings.pluginId,
158
+ });
159
+ events = feed.events;
160
+ } catch {
161
+ events = null;
162
+ }
163
+ return buildEventBrowserData(events, url, { ...options, ...settings, view: state.view, month: state.month, category: state.category });
164
+ }
165
+
166
+ /** Pure part of loadEventBrowser: `events` null means the feed failed. */
167
+ export async function buildEventBrowserData(events: PublicEvent[] | null, url: URL, options: EventPagesOptions = {}): Promise<EventBrowserData> {
168
+ const settings = resolve(url, options);
169
+ const { text, lang, dir } = await eventPageText(settings.locale);
170
+ const state = eventBrowserState(url.searchParams, monthOf(settings.now, settings.timeZone), options);
171
+ const all = events ?? [];
172
+ const visible = monthDateRange(state.month);
173
+ const inMonth = all.filter((event) => eventStartDate(event) <= visible.through && eventEndDate(event) >= visible.from);
174
+ const monthTitle = monthLabel(state.month, settings.locale);
175
+ const thisMonth = monthOf(settings.now, settings.timeZone);
176
+ const fullDate = new Intl.DateTimeFormat(settings.locale, { dateStyle: "full", timeZone: "UTC" });
177
+ const weekday = new Intl.DateTimeFormat(settings.locale, { weekday: "short", timeZone: "UTC" });
178
+ const day = new Intl.DateTimeFormat(settings.locale, { day: "numeric", timeZone: "UTC" });
179
+ const byDate = new Map<string, PublicEvent[]>();
180
+ for (const event of inMonth) {
181
+ const date = eventStartDate(event);
182
+ byDate.set(date, [...(byDate.get(date) ?? []), event]);
183
+ }
184
+ const byLocation = new Map<string, PublicEvent[]>();
185
+ for (const event of inMonth) {
186
+ const location = event.location.trim() || text.event.locationToConfirm;
187
+ byLocation.set(location, [...(byLocation.get(location) ?? []), event]);
188
+ }
189
+ const previousMonth = adjacentMonth(state, -1);
190
+ const nextMonth = adjacentMonth(state, 1);
191
+ return {
192
+ status: events ? 200 : 502,
193
+ pageTitle: text.pageTitle(monthTitle),
194
+ description: text.intro,
195
+ text,
196
+ lang,
197
+ dir,
198
+ locale: settings.locale,
199
+ origin: settings.origin,
200
+ pluginId: settings.pluginId,
201
+ basePath: settings.basePath,
202
+ linkTo: settings.linkTo,
203
+ state,
204
+ views: offeredViews(options).map((view) => ({ view, label: text.views[view], href: eventBrowserHref(state, { view }), current: view === state.view })),
205
+ monthTitle,
206
+ previous: { href: eventBrowserHref(state, { month: previousMonth }), label: text.month.previous(monthLabel(previousMonth, settings.locale)) },
207
+ next: { href: eventBrowserHref(state, { month: nextMonth }), label: text.month.next(monthLabel(nextMonth, settings.locale)) },
208
+ current: { href: eventBrowserHref(state, { month: thisMonth }), label: text.month.current, isCurrent: state.month === thisMonth },
209
+ clearHref: eventBrowserHref({ ...state, category: "" }),
210
+ categories: [...new Set(inMonth.flatMap((event) => event.categories))].sort((a, b) => a.localeCompare(b, settings.locale)),
211
+ events: inMonth,
212
+ weeks: state.view === "month" ? buildCalendar(state.month, settings.locale, all) : [],
213
+ weekdays: { short: weekdayHeadings(settings.locale), long: weekdayHeadings(settings.locale, "long") },
214
+ dateGroups: [...byDate].map(([date, grouped]) => {
215
+ const value = new Date(`${date}T12:00:00Z`);
216
+ return { date, id: `eventual-date-${date}`, label: fullDate.format(value), weekday: weekday.format(value), day: day.format(value), events: grouped };
217
+ }),
218
+ locationGroups: [...byLocation].map(([location, grouped]) => ({
219
+ location,
220
+ directionsUrl: grouped.map((event) => safeWebUrl(event.directionsUrl)).find(Boolean) ?? "",
221
+ events: grouped,
222
+ })),
223
+ today: settings.now.toISOString().slice(0, 10),
224
+ subscriptionUrl: calendarSubscriptionUrl(settings.origin, settings.pluginId, { locale: options.strict ? settings.contentLocale : undefined, category: state.category || undefined }),
225
+ };
226
+ }
227
+
228
+ /** The address of an event's detail page (or its own public URL with `linkTo: "cms"`). */
229
+ export function eventHref(event: PublicEvent, data: Pick<EventBrowserData, "basePath" | "linkTo">): string {
230
+ return eventPageUrl(data.linkTo === "cms" ? event : { ...event, publicUrl: undefined }, data.basePath);
231
+ }
232
+
233
+ /** The detail page: `id` is the route parameter (an event's slug or ID). */
234
+ export async function loadEventDetail(url: URL, id: string | undefined, options: EventPagesOptions = {}): Promise<EventDetailData> {
235
+ const settings = resolve(url, options);
236
+ const range = eventRange(url.searchParams, settings.now);
237
+ if (!range) return buildEventDetailData([], undefined, url, options);
238
+ try {
239
+ const feed = await fetchPublicFeed(settings.origin, range.from, range.through, "", {
240
+ locale: settings.contentLocale,
241
+ strict: options.strict ?? false,
242
+ publicUrls: false,
243
+ pluginId: settings.pluginId,
244
+ });
245
+ return buildEventDetailData(feed.events, id, url, options);
246
+ } catch {
247
+ return buildEventDetailData(null, id, url, options);
248
+ }
249
+ }
250
+
251
+ /** The content entry behind a feed event (a recurring date's ID ends in `#<date>`): the `eventId` for RsvpForm and TicketCheckout. */
252
+ export function eventContentId(event: PublicEvent): string {
253
+ return event.id.split("#")[0] ?? event.id;
254
+ }
255
+
256
+ /** The event's start as an ISO instant: the `occurrenceStart` for RsvpForm and TicketCheckout. */
257
+ export function occurrenceStart(event: PublicEvent): string {
258
+ const time = Date.parse(event.start);
259
+ return Number.isNaN(time) ? "" : new Date(time).toISOString();
260
+ }
261
+
262
+ /** Finds the event by ID, slug or series ID, preferring the date the address names. */
263
+ export function findEvent(events: PublicEvent[], param: string, from?: string): PublicEvent | undefined {
264
+ if (!param) return undefined;
265
+ const matches = events.filter((event) => event.id === param || event.slug === param || event.id.split("#")[0] === param);
266
+ return matches.find((event) => event.id === param)
267
+ ?? matches.find((event) => from && eventStartDate(event) === from)
268
+ ?? matches[0];
269
+ }
270
+
271
+ /** Pure part of loadEventDetail: `events` null means the feed failed. */
272
+ export async function buildEventDetailData(events: PublicEvent[] | null, id: string | undefined, url: URL, options: EventPagesOptions = {}): Promise<EventDetailData> {
273
+ const settings = resolve(url, options);
274
+ const { text, lang, dir } = await eventPageText(settings.locale);
275
+ const base = { text, lang, dir, locale: settings.locale, origin: settings.origin, pluginId: settings.pluginId, backHref: settings.basePath };
276
+ if (!events) return { ...base, status: 502, pageTitle: text.notice.unavailable, description: text.notice.unavailableDetail };
277
+ const event = findEvent(events, decodeRouteParam(id), url.searchParams.get("from") ?? undefined);
278
+ if (!event) return { ...base, status: 404, pageTitle: text.event.details, description: text.notice.notFound };
279
+ const sameDay = eventStartDate(event) === eventEndDate(event);
280
+ const start = displayDate(event.start, settings.locale, event.timezone, event.allDay, "full");
281
+ const end = displayDate(event.end, settings.locale, event.timezone, event.allDay, "full");
282
+ return {
283
+ ...base,
284
+ status: 200,
285
+ pageTitle: event.title,
286
+ description: descriptionExcerpt(event.description, 160),
287
+ event,
288
+ jsonLd: serializeJsonLd(eventToJsonLd(event, { siteUrl: settings.origin })),
289
+ dateText: sameDay ? start : `${start} – ${end}`,
290
+ timeText: event.allDay ? text.event.allDay : eventTimeRange(event, settings.locale),
291
+ imageUrl: safeImageUrl(event.imageMedia?.src || event.imageUrl, settings.origin),
292
+ websiteUrl: safeWebUrl(event.externalUrl) || undefined,
293
+ directionsUrl: safeWebUrl(event.directionsUrl) || undefined,
294
+ onlineUrl: event.locationType === "virtual" || event.locationType === "hybrid" ? safeWebUrl(event.virtualUrl ?? "") || undefined : undefined,
295
+ descriptionHtml: descriptionHtml(event.descriptionBlocks, event.description, { headingBase: 2, newTabText: text.newTab }),
296
+ calendarLinks: absoluteCalendarLinks(event.calendarLinks, settings.origin),
297
+ subscriptionUrl: calendarSubscriptionUrl(settings.origin, settings.pluginId),
298
+ };
299
+ }
300
+
301
+ export { EVENT_VIEWS };
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Addresses the event pages show: calendar subscription, the feed's per-event links made absolute,
3
+ * and safe image URLs. Every address that reaches the plugin carries the installed plugin ID
4
+ * (`eventual` for a config install, `r_…` for a Registry install).
5
+ */
6
+ import type { CalendarLinks } from "../event-details";
7
+
8
+ /** `webcal://…/_emdash/api/plugins/<pluginId>/calendar`, optionally for one language or category. */
9
+ export function calendarSubscriptionUrl(origin: string | URL, pluginId = "eventual", options: { locale?: string; category?: string } = {}): string {
10
+ try {
11
+ const url = new URL(`/_emdash/api/plugins/${encodeURIComponent(pluginId)}/calendar`, origin);
12
+ if (options.locale) url.searchParams.set("locale", options.locale);
13
+ if (options.category) url.searchParams.set("category", options.category);
14
+ return url.href.replace(/^https?:/i, "webcal:");
15
+ } catch {
16
+ return "";
17
+ }
18
+ }
19
+
20
+ /**
21
+ * The feed's calendar links with the `.ics` download made absolute against the API origin
22
+ * (the feed gives a site-relative path, which breaks when pages and API are on different hosts).
23
+ */
24
+ export function absoluteCalendarLinks(links: CalendarLinks | undefined, origin: string | URL): CalendarLinks | undefined {
25
+ if (!links) return undefined;
26
+ let ics = links.ics;
27
+ try {
28
+ ics = new URL(links.ics, origin).href;
29
+ } catch {}
30
+ return { ...links, ics };
31
+ }
32
+
33
+ /** https images anywhere; http only from the API origin itself (local development). */
34
+ export function safeImageUrl(value: string | undefined, origin: string | URL): string {
35
+ if (!value || !value.trim()) return "";
36
+ try {
37
+ const url = new URL(value, origin);
38
+ const site = new URL(origin);
39
+ if (url.protocol === "https:") return url.href;
40
+ if (url.protocol === "http:" && site.protocol === "http:" && url.origin === site.origin) return url.href;
41
+ return "";
42
+ } catch {
43
+ return "";
44
+ }
45
+ }
46
+
47
+ export function decodeRouteParam(value: string | undefined): string {
48
+ if (!value) return "";
49
+ try {
50
+ return decodeURIComponent(value);
51
+ } catch {
52
+ return "";
53
+ }
54
+ }