@akshayanimateddsa/site-ui 0.0.0-stage → 0.1.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.
@@ -0,0 +1,291 @@
1
+ /**
2
+ * The booking calendar: the calendar view (calendar.ts) with 1:1 session booking on top, in two
3
+ * modes. **Admin:** drag on the time grid (or "New availability") to add an available block, one-off
4
+ * or repeating weekly; click a block to delete it; set each session kind's length; see the requests
5
+ * and confirm or decline each one. **Student:** pick a session kind, see the open slots (the
6
+ * availability cut to that kind's length, minus taken times: slots.ts) and request one with a note.
7
+ * An admin can preview the student mode (`previewStudent`). Everything it shows comes from the
8
+ * site's `load()`, and every change goes through the site's callbacks, which call the site's own
9
+ * server; this module stores nothing. Dialogs: dialog.ts. Styles: css/calendar.css, css/dialog.css.
10
+ */
11
+ import { append, el } from '../dom.js';
12
+ import { openDialog } from '../dialog.js';
13
+ import { createCalendar } from './calendar.js';
14
+ import { dayKeyOf, minuteOfDay, zonedTime } from './dates.js';
15
+ import { expandAvailability, openSlots } from './slots.js';
16
+ /** The longest note a student can send. */
17
+ export const NOTE_MAX = 500;
18
+ const hhmm = (minutes) => `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
19
+ const minutesOf = (value) => {
20
+ const [h = 'x', m = 'x'] = value.split(':');
21
+ return Number(h) * 60 + Number(m);
22
+ };
23
+ /** Mounts a booking calendar in `host` (its content is replaced). */
24
+ export function createBookingCalendar(host, options) {
25
+ const { timeZone } = options;
26
+ const now = options.now ?? Date.now;
27
+ let mode = options.mode;
28
+ let data = null;
29
+ let kindId = null; // the student's chosen session kind
30
+ const status = el('p', { class: 'ui-status', role: 'status' }, 'Loading…');
31
+ const panels = el('div', { class: 'bk-panels' });
32
+ const modeSwitch = el('div', { class: 'cal-views bk-mode', role: 'group', 'aria-label': 'Show as' });
33
+ const newButton = el('button', { type: 'button', class: 'cal-btn cal-btn--primary bk-new', onclick: () => availabilityDialog(null) }, '+ New availability');
34
+ const calendar = createCalendar(host, {
35
+ ...options,
36
+ onRangeChange: () => refresh(),
37
+ onSelectEvent: (event) => select(event),
38
+ onCreate: (span) => {
39
+ if (mode === 'admin')
40
+ availabilityDialog(span);
41
+ },
42
+ });
43
+ calendar.element.classList.add('bk');
44
+ append(calendar.toolbarEnd, newButton, modeSwitch);
45
+ append(calendar.sidebar, status, panels);
46
+ /* ---------- Formatting ---------- */
47
+ const whenFormatter = new Intl.DateTimeFormat(options.locale, { timeZone, weekday: 'short', day: 'numeric', month: 'short' });
48
+ const timeFormatter = new Intl.DateTimeFormat(options.locale, { timeZone, hour: 'numeric', minute: '2-digit' });
49
+ const when = (span) => `${whenFormatter.format(new Date(span.start))}, ${timeFormatter.format(new Date(span.start))} – ${timeFormatter.format(new Date(span.end))}`;
50
+ const kindName = (id) => data?.kinds.find((k) => k.id === id)?.name ?? id;
51
+ const say = (message) => options.notify?.(message);
52
+ /* ---------- Events for what is on screen ---------- */
53
+ function eventsFor(range) {
54
+ if (!data)
55
+ return [];
56
+ const live = data.requests.filter((r) => r.status !== 'declined');
57
+ if (mode === 'admin') {
58
+ const blocks = new Map(data.availability.map((b) => [b.id, b]));
59
+ return [
60
+ ...expandAvailability(data.availability, range, timeZone).map((o) => ({
61
+ id: `a:${o.id}:${o.start}`, start: o.start, end: o.end, title: 'Available', tone: 'available',
62
+ ...(blocks.get(o.id)?.repeatWeekly ? { subtitle: 'Every week' } : {}),
63
+ data: { availability: blocks.get(o.id), occurrence: o },
64
+ })),
65
+ ...live.map((r) => ({
66
+ id: `r:${r.id}`, start: r.start, end: r.end, tone: r.status,
67
+ title: `${r.status === 'pending' ? 'Request' : 'Booked'}: ${kindName(r.kind)}`,
68
+ ...(r.who ? { subtitle: r.who } : {}),
69
+ data: { request: r },
70
+ })),
71
+ ];
72
+ }
73
+ const kind = data.kinds.find((k) => k.id === kindId);
74
+ const slots = kind?.minutes
75
+ ? openSlots({ availability: data.availability, busy: live, minutes: kind.minutes, range, now: now(), timeZone })
76
+ : [];
77
+ return [
78
+ ...slots.map((s) => ({ id: `s:${s.start}`, start: s.start, end: s.end, title: 'Open', subtitle: kind?.name ?? '', tone: 'open', data: { slot: s } })),
79
+ ...live.filter((r) => r.mine).map((r) => ({
80
+ id: `r:${r.id}`, start: r.start, end: r.end, tone: r.status,
81
+ title: `${r.status === 'pending' ? 'Requested' : 'Booked'}: ${kindName(r.kind)}`, data: { request: r },
82
+ })),
83
+ ];
84
+ }
85
+ function refresh() {
86
+ calendar.setEvents(eventsFor(calendar.range()));
87
+ renderPanels();
88
+ }
89
+ async function reload() {
90
+ try {
91
+ data = await options.load(mode);
92
+ status.textContent = '';
93
+ status.hidden = true;
94
+ const bookable = data.kinds.filter((k) => k.minutes);
95
+ if (!bookable.some((k) => k.id === kindId))
96
+ kindId = bookable[0]?.id ?? null;
97
+ }
98
+ catch (problem) {
99
+ status.textContent = problem instanceof Error ? problem.message : String(problem);
100
+ status.hidden = false;
101
+ }
102
+ refresh();
103
+ }
104
+ /** Runs a change, then reloads and says `done`; a failure is thrown on to the dialog that shows it. */
105
+ async function change(action, done) {
106
+ if (!action)
107
+ throw new Error('This action is not available here.');
108
+ await action();
109
+ say(done);
110
+ await reload();
111
+ }
112
+ /* ---------- The sidebar panels ---------- */
113
+ function renderPanels() {
114
+ newButton.hidden = mode !== 'admin';
115
+ modeSwitch.hidden = !(options.mode === 'admin' && options.previewStudent);
116
+ modeSwitch.replaceChildren(...['admin', 'student'].map((m) => el('button', { type: 'button', class: 'cal-view-btn', 'aria-pressed': String(mode === m), onclick: () => setMode(m) }, m === 'admin' ? 'My view' : 'Student view')));
117
+ if (!data) {
118
+ panels.replaceChildren();
119
+ return;
120
+ }
121
+ panels.replaceChildren(...(mode === 'admin' ? adminPanels(data) : studentPanels(data)));
122
+ }
123
+ function panel(title, ...children) {
124
+ return el('section', { class: 'bk-panel' }, el('h3', { class: 'bk-panel-title' }, title), ...children);
125
+ }
126
+ function requestList(requests, empty) {
127
+ if (!requests.length)
128
+ return el('p', { class: 'bk-empty' }, empty);
129
+ return el('ul', { class: 'bk-list' }, ...requests.map((r) => el('li', {}, el('button', { type: 'button', class: 'bk-item', 'data-tone': r.status, onclick: () => { calendar.goTo(dayKeyOf(r.start, timeZone)); requestDialog(r); } }, el('span', { class: 'bk-item-when' }, when(r)), el('span', { class: 'bk-item-what' }, [kindName(r.kind), r.who].filter(Boolean).join(' · ')), mode === 'student' ? el('span', { class: 'bk-item-status' }, r.status) : null))));
130
+ }
131
+ function adminPanels(current) {
132
+ const lengths = el('form', { class: 'bk-lengths' });
133
+ for (const kind of current.kinds) {
134
+ const input = el('input', { type: 'number', name: kind.id, min: 15, max: 240, step: 5, placeholder: 'not set', value: kind.minutes ?? '', 'aria-label': `${kind.name} length in minutes` });
135
+ append(lengths, el('label', { class: 'bk-length' }, el('span', {}, kind.name), input, el('span', { class: 'bk-unit' }, 'min')));
136
+ }
137
+ append(lengths, el('button', { type: 'submit', class: 'cal-btn' }, 'Save lengths'));
138
+ lengths.addEventListener('submit', (event) => {
139
+ event.preventDefault();
140
+ const form = new FormData(lengths);
141
+ const changed = current.kinds.filter((k) => form.get(k.id) !== '' && Number(form.get(k.id)) !== k.minutes);
142
+ void (async () => {
143
+ try {
144
+ for (const kind of changed)
145
+ await options.saveMinutes?.(kind.id, Number(form.get(kind.id)));
146
+ if (changed.length)
147
+ say('Session lengths saved.');
148
+ await reload();
149
+ }
150
+ catch (problem) {
151
+ status.textContent = problem instanceof Error ? problem.message : String(problem);
152
+ status.hidden = false;
153
+ }
154
+ })();
155
+ });
156
+ const pending = current.requests.filter((r) => r.status === 'pending').sort((a, b) => a.start - b.start);
157
+ const upcoming = current.requests.filter((r) => r.status === 'confirmed' && r.end > now()).sort((a, b) => a.start - b.start);
158
+ return [
159
+ panel(`Requests (${pending.length})`, requestList(pending, 'No requests waiting.')),
160
+ panel('Booked', requestList(upcoming, 'Nothing booked yet.')),
161
+ panel('Session lengths', lengths),
162
+ ];
163
+ }
164
+ function studentPanels(current) {
165
+ const bookable = current.kinds.filter((k) => k.minutes);
166
+ const kinds = bookable.length
167
+ ? el('div', { class: 'bk-kinds', role: 'radiogroup', 'aria-label': 'Session' }, ...bookable.map((k) => {
168
+ const radio = el('input', { type: 'radio', name: 'bk-kind', value: k.id, checked: k.id === kindId });
169
+ radio.addEventListener('change', () => { kindId = k.id; refresh(); });
170
+ return el('label', { class: 'bk-kind' }, radio, el('span', {}, k.name), el('small', {}, `${k.minutes} min`));
171
+ }))
172
+ : el('p', { class: 'bk-empty' }, "Booking isn't open yet.");
173
+ const mine = current.requests.filter((r) => r.mine && r.end > now()).sort((a, b) => a.start - b.start);
174
+ return [
175
+ panel('Book a session', kinds, bookable.length ? el('p', { class: 'bk-hint' }, 'Pick an open slot on the calendar.') : ''),
176
+ panel('Your requests', requestList(mine, 'None yet.')),
177
+ ];
178
+ }
179
+ /* ---------- Clicking an event ---------- */
180
+ function select(event) {
181
+ const info = event.data;
182
+ if (info?.request)
183
+ requestDialog(info.request);
184
+ else if (info?.availability && info.occurrence)
185
+ blockDialog(info.availability, info.occurrence);
186
+ else if (info?.slot)
187
+ slotDialog(info.slot);
188
+ }
189
+ function details(rows) {
190
+ return el('dl', { class: 'bk-details' }, ...rows.filter(([, v]) => v).flatMap(([k, v]) => [el('dt', {}, k), el('dd', {}, v ?? '')]));
191
+ }
192
+ /** Add an available block: from a dragged span, or blank (today, 10:00–11:00). */
193
+ function availabilityDialog(span) {
194
+ const start = span?.start ?? zonedTime(dayKeyOf(now(), timeZone), 600, timeZone);
195
+ const end = span?.end ?? start + 3_600_000;
196
+ const day = el('input', { type: 'date', name: 'day', required: true, value: dayKeyOf(start, timeZone) });
197
+ const from = el('input', { type: 'time', name: 'from', required: true, step: 300, value: hhmm(minuteOfDay(start, timeZone)) });
198
+ const to = el('input', { type: 'time', name: 'to', required: true, step: 300, value: hhmm(minuteOfDay(end, timeZone) || 1440) });
199
+ const repeat = el('input', { type: 'checkbox', name: 'repeat' });
200
+ const until = el('input', { type: 'date', name: 'until' });
201
+ const untilRow = el('label', { class: 'ui-field', hidden: true }, el('span', {}, 'Until (optional)'), until);
202
+ repeat.addEventListener('change', () => { untilRow.hidden = !repeat.checked; });
203
+ const body = el('div', { class: 'ui-form' }, el('label', { class: 'ui-field' }, el('span', {}, 'Day'), day), el('div', { class: 'ui-row' }, el('label', { class: 'ui-field' }, el('span', {}, 'From'), from), el('label', { class: 'ui-field' }, el('span', {}, 'To'), to)), el('label', { class: 'ui-check' }, repeat, el('span', {}, 'Repeat every week')), untilRow);
204
+ openDialog({
205
+ title: 'New availability',
206
+ body,
207
+ actions: [
208
+ { label: 'Cancel' },
209
+ {
210
+ label: 'Add', kind: 'primary',
211
+ run: () => {
212
+ const startMinute = minutesOf(from.value);
213
+ const endMinute = minutesOf(to.value) || 1440;
214
+ if (!day.value || Number.isNaN(startMinute) || Number.isNaN(endMinute))
215
+ throw new Error('Fill in the day and both times.');
216
+ if (endMinute <= startMinute)
217
+ throw new Error('The end time must be after the start time.');
218
+ if (repeat.checked && until.value && until.value < day.value)
219
+ throw new Error('"Until" must be on or after the day.');
220
+ return change(() => options.addAvailability?.({
221
+ start: zonedTime(day.value, startMinute, timeZone), end: zonedTime(day.value, endMinute, timeZone),
222
+ repeatWeekly: repeat.checked, until: repeat.checked && until.value ? until.value : null,
223
+ }) ?? Promise.reject(new Error('Adding availability is not available here.')), 'Availability added.');
224
+ },
225
+ },
226
+ ],
227
+ });
228
+ }
229
+ function blockDialog(block, occurrence) {
230
+ const weekday = new Intl.DateTimeFormat(options.locale, { timeZone, weekday: 'long' }).format(new Date(block.start));
231
+ openDialog({
232
+ title: 'Available',
233
+ body: details([
234
+ ['When', when(occurrence)],
235
+ ['Repeats', block.repeatWeekly ? `Every ${weekday}${block.until ? ` until ${block.until}` : ''}` : 'No'],
236
+ ]),
237
+ actions: [
238
+ { label: 'Close' },
239
+ {
240
+ label: block.repeatWeekly ? 'Delete every week' : 'Delete', kind: 'danger',
241
+ run: () => change(options.deleteAvailability && (() => options.deleteAvailability?.(block.id) ?? Promise.resolve()), 'Availability deleted.'),
242
+ },
243
+ ],
244
+ });
245
+ }
246
+ function requestDialog(request) {
247
+ const decide = (to, done) => () => change(options.decide && (() => options.decide?.(request.id, to) ?? Promise.resolve()), done);
248
+ const actions = mode === 'admin' && request.status === 'pending'
249
+ ? [{ label: 'Close' }, { label: 'Decline', kind: 'danger', run: decide('declined', 'Request declined.') }, { label: 'Confirm', kind: 'primary', run: decide('confirmed', 'Booking confirmed.') }]
250
+ : mode === 'admin' && request.status === 'confirmed'
251
+ ? [{ label: 'Close' }, { label: 'Cancel booking', kind: 'danger', run: decide('declined', 'Booking cancelled.') }]
252
+ : [{ label: 'Close' }];
253
+ openDialog({
254
+ title: `${kindName(request.kind)} · ${request.status}`,
255
+ body: details([['When', when(request)], ['Who', request.who], ['Contact', request.contact], ['Note', request.note]]),
256
+ actions,
257
+ });
258
+ }
259
+ function slotDialog(slot) {
260
+ const kind = data?.kinds.find((k) => k.id === kindId);
261
+ if (!kind)
262
+ return;
263
+ const note = el('textarea', { name: 'note', rows: 4, maxlength: NOTE_MAX, placeholder: 'What would you like to cover? (optional)' });
264
+ openDialog({
265
+ title: `Request ${kind.name}`,
266
+ body: el('div', { class: 'ui-form' }, details([['When', when(slot)], ['Length', `${kind.minutes} min`]]), el('label', { class: 'ui-field' }, el('span', {}, 'Note'), note)),
267
+ actions: [
268
+ { label: 'Cancel' },
269
+ {
270
+ label: 'Send request', kind: 'primary',
271
+ run: () => change(options.request && (() => options.request?.({ kind: kind.id, start: slot.start, end: slot.end, note: note.value.trim() }) ?? Promise.resolve()), "Request sent. You'll see it here once it's confirmed."),
272
+ },
273
+ ],
274
+ });
275
+ }
276
+ function setMode(next) {
277
+ mode = next;
278
+ calendar.element.dataset.mode = mode;
279
+ refresh();
280
+ void reload();
281
+ }
282
+ calendar.element.dataset.mode = mode;
283
+ void reload();
284
+ return {
285
+ calendar,
286
+ mode: () => mode,
287
+ setMode,
288
+ reload,
289
+ destroy: () => calendar.destroy(),
290
+ };
291
+ }
@@ -0,0 +1,63 @@
1
+ import { type DayKey } from './dates.js';
2
+ import { type CalendarEvent } from './layout.js';
3
+ import type { Interval } from './slots.js';
4
+ /** The three views. */
5
+ export type CalendarView = 'day' | 'week' | 'month';
6
+ /** The views in the order the switch shows them. */
7
+ export declare const CALENDAR_VIEWS: readonly CalendarView[];
8
+ /** What is on screen: the view, its first and last day (inclusive) and the instants they span. */
9
+ export interface CalendarRange extends Interval {
10
+ view: CalendarView;
11
+ from: DayKey;
12
+ to: DayKey;
13
+ }
14
+ /** Settings for `createCalendar`; only `timeZone` is required. */
15
+ export interface CalendarOptions {
16
+ /** The IANA time zone every day and time is shown in (e.g. 'Asia/Kolkata'). */
17
+ timeZone: string;
18
+ /** The locale for names and times (default: the browser's). */
19
+ locale?: string;
20
+ /** The view to open in (default 'week'; 'day' on a phone-width screen). */
21
+ view?: CalendarView;
22
+ /** The day to open on (default today). */
23
+ date?: DayKey;
24
+ /** The first day of the week (0 = Sunday, 1 = Monday, the default). */
25
+ weekStartsOn?: number;
26
+ /** The hour the time grid scrolls to when shown (default 8). */
27
+ scrollToHour?: number;
28
+ /** The step a drag on the time grid snaps to, in minutes (default 30). */
29
+ snapMinutes?: number;
30
+ /** The clock (default Date.now); tests and previews can pass their own. */
31
+ now?: () => number;
32
+ /** Events to show from the start. */
33
+ events?: CalendarEvent[];
34
+ /** Called with what is on screen: once at the start and after every move or view change. */
35
+ onRangeChange?: (range: CalendarRange) => void;
36
+ /** Called when an event is clicked (or chosen with Enter / Space). */
37
+ onSelectEvent?: (event: CalendarEvent, element: HTMLElement) => void;
38
+ /** Set it to let the viewer drag across the time grid to pick a span; called with that span. */
39
+ onCreate?: (span: Interval) => void;
40
+ }
41
+ /** A mounted calendar. */
42
+ export interface Calendar {
43
+ /** The calendar's root element (`.cal`). */
44
+ element: HTMLElement;
45
+ /** A slot under the small month for the site's own panels. */
46
+ sidebar: HTMLElement;
47
+ /** A slot in the toolbar, before the view switch, for the site's own buttons. */
48
+ toolbarEnd: HTMLElement;
49
+ /** Replaces the events shown. */
50
+ setEvents: (events: CalendarEvent[]) => void;
51
+ setView: (view: CalendarView) => void;
52
+ /** Shows the range holding `day`. */
53
+ goTo: (day: DayKey) => void;
54
+ today: () => void;
55
+ next: () => void;
56
+ prev: () => void;
57
+ /** What is on screen now. */
58
+ range: () => CalendarRange;
59
+ /** Stops the clock and removes the calendar. */
60
+ destroy: () => void;
61
+ }
62
+ /** Mounts a calendar in `host` (its content is replaced). */
63
+ export declare function createCalendar(host: HTMLElement, options: CalendarOptions): Calendar;