@akshayanimateddsa/site-ui 0.0.0-stage → 0.1.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,317 @@
1
+ /**
2
+ * The calendar view: an Outlook-style calendar with Day, Week and Month views. A toolbar (Today,
3
+ * previous / next, the range title, a slot for the site's buttons, the view switch), a sidebar
4
+ * with a small month to jump around (and a slot for the site's panels), and the main view: a
5
+ * time grid with half-hour lines and a red "now" line (day and week), or a month of day cells with
6
+ * event chips. Events come from the caller (`setEvents`); clicking one calls `onSelectEvent`, and
7
+ * with `onCreate` the caller can drag across the time grid to pick a span (snapped to
8
+ * `snapMinutes`). It stores nothing and calls no network: a site loads its events when
9
+ * `onRangeChange` says what is on screen. Styles: css/calendar.css; colours are `--cal-*` tokens.
10
+ * Keys (focus inside the calendar): T today, D / W / M the view, ← / → previous / next.
11
+ */
12
+ import { append, el } from '../dom.js';
13
+ import { addDays, addMonths, dayKeyOf, minuteOfDay, monthGrid, parseDayKey, startOfDay, startOfMonth, weekDays, zonedTime, } from './dates.js';
14
+ import { eventsOnDay, layoutDay } from './layout.js';
15
+ /** The views in the order the switch shows them. */
16
+ export const CALENDAR_VIEWS = ['day', 'week', 'month'];
17
+ const isTyping = (target) => target instanceof HTMLElement && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName));
18
+ /** Mounts a calendar in `host` (its content is replaced). */
19
+ export function createCalendar(host, options) {
20
+ const { timeZone } = options;
21
+ const locale = options.locale;
22
+ const weekStartsOn = options.weekStartsOn ?? 1;
23
+ const snap = options.snapMinutes ?? 30;
24
+ const now = options.now ?? Date.now;
25
+ const narrow = typeof matchMedia === 'function' && matchMedia('(max-width: 640px)').matches;
26
+ let view = options.view ?? (narrow ? 'day' : 'week');
27
+ if (narrow && view === 'week')
28
+ view = 'day';
29
+ let current = options.date ?? dayKeyOf(now(), timeZone);
30
+ let miniMonth = startOfMonth(current);
31
+ let events = options.events ?? [];
32
+ let scrolledTo = null; // the time grid's scroll position once the viewer scrolls (kept across redraws)
33
+ /* ---------- Formatting (days are formatted at UTC noon, times in the calendar's zone) ---------- */
34
+ const utcDate = (key) => {
35
+ const { year, month, day } = parseDayKey(key);
36
+ return new Date(Date.UTC(year, month - 1, day, 12));
37
+ };
38
+ const dayFormat = (format) => {
39
+ const formatter = new Intl.DateTimeFormat(locale, { ...format, timeZone: 'UTC' });
40
+ return (key) => formatter.format(utcDate(key));
41
+ };
42
+ const weekdayShort = dayFormat({ weekday: 'short' });
43
+ const monthYear = dayFormat({ month: 'long', year: 'numeric' });
44
+ const monthDay = dayFormat({ month: 'short', day: 'numeric' });
45
+ const longDay = dayFormat({ weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
46
+ const timeFormatter = new Intl.DateTimeFormat(locale, { timeZone, hour: 'numeric', minute: '2-digit' });
47
+ const time = (ms) => timeFormatter.format(new Date(ms));
48
+ const hourFormatter = new Intl.DateTimeFormat(locale, { timeZone: 'UTC', hour: 'numeric' });
49
+ const hourLabel = (hour) => hourFormatter.format(new Date(Date.UTC(2000, 0, 1, hour)));
50
+ const todayKey = () => dayKeyOf(now(), timeZone);
51
+ /* ---------- What is on screen ---------- */
52
+ function visibleDays() {
53
+ if (view === 'day')
54
+ return [current];
55
+ if (view === 'week')
56
+ return weekDays(current, weekStartsOn);
57
+ return monthGrid(current, weekStartsOn).flat();
58
+ }
59
+ function range() {
60
+ const days = visibleDays();
61
+ const from = days[0] ?? current;
62
+ const to = days[days.length - 1] ?? current;
63
+ return { view, from, to, start: startOfDay(from, timeZone), end: startOfDay(addDays(to, 1), timeZone) };
64
+ }
65
+ function title() {
66
+ if (view === 'day')
67
+ return longDay(current);
68
+ if (view === 'month')
69
+ return monthYear(current);
70
+ const days = weekDays(current, weekStartsOn);
71
+ const first = days[0] ?? current;
72
+ const last = days[6] ?? current;
73
+ const year = parseDayKey(last).year;
74
+ return `${monthDay(first)} – ${monthDay(last)}, ${year}`;
75
+ }
76
+ /* ---------- The frame ---------- */
77
+ const titleEl = el('h2', { class: 'cal-title', 'aria-live': 'polite' });
78
+ const toolbarEnd = el('div', { class: 'cal-toolbar-end' });
79
+ const viewButtons = CALENDAR_VIEWS.map((name) => el('button', { type: 'button', class: 'cal-view-btn', 'data-view': name, onclick: () => setView(name) }, name[0]?.toUpperCase() + name.slice(1)));
80
+ const mini = el('div', { class: 'cal-mini' });
81
+ const sidebar = el('div', { class: 'cal-sidebar-extra' });
82
+ const main = el('div', { class: 'cal-main' });
83
+ const root = el('div', { class: 'cal' }, el('div', { class: 'cal-toolbar' }, el('button', { type: 'button', class: 'cal-btn cal-today', onclick: () => today() }, 'Today'), el('button', { type: 'button', class: 'cal-icon-btn', 'aria-label': 'Previous', title: 'Previous', onclick: () => prev() }, '‹'), el('button', { type: 'button', class: 'cal-icon-btn', 'aria-label': 'Next', title: 'Next', onclick: () => next() }, '›'), titleEl, toolbarEnd, el('div', { class: 'cal-views', role: 'group', 'aria-label': 'View' }, ...viewButtons)), el('div', { class: 'cal-body' }, el('aside', { class: 'cal-sidebar' }, mini, sidebar), main));
84
+ root.addEventListener('keydown', (event) => {
85
+ if (event.altKey || event.ctrlKey || event.metaKey || isTyping(event.target))
86
+ return;
87
+ const actions = {
88
+ t: today, d: () => setView('day'), w: () => setView('week'), m: () => setView('month'),
89
+ ArrowLeft: prev, ArrowRight: next,
90
+ };
91
+ const action = actions[event.key.length === 1 ? event.key.toLowerCase() : event.key];
92
+ if (!action)
93
+ return;
94
+ event.preventDefault();
95
+ action();
96
+ });
97
+ /* ---------- An event, as a block (time grid) or a chip (month) ---------- */
98
+ function eventButton(event, className, label) {
99
+ const button = el('button', {
100
+ type: 'button', class: className, 'data-tone': event.tone ?? 'event', 'data-id': event.id,
101
+ title: `${event.title}${event.subtitle ? ` · ${event.subtitle}` : ''} (${time(event.start)} – ${time(event.end)})`,
102
+ });
103
+ append(button, ...label);
104
+ button.addEventListener('click', (click) => {
105
+ click.stopPropagation();
106
+ options.onSelectEvent?.(event, button);
107
+ });
108
+ button.addEventListener('pointerdown', (down) => down.stopPropagation()); // not a drag on the grid
109
+ return button;
110
+ }
111
+ /* ---------- Day and week: the time grid ---------- */
112
+ function renderTimeGrid(days) {
113
+ const today = todayKey();
114
+ const head = el('div', { class: 'cal-grid-head' }, el('div', { class: 'cal-gutter-head' }));
115
+ const body = el('div', { class: 'cal-grid-body' });
116
+ const gutter = el('div', { class: 'cal-gutter', 'aria-hidden': 'true' });
117
+ for (let hour = 1; hour < 24; hour++) {
118
+ append(gutter, el('span', { class: 'cal-hour-label', style: `top:${(hour / 24) * 100}%` }, hourLabel(hour)));
119
+ }
120
+ append(body, gutter);
121
+ for (const day of days) {
122
+ append(head, el('div', { class: 'cal-day-head', 'data-today': day === today }, el('span', { class: 'cal-day-name' }, weekdayShort(day)), el('button', { type: 'button', class: 'cal-day-num', 'aria-label': longDay(day), onclick: () => { current = day; setView('day'); } }, String(parseDayKey(day).day))));
123
+ const column = el('div', { class: 'cal-col', 'data-day': day, 'data-today': day === today });
124
+ for (const segment of layoutDay(events, day, timeZone)) {
125
+ const { event } = segment;
126
+ const block = eventButton(event, 'cal-event', [
127
+ el('span', { class: 'cal-event-title' }, event.title),
128
+ el('span', { class: 'cal-event-time' }, `${time(event.start)} – ${time(event.end)}`),
129
+ event.subtitle ? el('span', { class: 'cal-event-sub' }, event.subtitle) : document.createTextNode(''),
130
+ ]);
131
+ block.style.top = `${(segment.top / 1440) * 100}%`;
132
+ block.style.height = `${((segment.bottom - segment.top) / 1440) * 100}%`;
133
+ block.style.left = `${(segment.column / segment.columns) * 100}%`;
134
+ block.style.width = `${100 / segment.columns}%`;
135
+ if (segment.bottom - segment.top < 45)
136
+ block.classList.add('cal-event--short');
137
+ append(column, block);
138
+ }
139
+ if (day === today)
140
+ append(column, el('div', { class: 'cal-now', 'aria-hidden': 'true' }));
141
+ if (options.onCreate)
142
+ enableDrag(column, day);
143
+ append(body, column);
144
+ }
145
+ const scroll = el('div', { class: 'cal-scroll' }, body);
146
+ const grid = el('div', { class: 'cal-grid', style: `--cal-days:${days.length}` }, head, scroll);
147
+ placeNowLines(grid);
148
+ requestAnimationFrame(() => {
149
+ scroll.scrollTop = scrolledTo ?? (scroll.scrollHeight * (options.scrollToHour ?? 8)) / 24;
150
+ scroll.addEventListener('scroll', () => { scrolledTo = scroll.scrollTop; }, { passive: true });
151
+ });
152
+ return grid;
153
+ }
154
+ function placeNowLines(scope) {
155
+ for (const line of scope.querySelectorAll('.cal-now')) {
156
+ line.style.top = `${(minuteOfDay(now(), timeZone) / 1440) * 100}%`;
157
+ }
158
+ }
159
+ /** Drag on an empty part of a day column to pick a span (snapped); a plain click picks one hour. */
160
+ function enableDrag(column, day) {
161
+ const minuteAt = (clientY) => {
162
+ const box = column.getBoundingClientRect();
163
+ const raw = ((clientY - box.top) / box.height) * 1440;
164
+ return Math.max(0, Math.min(1440 - snap, Math.floor(raw / snap) * snap));
165
+ };
166
+ column.addEventListener('pointerdown', (down) => {
167
+ if (down.button !== 0)
168
+ return;
169
+ down.preventDefault();
170
+ const anchor = minuteAt(down.clientY);
171
+ let from = anchor;
172
+ let to = anchor + snap;
173
+ let moved = false;
174
+ const ghost = el('div', { class: 'cal-selection', 'aria-hidden': 'true' });
175
+ const draw = () => {
176
+ ghost.style.top = `${(from / 1440) * 100}%`;
177
+ ghost.style.height = `${((to - from) / 1440) * 100}%`;
178
+ ghost.textContent = `${time(zonedTime(day, from, timeZone))} – ${time(zonedTime(day, to, timeZone))}`;
179
+ };
180
+ draw();
181
+ append(column, ghost);
182
+ column.setPointerCapture(down.pointerId);
183
+ const move = (event) => {
184
+ const at = minuteAt(event.clientY);
185
+ if (at !== anchor)
186
+ moved = true;
187
+ from = Math.min(anchor, at);
188
+ to = Math.max(anchor, at) + snap;
189
+ draw();
190
+ };
191
+ const up = () => {
192
+ column.removeEventListener('pointermove', move);
193
+ column.removeEventListener('pointerup', up);
194
+ column.removeEventListener('pointercancel', cancel);
195
+ ghost.remove();
196
+ if (!moved)
197
+ to = Math.min(1440, from + Math.max(snap, 60));
198
+ options.onCreate?.({ start: zonedTime(day, from, timeZone), end: zonedTime(day, to, timeZone) });
199
+ };
200
+ const cancel = () => {
201
+ column.removeEventListener('pointermove', move);
202
+ column.removeEventListener('pointerup', up);
203
+ column.removeEventListener('pointercancel', cancel);
204
+ ghost.remove();
205
+ };
206
+ column.addEventListener('pointermove', move);
207
+ column.addEventListener('pointerup', up);
208
+ column.addEventListener('pointercancel', cancel);
209
+ });
210
+ }
211
+ /* ---------- Month: day cells with chips ---------- */
212
+ const CHIPS = 3;
213
+ function renderMonth() {
214
+ const today = todayKey();
215
+ const month = current.slice(0, 7);
216
+ const weeks = monthGrid(current, weekStartsOn);
217
+ const head = el('div', { class: 'cal-month-head' }, ...(weeks[0] ?? []).map((day) => el('div', { class: 'cal-month-dayname' }, weekdayShort(day))));
218
+ const body = el('div', { class: 'cal-month-body', style: `--cal-weeks:${weeks.length}` });
219
+ for (const week of weeks) {
220
+ for (const day of week) {
221
+ const dayEvents = eventsOnDay(events, day, timeZone);
222
+ const openDay = () => { current = day; setView('day'); };
223
+ const cell = el('div', { class: 'cal-cell', 'data-day': day, 'data-today': day === today, 'data-outside': day.slice(0, 7) !== month }, el('button', { type: 'button', class: 'cal-cell-num', 'aria-label': longDay(day), onclick: openDay }, parseDayKey(day).day === 1 ? monthDay(day) : String(parseDayKey(day).day)));
224
+ for (const event of dayEvents.slice(0, CHIPS)) {
225
+ append(cell, eventButton(event, 'cal-chip', [
226
+ el('span', { class: 'cal-chip-dot', 'aria-hidden': 'true' }),
227
+ el('span', { class: 'cal-chip-time' }, time(Math.max(event.start, startOfDay(day, timeZone)))),
228
+ el('span', { class: 'cal-chip-title' }, event.title),
229
+ ]));
230
+ }
231
+ if (dayEvents.length > CHIPS) {
232
+ append(cell, el('button', { type: 'button', class: 'cal-more', onclick: openDay }, `+${dayEvents.length - CHIPS} more`));
233
+ }
234
+ append(body, cell);
235
+ }
236
+ }
237
+ return el('div', { class: 'cal-month' }, head, body);
238
+ }
239
+ /* ---------- The small month in the sidebar ---------- */
240
+ function renderMini() {
241
+ const { from, to } = range();
242
+ const today = todayKey();
243
+ const month = miniMonth.slice(0, 7);
244
+ const weeks = monthGrid(miniMonth, weekStartsOn);
245
+ const grid = el('div', { class: 'cal-mini-grid', role: 'grid', 'aria-label': monthYear(miniMonth) }, ...(weeks[0] ?? []).map((day) => el('span', { class: 'cal-mini-dayname', 'aria-hidden': 'true' }, weekdayShort(day).slice(0, 2))));
246
+ for (const day of weeks.flat()) {
247
+ append(grid, el('button', {
248
+ type: 'button', class: 'cal-mini-day', 'aria-label': longDay(day),
249
+ 'data-today': day === today, 'data-outside': day.slice(0, 7) !== month,
250
+ 'data-selected': day >= from && day <= to && (view !== 'month' || day.slice(0, 7) === current.slice(0, 7)),
251
+ onclick: () => goTo(day),
252
+ }, String(parseDayKey(day).day)));
253
+ }
254
+ mini.replaceChildren(el('div', { class: 'cal-mini-head' }, el('span', { class: 'cal-mini-title' }, monthYear(miniMonth)), el('button', { type: 'button', class: 'cal-icon-btn cal-icon-btn--sm', 'aria-label': 'Previous month', onclick: () => { miniMonth = addMonths(miniMonth, -1); renderMini(); } }, '‹'), el('button', { type: 'button', class: 'cal-icon-btn cal-icon-btn--sm', 'aria-label': 'Next month', onclick: () => { miniMonth = addMonths(miniMonth, 1); renderMini(); } }, '›')), grid);
255
+ }
256
+ /* ---------- Rendering and moving ---------- */
257
+ function render() {
258
+ root.dataset.view = view;
259
+ titleEl.textContent = title();
260
+ for (const button of viewButtons)
261
+ button.setAttribute('aria-pressed', String(button.dataset.view === view));
262
+ main.replaceChildren(view === 'month' ? renderMonth() : renderTimeGrid(visibleDays()));
263
+ renderMini();
264
+ }
265
+ function moved() {
266
+ miniMonth = startOfMonth(current);
267
+ render();
268
+ options.onRangeChange?.(range());
269
+ }
270
+ function setView(next) {
271
+ view = next;
272
+ moved();
273
+ }
274
+ function goTo(day) {
275
+ current = day;
276
+ moved();
277
+ }
278
+ function step(direction) {
279
+ current = view === 'month' ? addMonths(startOfMonth(current), direction) : addDays(current, direction * (view === 'week' ? 7 : 1));
280
+ moved();
281
+ }
282
+ const today = () => goTo(todayKey());
283
+ const next = () => step(1);
284
+ const prev = () => step(-1);
285
+ // Every minute: move the "now" line; at midnight, draw the new day.
286
+ let shownToday = todayKey();
287
+ const clock = setInterval(() => {
288
+ if (todayKey() !== shownToday) {
289
+ shownToday = todayKey();
290
+ render();
291
+ }
292
+ else
293
+ placeNowLines(main);
294
+ }, 60_000);
295
+ host.replaceChildren(root);
296
+ render();
297
+ queueMicrotask(() => options.onRangeChange?.(range()));
298
+ return {
299
+ element: root,
300
+ sidebar,
301
+ toolbarEnd,
302
+ setEvents(list) {
303
+ events = list;
304
+ render();
305
+ },
306
+ setView,
307
+ goTo,
308
+ today,
309
+ next,
310
+ prev,
311
+ range,
312
+ destroy() {
313
+ clearInterval(clock);
314
+ root.remove();
315
+ },
316
+ };
317
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Calendar date maths, pure and headless (no DOM): the calendar and the booking slots run on it,
3
+ * and a site's server can import it too. Days are `DayKey` strings ('YYYY-MM-DD') so they can be
4
+ * compared and stored as text; instants are epoch milliseconds. Wall-clock times are read in an
5
+ * IANA time zone through `Intl`, so the same code shows India (no daylight saving) or any zone that
6
+ * has it.
7
+ */
8
+ /** A calendar day as 'YYYY-MM-DD'. */
9
+ export type DayKey = string;
10
+ /** An instant's wall-clock parts in a time zone (month 1–12, weekday 0 = Sunday). */
11
+ export interface ZonedParts {
12
+ year: number;
13
+ month: number;
14
+ day: number;
15
+ hour: number;
16
+ minute: number;
17
+ weekday: number;
18
+ }
19
+ /** The wall-clock parts of instant `ms` in `timeZone`. */
20
+ export declare function zonedParts(ms: number, timeZone: string): ZonedParts;
21
+ /** The day instant `ms` falls on in `timeZone`. */
22
+ export declare function dayKeyOf(ms: number, timeZone: string): DayKey;
23
+ /** Minutes since midnight of instant `ms` in `timeZone` (0–1439). */
24
+ export declare function minuteOfDay(ms: number, timeZone: string): number;
25
+ /** A day's year, month (1–12) and day of month. */
26
+ export declare function parseDayKey(key: DayKey): {
27
+ year: number;
28
+ month: number;
29
+ day: number;
30
+ };
31
+ /** The day `n` days after `key` (negative: before). */
32
+ export declare const addDays: (key: DayKey, n: number) => DayKey;
33
+ /** The same day of the month `n` months later, kept inside a shorter month (Jan 31 + 1 → Feb 28). */
34
+ export declare function addMonths(key: DayKey, n: number): DayKey;
35
+ /** The weekday of a day (0 = Sunday … 6 = Saturday). */
36
+ export declare const weekdayOf: (key: DayKey) => number;
37
+ /** Whole days from `a` to `b` (negative when `b` is earlier). */
38
+ export declare const daysBetween: (a: DayKey, b: DayKey) => number;
39
+ /** The first day of the week holding `key`; weeks start on `weekStartsOn` (1 = Monday, the default). */
40
+ export declare function startOfWeek(key: DayKey, weekStartsOn?: number): DayKey;
41
+ /** The 7 days of the week holding `key`. */
42
+ export declare function weekDays(key: DayKey, weekStartsOn?: number): DayKey[];
43
+ /** The first day of the month holding `key`. */
44
+ export declare const startOfMonth: (key: DayKey) => DayKey;
45
+ /**
46
+ * The month holding `key` as whole weeks (4 to 6 rows of 7 days), starting on `weekStartsOn`; the
47
+ * first and last rows include days of the months around it, as a wall calendar shows them.
48
+ */
49
+ export declare function monthGrid(key: DayKey, weekStartsOn?: number): DayKey[][];
50
+ /**
51
+ * The instant when `timeZone`'s clock shows `minutes` past midnight on day `key` (minutes may pass
52
+ * 1440: the next day). A wall time skipped by a daylight-saving jump resolves to the instant after it.
53
+ */
54
+ export declare function zonedTime(key: DayKey, minutes: number, timeZone: string): number;
55
+ /** The instant day `key` starts in `timeZone`. */
56
+ export declare const startOfDay: (key: DayKey, timeZone: string) => number;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Calendar date maths, pure and headless (no DOM): the calendar and the booking slots run on it,
3
+ * and a site's server can import it too. Days are `DayKey` strings ('YYYY-MM-DD') so they can be
4
+ * compared and stored as text; instants are epoch milliseconds. Wall-clock times are read in an
5
+ * IANA time zone through `Intl`, so the same code shows India (no daylight saving) or any zone that
6
+ * has it.
7
+ */
8
+ const formatters = new Map();
9
+ const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
10
+ const pad = (n) => String(n).padStart(2, '0');
11
+ function partsFormatter(timeZone) {
12
+ let formatter = formatters.get(timeZone);
13
+ if (!formatter) {
14
+ formatter = new Intl.DateTimeFormat('en-US', {
15
+ timeZone, hourCycle: 'h23', weekday: 'short',
16
+ year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit',
17
+ });
18
+ formatters.set(timeZone, formatter);
19
+ }
20
+ return formatter;
21
+ }
22
+ /** The wall-clock parts of instant `ms` in `timeZone`. */
23
+ export function zonedParts(ms, timeZone) {
24
+ const parts = {};
25
+ for (const part of partsFormatter(timeZone).formatToParts(new Date(ms)))
26
+ parts[part.type] = part.value;
27
+ return {
28
+ year: Number(parts.year), month: Number(parts.month), day: Number(parts.day),
29
+ hour: Number(parts.hour) % 24, minute: Number(parts.minute), weekday: WEEKDAYS.indexOf(parts.weekday ?? ''),
30
+ };
31
+ }
32
+ /** The day instant `ms` falls on in `timeZone`. */
33
+ export function dayKeyOf(ms, timeZone) {
34
+ const { year, month, day } = zonedParts(ms, timeZone);
35
+ return `${year}-${pad(month)}-${pad(day)}`;
36
+ }
37
+ /** Minutes since midnight of instant `ms` in `timeZone` (0–1439). */
38
+ export function minuteOfDay(ms, timeZone) {
39
+ const { hour, minute } = zonedParts(ms, timeZone);
40
+ return hour * 60 + minute;
41
+ }
42
+ /** A day's year, month (1–12) and day of month. */
43
+ export function parseDayKey(key) {
44
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(key);
45
+ if (!match)
46
+ throw new Error(`Not a day (YYYY-MM-DD): ${key}`);
47
+ return { year: Number(match[1]), month: Number(match[2]), day: Number(match[3]) };
48
+ }
49
+ const fromUtc = (ms) => new Date(ms).toISOString().slice(0, 10);
50
+ const utcNoon = (key) => {
51
+ const { year, month, day } = parseDayKey(key);
52
+ return Date.UTC(year, month - 1, day, 12);
53
+ };
54
+ /** The day `n` days after `key` (negative: before). */
55
+ export const addDays = (key, n) => fromUtc(utcNoon(key) + n * 86_400_000);
56
+ /** The same day of the month `n` months later, kept inside a shorter month (Jan 31 + 1 → Feb 28). */
57
+ export function addMonths(key, n) {
58
+ const { year, month, day } = parseDayKey(key);
59
+ const first = new Date(Date.UTC(year, month - 1 + n, 1, 12));
60
+ const last = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0, 12)).getUTCDate();
61
+ first.setUTCDate(Math.min(day, last));
62
+ return fromUtc(first.getTime());
63
+ }
64
+ /** The weekday of a day (0 = Sunday … 6 = Saturday). */
65
+ export const weekdayOf = (key) => new Date(utcNoon(key)).getUTCDay();
66
+ /** Whole days from `a` to `b` (negative when `b` is earlier). */
67
+ export const daysBetween = (a, b) => Math.round((utcNoon(b) - utcNoon(a)) / 86_400_000);
68
+ /** The first day of the week holding `key`; weeks start on `weekStartsOn` (1 = Monday, the default). */
69
+ export function startOfWeek(key, weekStartsOn = 1) {
70
+ return addDays(key, -((weekdayOf(key) - weekStartsOn + 7) % 7));
71
+ }
72
+ /** The 7 days of the week holding `key`. */
73
+ export function weekDays(key, weekStartsOn = 1) {
74
+ const first = startOfWeek(key, weekStartsOn);
75
+ return Array.from({ length: 7 }, (_, i) => addDays(first, i));
76
+ }
77
+ /** The first day of the month holding `key`. */
78
+ export const startOfMonth = (key) => `${key.slice(0, 8)}01`;
79
+ /**
80
+ * The month holding `key` as whole weeks (4 to 6 rows of 7 days), starting on `weekStartsOn`; the
81
+ * first and last rows include days of the months around it, as a wall calendar shows them.
82
+ */
83
+ export function monthGrid(key, weekStartsOn = 1) {
84
+ const first = startOfMonth(key);
85
+ const last = addDays(addMonths(first, 1), -1);
86
+ const weeks = [];
87
+ for (let start = startOfWeek(first, weekStartsOn); start <= last; start = addDays(start, 7)) {
88
+ weeks.push(Array.from({ length: 7 }, (_, i) => addDays(start, i)));
89
+ }
90
+ return weeks;
91
+ }
92
+ /** How far `timeZone`'s clock is ahead of UTC at instant `ms`, in milliseconds. */
93
+ function offsetAt(ms, timeZone) {
94
+ const p = zonedParts(ms, timeZone);
95
+ return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute) - Math.floor(ms / 60_000) * 60_000;
96
+ }
97
+ /**
98
+ * The instant when `timeZone`'s clock shows `minutes` past midnight on day `key` (minutes may pass
99
+ * 1440: the next day). A wall time skipped by a daylight-saving jump resolves to the instant after it.
100
+ */
101
+ export function zonedTime(key, minutes, timeZone) {
102
+ const { year, month, day } = parseDayKey(key);
103
+ const wall = Date.UTC(year, month - 1, day, 0, minutes);
104
+ const first = wall - offsetAt(wall, timeZone);
105
+ const second = wall - offsetAt(first, timeZone);
106
+ return second === first ? first : Math.max(first, second);
107
+ }
108
+ /** The instant day `key` starts in `timeZone`. */
109
+ export const startOfDay = (key, timeZone) => zonedTime(key, 0, timeZone);
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Where events go on the calendar, pure and headless: which events touch a day, and in the day and
3
+ * week views, each event's vertical span and its column when events overlap (side by side, as
4
+ * Outlook draws them). The calendar view (calendar.ts) turns these numbers into positions.
5
+ */
6
+ import { type DayKey } from './dates.js';
7
+ import { type Interval } from './slots.js';
8
+ /**
9
+ * An event to show. `tone` picks its colour (`--cal-tone-<tone>` in css/calendar.css: event,
10
+ * available, open, pending, confirmed, declined, or a site's own); `data` is the caller's own.
11
+ */
12
+ export interface CalendarEvent extends Interval {
13
+ id: string;
14
+ title: string;
15
+ subtitle?: string;
16
+ tone?: string;
17
+ data?: unknown;
18
+ }
19
+ /** An event's piece on one day of the time grid. */
20
+ export interface DaySegment {
21
+ event: CalendarEvent;
22
+ /** Minutes from midnight where the piece starts and ends on this day (0–1440). */
23
+ top: number;
24
+ bottom: number;
25
+ /** Its column among the events it overlaps, and how many columns they need. */
26
+ column: number;
27
+ columns: number;
28
+ /** The event started on an earlier day / goes on to a later day. */
29
+ continuesBefore: boolean;
30
+ continuesAfter: boolean;
31
+ }
32
+ /** The span of day `key` in `timeZone`. */
33
+ export declare const daySpan: (key: DayKey, timeZone: string) => Interval;
34
+ /** The events that touch day `key`, in start order (longer first on a tie). */
35
+ export declare function eventsOnDay(events: readonly CalendarEvent[], key: DayKey, timeZone: string): CalendarEvent[];
36
+ /**
37
+ * The time-grid pieces for day `key`: each event clipped to the day, and overlapping events split
38
+ * into columns (an event takes the first column free at its start; a group of events that overlap
39
+ * each other, directly or through others, shares one column count).
40
+ */
41
+ export declare function layoutDay(events: readonly CalendarEvent[], key: DayKey, timeZone: string): DaySegment[];
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Where events go on the calendar, pure and headless: which events touch a day, and in the day and
3
+ * week views, each event's vertical span and its column when events overlap (side by side, as
4
+ * Outlook draws them). The calendar view (calendar.ts) turns these numbers into positions.
5
+ */
6
+ import { addDays, startOfDay, minuteOfDay } from './dates.js';
7
+ import { overlaps } from './slots.js';
8
+ /** The span of day `key` in `timeZone`. */
9
+ export const daySpan = (key, timeZone) => ({
10
+ start: startOfDay(key, timeZone),
11
+ end: startOfDay(addDays(key, 1), timeZone),
12
+ });
13
+ /** The events that touch day `key`, in start order (longer first on a tie). */
14
+ export function eventsOnDay(events, key, timeZone) {
15
+ const span = daySpan(key, timeZone);
16
+ return events
17
+ .filter((event) => overlaps(event, span))
18
+ .sort((a, b) => a.start - b.start || b.end - a.end);
19
+ }
20
+ /**
21
+ * The time-grid pieces for day `key`: each event clipped to the day, and overlapping events split
22
+ * into columns (an event takes the first column free at its start; a group of events that overlap
23
+ * each other, directly or through others, shares one column count).
24
+ */
25
+ export function layoutDay(events, key, timeZone) {
26
+ const span = daySpan(key, timeZone);
27
+ const minutesOf = (ms) => (ms <= span.start ? 0 : ms >= span.end ? 1440 : minuteOfDay(ms, timeZone));
28
+ const segments = [];
29
+ let group = [];
30
+ let groupEnd = -Infinity;
31
+ const closeGroup = () => {
32
+ const columns = Math.max(1, ...group.map((s) => s.column + 1));
33
+ for (const segment of group)
34
+ segment.columns = columns;
35
+ group = [];
36
+ };
37
+ for (const event of eventsOnDay(events, key, timeZone)) {
38
+ const top = minutesOf(event.start);
39
+ // A piece is at least 15 minutes tall, so a short event stays clickable.
40
+ const bottom = Math.max(minutesOf(event.end), Math.min(1440, top + 15));
41
+ if (top >= groupEnd)
42
+ closeGroup();
43
+ const taken = new Set(group.filter((s) => s.bottom > top).map((s) => s.column));
44
+ let column = 0;
45
+ while (taken.has(column))
46
+ column++;
47
+ const segment = {
48
+ event, top, bottom, column, columns: 1,
49
+ continuesBefore: event.start < span.start, continuesAfter: event.end > span.end,
50
+ };
51
+ group.push(segment);
52
+ segments.push(segment);
53
+ groupEnd = Math.max(groupEnd, bottom);
54
+ }
55
+ closeGroup();
56
+ return segments;
57
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Booking slots, pure and headless: a person's available blocks (one-off or repeating weekly)
3
+ * expanded into dated occurrences, then cut into bookable slots of a given length, minus the times
4
+ * already taken. The booking calendar shows these to a student, and a site's server imports the
5
+ * same functions to check that a requested slot is really open (one rule, one copy).
6
+ */
7
+ import { type DayKey } from './dates.js';
8
+ /** A span of time: epoch milliseconds, `end` exclusive. */
9
+ export interface Interval {
10
+ start: number;
11
+ end: number;
12
+ }
13
+ /**
14
+ * An available block. With `repeatWeekly` it comes back every week at the same wall-clock time
15
+ * (in the calendar's time zone) from its first day until `until` (a day, inclusive; none: forever).
16
+ */
17
+ export interface Availability extends Interval {
18
+ id: string;
19
+ repeatWeekly?: boolean;
20
+ until?: DayKey | null;
21
+ }
22
+ /** One dated occurrence of an available block. */
23
+ export interface Occurrence extends Interval {
24
+ id: string;
25
+ }
26
+ /** Whether two spans share any time (touching ends don't count). */
27
+ export declare const overlaps: (a: Interval, b: Interval) => boolean;
28
+ /** Every occurrence of `blocks` that overlaps `range`, in start order. */
29
+ export declare function expandAvailability(blocks: readonly Availability[], range: Interval, timeZone: string): Occurrence[];
30
+ /** What `openSlots` needs. */
31
+ export interface SlotQuery {
32
+ /** The available blocks. */
33
+ availability: readonly Availability[];
34
+ /** Times already taken (pending or confirmed bookings, other events). */
35
+ busy: readonly Interval[];
36
+ /** The session length, in minutes. */
37
+ minutes: number;
38
+ /** Only slots inside this span. */
39
+ range: Interval;
40
+ /** Slots starting before this instant are left out (the past). */
41
+ now: number;
42
+ timeZone: string;
43
+ }
44
+ /**
45
+ * The bookable slots: each occurrence cut from its start into back-to-back slots of `minutes`
46
+ * (a remainder too short for a session is dropped), minus slots that overlap a busy time or start
47
+ * before `now`; in start order, each start once.
48
+ */
49
+ export declare function openSlots(query: SlotQuery): Interval[];
50
+ /** Whether `slot` is exactly one of the open slots (the server's check before taking a booking). */
51
+ export declare function isOpenSlot(slot: Interval, query: Omit<SlotQuery, 'range'>): boolean;