@gecko-ui-kit/components 0.0.0-stage → 0.20.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,523 @@
1
+ /* Month calendar with events: a month grid where each day shows its events as small chips, and an
2
+ event that runs over several days draws one bar per week across those days. A day with more
3
+ events than fit shows “+2 more”, which opens a small list beside the day.
4
+ How it moves: going to another month slides the weeks out and the new ones in from the side you
5
+ travel to, while the month title ticks up or down like a counter and the grid grows or shrinks
6
+ to the new number of weeks. Event chips drop in one after another, and today wears a ring that
7
+ pulses once. With draggable on, an event lifts as you drag it (on touch: press and hold first),
8
+ the days it would cover light up, and on release it lands on its new day with a small squash.
9
+ Keyboard: the ARIA grid pattern — arrow keys move day by day (into the next or last month),
10
+ Home / End to the start or end of the week, Page Up / Page Down month by month, Enter picks a day,
11
+ and Alt + arrow keys move a focused event. */
12
+ import * as M from '@gecko-ui-kit/motion';
13
+ import { icon } from '@gecko-ui-kit/icons';
14
+ import { esc } from '../index.js';
15
+
16
+ const { g, RM, $$ } = M;
17
+ const DAY = 864e5;
18
+ /** 'YYYY-MM-DD' (or a Date) → days since 1970. Dates only: the time of day is ignored. */
19
+ const toN = (v) => {
20
+ if (v == null || v === '') return null;
21
+ if (typeof v === 'number') return Math.floor(v);
22
+ if (v instanceof Date) return Number.isNaN(+v) ? null : Date.UTC(v.getFullYear(), v.getMonth(), v.getDate()) / DAY;
23
+ const [y, m, d] = String(v).slice(0, 10).split('-').map(Number);
24
+ return y && m && d ? Date.UTC(y, m - 1, d) / DAY : null;
25
+ };
26
+ const toS = (n) => new Date(n * DAY).toISOString().slice(0, 10);
27
+ const parts = (n) => { const d = new Date(n * DAY); return { y: d.getUTCFullYear(), m: d.getUTCMonth(), d: d.getUTCDate(), w: d.getUTCDay() }; };
28
+ /** Days since 1970 → a local Date at midnight (what the callbacks hand back). */
29
+ const toDate = (n) => { const p = parts(n); return new Date(p.y, p.m, p.d); };
30
+ const monthOf = (n) => { const p = parts(n); return Date.UTC(p.y, p.m, 1) / DAY; };
31
+ const addMonths = (first, k) => { const p = parts(first); return Date.UTC(p.y, p.m + k, 1) / DAY; };
32
+ const daysIn = (first) => { const p = parts(first); return new Date(Date.UTC(p.y, p.m + 1, 0)).getUTCDate(); };
33
+ const fmt = (n, locale, opt) => new Intl.DateTimeFormat(locale, { timeZone: 'UTC', ...opt }).format(new Date(n * DAY));
34
+ /** A moved date in the same shape it came in: a Date keeps its time of day, a string keeps anything after the date. */
35
+ const like = (orig, n) => {
36
+ if (orig instanceof Date) { const d = new Date(orig); const p = parts(n); d.setFullYear(p.y, p.m, p.d); return d; }
37
+ return typeof orig === 'string' ? toS(n) + orig.slice(10) : toS(n);
38
+ };
39
+ const TONES = ['accent', 'good', 'warn', 'bad', 'indigo', 'teal', 'rose', 'amber', 'violet', 'green', 'slate', 'sky'];
40
+ const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
41
+
42
+ const WORDS = {
43
+ label: 'Calendar',
44
+ prev: 'Previous month', next: 'Next month', today: 'Today',
45
+ todayMark: 'today',
46
+ count: (n) => (n === 0 ? 'no events' : n === 1 ? '1 event' : `${n} events`),
47
+ more: (n) => `+${n} more`,
48
+ moreLabel: (n, day) => `${n} more on ${day}`,
49
+ close: 'Close',
50
+ moveHint: 'Alt + arrow keys move it to another day',
51
+ moved: (title, day) => `Moved ${title} to ${day}`,
52
+ };
53
+ let uid = 0;
54
+
55
+ /**
56
+ * const cal = calendar(el, {
57
+ * month: new Date(), // any day in the month to show first (default: value, else today)
58
+ * events: [{ id, title, start: Date | 'YYYY-MM-DD', end, tone: 'accent' | 'good' | 'warn' | 'bad'
59
+ * | 'teal' | 'rose' | 'indigo' | 'amber' | 'violet' | 'green' | 'slate' | 'sky' | any CSS colour,
60
+ * allDay: true, time: '09:30' }], // allDay: false → a dot and the time instead of a bar
61
+ * weekStart: 1, // 1 = Monday, 0 = Sunday
62
+ * locale: 'en', // month and day names through Intl ('th' gives Thai with the Buddhist year)
63
+ * today: new Date(),
64
+ * maxPerDay: 3, // chips shown per day; the rest go under “+2 more”
65
+ * selectable: true, // clicking a day marks it as picked
66
+ * draggable: false, // drag an event to another day (touch: press and hold, then drag)
67
+ * size: '' | 'sm', // sm: short days with thin colour bars instead of titles
68
+ * value: null, // a picked day to start with
69
+ * label: '', // name for screen readers (default words.label)
70
+ * words: { label, prev, next, today, todayMark, count, more, moreLabel, close, moveHint, moved },
71
+ * onMonth(date, cal), onDay(date, events, cal), onEvent(event, cal),
72
+ * onMove(event, newStart, newEnd, cal) // return false to put it back
73
+ * })
74
+ * cal.month · cal.value · cal.events · cal.go(date) · cal.next() · cal.prev() · cal.today() · cal.select(date)
75
+ * cal.setEvents(events) · cal.addEvent(event) · cal.removeEvent(id) · cal.destroy()
76
+ */
77
+ export const calendar = (el, opts = {}) => {
78
+ el = $$(el)[0];
79
+ if (!el) return null;
80
+ const o = { month: null, events: [], weekStart: 1, locale: 'en', today: new Date(), maxPerDay: 3, selectable: true, draggable: false, size: '', value: null, label: '', words: null, onMonth: null, onDay: null, onEvent: null, onMove: null, ...opts };
81
+ const W = { ...WORDS, ...o.words };
82
+ const max = Math.max(1, Math.round(+o.maxPerDay || 3));
83
+ const today = toN(o.today) ?? toN(new Date());
84
+ const ws0 = ((+o.weekStart || 0) % 7 + 7) % 7;
85
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
86
+ const timers = new Set();
87
+ const later = (fn, ms) => { const t = setTimeout(() => { timers.delete(t); fn(); }, ms); timers.add(t); };
88
+ const base = `cal${++uid}`;
89
+
90
+ /* ---------- events: one record per event ---------- */
91
+ let seq = 0, recs = [];
92
+ const norm = (e) => {
93
+ if (!e) return null;
94
+ const s = toN(e.start);
95
+ if (s == null) return null;
96
+ let en = toN(e.end ?? e.start);
97
+ if (en == null || en < s) en = s;
98
+ const allDay = e.allDay !== false;
99
+ let time = e.time ?? '';
100
+ if (!time && !allDay) {
101
+ if (typeof e.start === 'string' && e.start.length > 11) time = e.start.slice(11, 16);
102
+ else if (e.start instanceof Date) time = new Intl.DateTimeFormat(o.locale, { hour: '2-digit', minute: '2-digit' }).format(e.start);
103
+ }
104
+ return { id: String(e.id ?? `${base}-e${++seq}`), ev: e, s, e: en, title: String(e.title ?? ''), tone: e.tone || 'accent', allDay, time: String(time) };
105
+ };
106
+ const normAll = (list) => {
107
+ const seen = new Set();
108
+ return (list || []).map(norm).filter((r) => { if (!r) return false; if (seen.has(r.id)) r.id = `${r.id}~${++seq}`; seen.add(r.id); return true; });
109
+ };
110
+ const byId = (id) => recs.find((r) => r.id === id);
111
+ const long = (n) => fmt(n, o.locale, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
112
+ const dayName = (n) => fmt(n, o.locale, { weekday: 'long', day: 'numeric', month: 'long' });
113
+ const when = (r) => {
114
+ if (r.e === r.s) return dayName(r.s);
115
+ const f = new Intl.DateTimeFormat(o.locale, { day: 'numeric', month: 'long', timeZone: 'UTC' });
116
+ const a = new Date(r.s * DAY), b = new Date(r.e * DAY);
117
+ return f.formatRange ? f.formatRange(a, b) : `${f.format(a)} – ${f.format(b)}`;
118
+ };
119
+ const rank = (r) => (r.e > r.s ? 0 : r.allDay ? 1 : 2);
120
+ const order = (x, y) => rank(x) - rank(y) || (y.e - y.s) - (x.e - x.s) || x.s - y.s || x.time.localeCompare(y.time) || x.title.localeCompare(y.title);
121
+ const dayEvents = (n) => recs.filter((r) => r.s <= n && r.e >= n).sort(order);
122
+ const toneAttr = (r) => (TONES.includes(r.tone) ? { cls: ` cal__ev--${r.tone}`, style: '' }
123
+ : { cls: '', style: /^[#\w\s(),.%-]+$/.test(r.tone) ? `--c:${r.tone};` : '' });
124
+
125
+ /* ---------- state ---------- */
126
+ let sel = toN(o.value);
127
+ let view = monthOf(toN(o.month) ?? sel ?? today);
128
+ let focusN = null, pop = null, popFrom = null, slide = null, dragging = null, suppress = false;
129
+
130
+ const root = document.createElement('div');
131
+ root.className = `cal${o.size === 'sm' ? ' cal--sm' : ''}${o.draggable ? ' cal--drag' : ''}`;
132
+ root.style.setProperty('--cal-max', max);
133
+ const wk = Array.from({ length: 7 }, (_, i) => toN('2024-01-01') + ((ws0 + i + 6) % 7));
134
+ root.innerHTML = `<div class="cal__top"><div class="cal__title" id="${base}-t"></div>`
135
+ + `<button type="button" class="btn btn--sm cal__today">${esc(W.today)}</button>`
136
+ + `<button type="button" class="iconbtn iconbtn--sm cal__prev" aria-label="${esc(W.prev)}">${icon('chevL')}</button>`
137
+ + `<button type="button" class="iconbtn iconbtn--sm cal__next" aria-label="${esc(W.next)}">${icon('chevR')}</button></div>`
138
+ + `<span class="cal__sr" id="${base}-l">${esc(o.label || W.label)}</span>`
139
+ + `<div class="cal__grid" role="grid" aria-labelledby="${base}-l ${base}-t">`
140
+ + `<div class="cal__wk" role="row">${wk.map((n) => `<div class="cal__wd" role="columnheader" aria-label="${esc(fmt(n, o.locale, { weekday: 'long' }))}"><span class="cal__wd-l" aria-hidden="true">${esc(fmt(n, o.locale, { weekday: 'short' }))}</span><span class="cal__wd-s" aria-hidden="true">${esc(fmt(n, o.locale, { weekday: 'narrow' }))}</span></div>`).join('')}</div>`
141
+ + '<div class="cal__vp"></div></div><div class="cal__sr" role="status"></div>';
142
+ el.innerHTML = ''; el.append(root);
143
+ const titleEl = root.querySelector('.cal__title'), vp = root.querySelector('.cal__vp');
144
+ const say = (t) => { root.querySelector('.cal__sr[role="status"]').textContent = t; };
145
+
146
+ /* ---------- the grid ---------- */
147
+ const gridOf = (first) => {
148
+ const lead = (parts(first).w - ws0 + 7) % 7, start = first - lead;
149
+ const weeks = Math.ceil((lead + daysIn(first)) / 7);
150
+ return { start, weeks, end: start + weeks * 7 - 1 };
151
+ };
152
+ /** Events in a week as bars, each on the first lane that is free on all its days. */
153
+ const layout = (ws) => {
154
+ const we = ws + 6, lanes = [];
155
+ const segs = recs.filter((r) => r.s <= we && r.e >= ws).map((r) => ({ r, a: Math.max(r.s, ws), b: Math.min(r.e, we) }))
156
+ .sort((x, y) => x.a - y.a || (y.b - y.a) - (x.b - x.a) || order(x.r, y.r));
157
+ segs.forEach((sg) => {
158
+ for (let k = 0; ; k++) {
159
+ const L = (lanes[k] ||= Array(7).fill(false));
160
+ let free = true;
161
+ for (let c = sg.a - ws; c <= sg.b - ws; c++) if (L[c]) { free = false; break; }
162
+ if (free) { for (let c = sg.a - ws; c <= sg.b - ws; c++) L[c] = true; sg.lane = k; break; }
163
+ }
164
+ });
165
+ return segs;
166
+ };
167
+ const evHTML = (r, { span = 1, lane = 0, contL = false, contR = false, row = false } = {}) => {
168
+ const t = toneAttr(r), bar = r.e > r.s || r.allDay;
169
+ const cls = `cal__ev${t.cls}${bar ? ' is-bar' : ' is-dot'}${span > 1 ? ' is-wide' : ''}${contL ? ' is-cont-l' : ''}${contR ? ' is-cont-r' : ''}${row ? ' is-row' : ''}`;
170
+ const label = `${r.title}, ${r.time ? `${r.time}, ` : ''}${when(r)}`;
171
+ const drag = o.draggable && !row ? ` aria-keyshortcuts="Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown" aria-description="${esc(W.moveHint)}"` : '';
172
+ return `<button type="button" class="${cls}" data-id="${esc(r.id)}" style="${t.style}${row ? '' : `--span:${span};--lane:${lane}`}" tabindex="-1" aria-label="${esc(label)}"${drag}>`
173
+ + `${bar ? '' : '<i class="cal__dot" aria-hidden="true"></i>'}${r.time ? `<time>${esc(r.time)}</time>` : ''}<span class="cal__evt">${esc(r.title)}</span></button>`;
174
+ };
175
+ const weekHTML = (ws) => {
176
+ const segs = layout(ws);
177
+ const cnt = Array(7).fill(0), hid = Array(7).fill(0), at = Array.from({ length: 7 }, () => []);
178
+ segs.forEach((sg) => {
179
+ for (let c = sg.a - ws; c <= sg.b - ws; c++) { cnt[c]++; if (sg.lane >= max) hid[c]++; }
180
+ if (sg.lane < max) at[sg.a - ws].push(sg);
181
+ });
182
+ let h = `<div class="cal__week" role="row" data-n="${ws}">`;
183
+ for (let c = 0; c < 7; c++) {
184
+ const n = ws + c, p = parts(n), out = monthOf(n) !== view, isT = n === today;
185
+ const label = `${long(n)}${isT ? `, ${W.todayMark}` : ''}, ${W.count(cnt[c])}`;
186
+ h += `<div class="cal__cell${out ? ' is-out' : ''}${isT ? ' is-today' : ''}${o.selectable && n === sel ? ' is-sel' : ''}" role="gridcell" data-n="${n}"${o.selectable ? ` aria-selected="${n === sel}"` : ''}>`
187
+ + `<button type="button" class="cal__date" tabindex="-1" aria-label="${esc(label)}"${isT ? ' aria-current="date"' : ''}><span class="cal__dn">${p.d}</span>${p.d === 1 ? `<span class="cal__mo">${esc(fmt(n, o.locale, { month: 'short' }))}</span>` : ''}</button>`
188
+ + at[c].map((sg) => evHTML(sg.r, { span: sg.b - sg.a + 1, lane: sg.lane, contL: sg.a > sg.r.s, contR: sg.b < sg.r.e })).join('')
189
+ + (hid[c] ? `<button type="button" class="cal__more" tabindex="-1" aria-haspopup="dialog" aria-label="${esc(W.moreLabel(hid[c], dayName(n)))}"><span class="cal__more-l">${esc(W.more(hid[c]))}</span><span class="cal__more-s">+${hid[c]}</span></button>` : '')
190
+ + '</div>';
191
+ }
192
+ return `${h}</div>`;
193
+ };
194
+ const weeksHTML = () => { const gd = gridOf(view); return Array.from({ length: gd.weeks }, (_, k) => weekHTML(gd.start + k * 7)).join(''); };
195
+ const weeksEl = () => vp.querySelector('.cal__weeks:not(.is-leaving)');
196
+ const cellOf = (n) => weeksEl()?.querySelector(`.cal__cell[data-n="${n}"]`);
197
+ const dateOf = (n) => cellOf(n)?.querySelector('.cal__date');
198
+ const segsOf = (id) => [...(weeksEl()?.querySelectorAll('.cal__ev') || [])].filter((b) => b.dataset.id === id);
199
+ const segDays = (b) => { const a = +b.closest('.cal__cell').dataset.n; return [a, a + (+b.style.getPropertyValue('--span') || 1) - 1]; };
200
+
201
+ /* ---------- focus: one day (and the events in it) in the Tab order ---------- */
202
+ const roving = () => {
203
+ const box = weeksEl(); if (!box) return;
204
+ const gd = gridOf(view);
205
+ if (focusN == null || focusN < gd.start || focusN > gd.end) focusN = sel != null && monthOf(sel) === view ? sel : monthOf(today) === view ? today : view;
206
+ box.querySelectorAll('.cal__cell').forEach((c) => {
207
+ const mine = +c.dataset.n === focusN;
208
+ c.querySelectorAll('.cal__date, .cal__ev, .cal__more').forEach((b) => { b.tabIndex = mine ? 0 : -1; });
209
+ });
210
+ };
211
+ const focusKey = () => {
212
+ const a = document.activeElement;
213
+ if (!a || !vp.contains(a)) return null;
214
+ const cell = a.closest('.cal__cell');
215
+ return { n: cell ? +cell.dataset.n : null, id: a.classList.contains('cal__ev') ? a.dataset.id : null, more: a.classList.contains('cal__more') };
216
+ };
217
+ const restore = (k) => {
218
+ if (!k) return;
219
+ const t = (k.id && (segsOf(k.id).find((b) => { const [a, b2] = segDays(b); return k.n >= a && k.n <= b2; }) || segsOf(k.id)[0]))
220
+ || (k.more && cellOf(k.n)?.querySelector('.cal__more')) || dateOf(k.n);
221
+ t?.focus();
222
+ };
223
+
224
+ /* ---------- motion ---------- */
225
+ const chipsIn = (box, delay = 0) => {
226
+ if (RM()) return;
227
+ const evs = [...box.querySelectorAll('.cal__ev, .cal__more')];
228
+ if (!evs.length) return;
229
+ const wide = (t) => t.classList.contains('is-wide');
230
+ g.fromTo(evs, { opacity: 0, y: (i, t) => (wide(t) ? 0 : 5), scaleX: (i, t) => (wide(t) ? 0.35 : 1), transformOrigin: '0% 50%' },
231
+ { opacity: 1, y: 0, scaleX: 1, duration: 0.38, ease: 'power3.out', delay, stagger: Math.min(0.022, 0.5 / evs.length), clearProps: 'opacity,transform' });
232
+ };
233
+ const ringToday = (delay = 0.25) => {
234
+ const d = dateOf(today);
235
+ if (!d || RM()) return;
236
+ const ring = document.createElement('span');
237
+ ring.className = 'cal__ring'; ring.setAttribute('aria-hidden', 'true'); d.append(ring);
238
+ g.fromTo(ring, { scale: 0.8, opacity: 0.9 }, { scale: 1.9, opacity: 0, duration: 0.7, delay, ease: 'power2.out', onComplete: () => ring.remove() });
239
+ };
240
+ const popDate = (n) => { const d = dateOf(n); if (d && !RM()) g.fromTo(d, { scale: 0.78 }, { scale: 1, duration: 0.45, ease: 'back.out(3)', clearProps: 'transform' }); };
241
+ const setTitle = (dir) => {
242
+ const text = fmt(view, o.locale, { month: 'long', year: 'numeric' });
243
+ const old = titleEl.querySelector('span:not(.is-old)');
244
+ if (old && old.textContent === text) return;
245
+ const s = document.createElement('span'); s.textContent = text;
246
+ titleEl.querySelectorAll('.is-old').forEach((x) => { g.killTweensOf(x); x.remove(); });
247
+ if (!old || !dir || RM()) { titleEl.replaceChildren(s); return; }
248
+ old.classList.add('is-old'); titleEl.append(s);
249
+ g.to(old, { yPercent: -100 * dir, opacity: 0, duration: 0.28, ease: 'power2.in', onComplete: () => old.remove() });
250
+ g.fromTo(s, { yPercent: 100 * dir, opacity: 0 }, { yPercent: 0, opacity: 1, duration: 0.5, delay: 0.05, ease: 'back.out(1.7)', clearProps: 'transform,opacity' });
251
+ };
252
+ const finishSlide = () => {
253
+ if (!slide) return;
254
+ slide.kill(); slide = null;
255
+ vp.querySelectorAll('.cal__weeks.is-leaving').forEach((x) => x.remove());
256
+ vp.classList.remove('is-sliding');
257
+ g.set(vp, { clearProps: 'height' });
258
+ const box = weeksEl(); if (box) g.set(box, { clearProps: 'transform,opacity' });
259
+ };
260
+
261
+ /** Draw the month. dir = 1 / -1 slides the new weeks in from that side. */
262
+ const render = (dir = 0, focusIt = false) => {
263
+ finishSlide();
264
+ setTitle(dir);
265
+ const old = weeksEl();
266
+ const fresh = document.createElement('div');
267
+ fresh.className = 'cal__weeks'; fresh.setAttribute('role', 'rowgroup');
268
+ fresh.innerHTML = weeksHTML();
269
+ if (old && dir && !RM()) {
270
+ const h0 = vp.offsetHeight, w = vp.offsetWidth;
271
+ old.classList.add('is-leaving'); old.inert = true; old.setAttribute('aria-hidden', 'true'); old.removeAttribute('role');
272
+ vp.classList.add('is-sliding'); vp.append(fresh);
273
+ const h1 = fresh.offsetHeight;
274
+ slide = g.timeline({ onComplete: finishSlide })
275
+ .to(old, { x: -dir * w * 0.32, opacity: 0, duration: 0.3, ease: 'power2.in' }, 0)
276
+ .fromTo(fresh, { x: dir * w * 0.32, opacity: 0 }, { x: 0, opacity: 1, duration: 0.52, ease: 'power3.out' }, 0.08);
277
+ if (h0 !== h1) slide.fromTo(vp, { height: h0 }, { height: h1, duration: 0.5, ease: 'power3.inOut' }, 0);
278
+ chipsIn(fresh, 0.26);
279
+ } else {
280
+ old?.remove(); vp.append(fresh);
281
+ chipsIn(fresh, dir ? 0 : 0.12);
282
+ }
283
+ roving();
284
+ if (focusIt) dateOf(focusN)?.focus({ preventScroll: true }); // the new weeks are still sliding in
285
+ ringToday(dir ? 0.35 : 0.3); // only when today is on show
286
+ };
287
+ /** Rebuild the weeks in place (events changed), keeping focus where it was. */
288
+ const refresh = ({ anim = false } = {}) => {
289
+ finishSlide();
290
+ const box = weeksEl(); if (!box) return;
291
+ const k = focusKey();
292
+ box.innerHTML = weeksHTML();
293
+ roving(); restore(k);
294
+ if (anim) chipsIn(box);
295
+ };
296
+ const setView = (first, { focus = false, dir } = {}) => {
297
+ if (first === view) { roving(); if (focus) dateOf(focusN)?.focus(); return; }
298
+ const d = dir ?? (first > view ? 1 : -1);
299
+ view = first; closeMore(false);
300
+ render(d, focus);
301
+ say(fmt(view, o.locale, { month: 'long', year: 'numeric' }));
302
+ o.onMonth?.(toDate(view), api);
303
+ };
304
+ const paintSel = () => {
305
+ if (!o.selectable) return;
306
+ weeksEl()?.querySelectorAll('.cal__cell').forEach((c) => {
307
+ const on = +c.dataset.n === sel;
308
+ c.classList.toggle('is-sel', on); c.setAttribute('aria-selected', String(on));
309
+ });
310
+ };
311
+ const choose = (n, { focus = true, quiet = false } = {}) => {
312
+ focusN = n;
313
+ if (monthOf(n) !== view) setView(monthOf(n), { focus });
314
+ if (o.selectable) { sel = n; paintSel(); popDate(n); }
315
+ roving();
316
+ if (focus) dateOf(n)?.focus();
317
+ if (!quiet) o.onDay?.(toDate(n), dayEvents(n).map((r) => r.ev), api);
318
+ };
319
+
320
+ /* ---------- “+2 more”: a small list beside the day ---------- */
321
+ const openMore = (n, from) => {
322
+ closeMore(false);
323
+ const cell = cellOf(n); if (!cell) return;
324
+ const list = dayEvents(n);
325
+ pop = document.createElement('div');
326
+ pop.className = 'cal__pop'; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', long(n)); pop.dataset.n = n;
327
+ pop.innerHTML = `<div class="cal__pop-h"><b>${esc(dayName(n))}</b><button type="button" class="cal__pop-x" aria-label="${esc(W.close)}">${icon('close')}</button></div>`
328
+ + `<div class="cal__pop-list">${list.map((r) => evHTML(r, { row: true })).join('')}</div>`;
329
+ root.append(pop);
330
+ popFrom = from;
331
+ const rb = root.getBoundingClientRect(), cb = cell.getBoundingClientRect();
332
+ const w = Math.min(rb.width - 8, Math.max(cb.width + 28, 220));
333
+ const left = clamp(cb.left - rb.left - 14, 4, rb.width - w - 4), top = Math.max(0, cb.top - rb.top - 8);
334
+ Object.assign(pop.style, { width: `${w}px`, left: `${left}px`, top: `${top}px` });
335
+ const first = pop.querySelector('.cal__pop-list .cal__ev') || pop.querySelector('.cal__pop-x');
336
+ pop.querySelectorAll('button').forEach((b) => { b.tabIndex = 0; });
337
+ if (!RM()) {
338
+ g.fromTo(pop, { opacity: 0, scale: 0.88, transformOrigin: `${cb.left - rb.left - left + cb.width / 2}px ${cb.top - rb.top - top + 16}px` },
339
+ { opacity: 1, scale: 1, duration: 0.32, ease: 'back.out(1.8)', clearProps: 'transform,opacity' });
340
+ g.fromTo(pop.querySelectorAll('.cal__pop-list .cal__ev'), { opacity: 0, x: -6 }, { opacity: 1, x: 0, duration: 0.3, delay: 0.08, stagger: 0.03, ease: 'power2.out', clearProps: 'transform,opacity' });
341
+ }
342
+ first?.focus();
343
+ };
344
+ const closeMore = (back = true) => {
345
+ if (!pop) return;
346
+ const p = pop, from = popFrom;
347
+ pop = null; popFrom = null;
348
+ if (RM()) p.remove(); else g.to(p, { opacity: 0, scale: 0.95, duration: 0.14, ease: 'power2.in', onComplete: () => p.remove() });
349
+ if (back && from?.isConnected) from.focus();
350
+ };
351
+
352
+ /* ---------- moving an event ---------- */
353
+ const mark = (ns, r) => {
354
+ weeksEl()?.querySelectorAll('.cal__cell').forEach((c) => {
355
+ const n = +c.dataset.n;
356
+ c.classList.toggle('is-drop', ns != null && n >= ns && n <= ns + (r.e - r.s));
357
+ });
358
+ };
359
+ /** Move a record to start on ns. Returns false when it stays where it was. */
360
+ const moveTo = (r, ns, { rect = null, day = ns } = {}) => {
361
+ if (ns === r.s) return false;
362
+ const len = r.e - r.s, before = r.ev;
363
+ if (o.onMove?.(before, toDate(ns), toDate(ns + len), api) === false) return false;
364
+ r.ev = { ...before, start: like(before.start, ns), ...(before.end != null ? { end: like(before.end, ns + len) } : {}) };
365
+ r.s = ns; r.e = ns + len;
366
+ if (ns + len < gridOf(view).start || ns > gridOf(view).end) { focusN = ns; setView(monthOf(ns)); }
367
+ else refresh();
368
+ const segs = segsOf(r.id);
369
+ const main = segs.find((b) => { const [a, b2] = segDays(b); return day >= a && day <= b2; }) || segs[0];
370
+ if (main && rect) M.landFrom(main, rect);
371
+ else if (!main && !RM()) { const more = cellOf(ns)?.querySelector('.cal__more'); if (more) g.fromTo(more, { scale: 0.8 }, { scale: 1, duration: 0.45, ease: 'back.out(3)', clearProps: 'transform' }); }
372
+ if (!RM()) segs.filter((b) => b !== main).forEach((b) => g.fromTo(b, { opacity: 0 }, { opacity: 1, duration: 0.3, delay: 0.15, clearProps: 'opacity' }));
373
+ say(W.moved(r.title, dayName(ns)));
374
+ return true;
375
+ };
376
+ const endDrag = () => {
377
+ dragging = null;
378
+ root.classList.remove('is-dragging');
379
+ later(() => { suppress = false; }, 0);
380
+ };
381
+
382
+ /* ---------- input ---------- */
383
+ on(root, 'click', (ev) => {
384
+ if (suppress) { suppress = false; return; }
385
+ const t = ev.target;
386
+ if (t.closest('.cal__prev')) { api.prev(); return; }
387
+ if (t.closest('.cal__next')) { api.next(); return; }
388
+ if (t.closest('.cal__today')) { api.today(); dateOf(today)?.focus(); return; }
389
+ if (t.closest('.cal__pop-x')) { closeMore(true); return; }
390
+ const evb = t.closest('.cal__ev');
391
+ if (evb) { const r = byId(evb.dataset.id); if (r) o.onEvent?.(r.ev, api); return; }
392
+ const more = t.closest('.cal__more');
393
+ if (more) { const n = +more.closest('.cal__cell').dataset.n; if (pop && +pop.dataset.n === n) closeMore(true); else openMore(n, more); return; }
394
+ const cell = t.closest('.cal__weeks .cal__cell');
395
+ if (cell && !cell.closest('.is-leaving')) { closeMore(false); choose(+cell.dataset.n); }
396
+ });
397
+ on(root, 'keydown', (ev) => {
398
+ if (pop && pop.contains(ev.target)) { if (ev.key === 'Escape') { ev.preventDefault(); closeMore(true); } return; }
399
+ const cell = ev.target.closest?.('.cal__weeks .cal__cell'); if (!cell) return;
400
+ const n = +cell.dataset.n;
401
+ const chip = ev.target.closest('.cal__ev');
402
+ if (chip && ev.altKey) {
403
+ const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 }[ev.key];
404
+ if (!step || !o.draggable) return;
405
+ ev.preventDefault();
406
+ const r = byId(chip.dataset.id); if (!r) return;
407
+ const ns = r.s + step;
408
+ if (moveTo(r, ns, { rect: chip.getBoundingClientRect(), day: ns })) {
409
+ const segs = segsOf(r.id);
410
+ (segs.find((b) => { const [a, b2] = segDays(b); return ns >= a && ns <= b2; }) || segs[0] || dateOf(ns))?.focus();
411
+ } else if (!RM()) M.shake(chip);
412
+ return;
413
+ }
414
+ const lead = (parts(n).w - ws0 + 7) % 7;
415
+ const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7, Home: -lead, End: 6 - lead }[ev.key];
416
+ let to = step != null ? n + step : null;
417
+ if (ev.key === 'PageUp' || ev.key === 'PageDown') {
418
+ const m = addMonths(monthOf(n), (ev.key === 'PageUp' ? -1 : 1) * (ev.shiftKey ? 12 : 1));
419
+ to = m + Math.min(parts(n).d, daysIn(m)) - 1;
420
+ }
421
+ if (to == null || ev.altKey || ev.ctrlKey || ev.metaKey) return;
422
+ ev.preventDefault();
423
+ focusN = to;
424
+ if (monthOf(to) !== view) setView(monthOf(to), { focus: true });
425
+ else { roving(); dateOf(to)?.focus(); }
426
+ });
427
+ on(root, 'focusin', (ev) => {
428
+ const cell = ev.target.closest?.('.cal__weeks .cal__cell');
429
+ if (cell && !cell.closest('.is-leaving') && +cell.dataset.n !== focusN && ev.target.classList.contains('cal__date')) { focusN = +cell.dataset.n; roving(); }
430
+ });
431
+ on(document, 'pointerdown', (ev) => { if (pop && !pop.contains(ev.target) && !ev.target.closest?.('.cal__more')) closeMore(false); });
432
+ on(root, 'focusout', (ev) => { if (pop && ev.relatedTarget && !pop.contains(ev.relatedTarget)) closeMore(false); });
433
+
434
+ // drag an event to another day (mouse: straight away; touch: press and hold first)
435
+ on(root, 'pointerdown', (ev) => {
436
+ if (!o.draggable || ev.button > 0) return;
437
+ const chip = ev.target.closest('.cal__weeks .cal__ev');
438
+ if (!chip || chip.closest('.is-leaving')) return;
439
+ const r = byId(chip.dataset.id); if (!r) return;
440
+ const week = chip.closest('.cal__week'), wr = week.getBoundingClientRect();
441
+ const [a, b] = segDays(chip);
442
+ const col = clamp(Math.floor((ev.clientX - wr.left) / (wr.width / 7)), 0, 6);
443
+ const off = clamp(+week.dataset.n + col, a, b) - r.s; // which day of the event was grabbed
444
+ const mine = (z) => (z && root.contains(z) && !z.closest('.is-leaving') ? z : null);
445
+ M.drag(chip, ev, {
446
+ targets: '.cal__cell',
447
+ lift: RM() ? { scale: 1 } : { scale: 1.05, rotation: 1.5 },
448
+ onStart: () => { dragging = r; suppress = true; root.classList.add('is-dragging'); closeMore(false); },
449
+ onMove: (dx, dy, over) => { const z = mine(over); mark(z ? +z.dataset.n - off : null, r); },
450
+ onDrop: (zone, rect) => {
451
+ mark(null, r);
452
+ const z = mine(zone);
453
+ const ok = z ? moveTo(r, +z.dataset.n - off, { rect, day: +z.dataset.n }) : false;
454
+ endDrag();
455
+ return ok;
456
+ },
457
+ onCancel: () => { mark(null, r); endDrag(); },
458
+ });
459
+ });
460
+ on(root, 'touchmove', (ev) => { if (dragging) ev.preventDefault(); }, { passive: false });
461
+ on(root, 'contextmenu', (ev) => { if (o.draggable && ev.target.closest?.('.cal__weeks .cal__ev')) ev.preventDefault(); });
462
+
463
+ const api = {
464
+ el: root, opts: o,
465
+ /** The first day of the month on show, as a Date. */
466
+ get month() { return toDate(view); },
467
+ /** The picked day, as a Date (or null). */
468
+ get value() { return sel == null ? null : toDate(sel); },
469
+ /** The events as they are now (moved ones carry their new start and end). */
470
+ get events() { return recs.map((r) => r.ev); },
471
+ go(date) {
472
+ const n = toN(date); if (n == null) return api;
473
+ focusN = n; setView(monthOf(n));
474
+ return api;
475
+ },
476
+ next() { setView(addMonths(view, 1)); return api; },
477
+ prev() { setView(addMonths(view, -1)); return api; },
478
+ today() {
479
+ focusN = today;
480
+ if (monthOf(today) === view) { roving(); ringToday(0); } else setView(monthOf(today));
481
+ return api;
482
+ },
483
+ /** Pick a day from code (no onDay). null clears. */
484
+ select(date) {
485
+ const n = toN(date);
486
+ if (n == null) { sel = null; paintSel(); return api; }
487
+ choose(n, { focus: false, quiet: true });
488
+ return api;
489
+ },
490
+ setEvents(list) { recs = normAll(list); closeMore(false); refresh({ anim: true }); return api; },
491
+ addEvent(e) {
492
+ const r = norm(e); if (!r) return api;
493
+ recs = recs.filter((x) => x.id !== r.id); recs.push(r);
494
+ refresh();
495
+ const segs = segsOf(r.id);
496
+ if (!RM()) {
497
+ if (segs.length) g.fromTo(segs, { opacity: 0, scale: 0.6 }, { opacity: 1, scale: 1, duration: 0.45, ease: 'back.out(2.4)', stagger: 0.05, clearProps: 'transform,opacity' });
498
+ else { const more = cellOf(r.s)?.querySelector('.cal__more'); if (more) g.fromTo(more, { scale: 0.8 }, { scale: 1, duration: 0.45, ease: 'back.out(3)', clearProps: 'transform' }); }
499
+ }
500
+ return api;
501
+ },
502
+ removeEvent(id) {
503
+ const r = byId(String(id)); if (!r) return api;
504
+ const drop = () => { recs = recs.filter((x) => x !== r); if (pop) closeMore(false); refresh(); };
505
+ const segs = segsOf(r.id);
506
+ if (RM() || !segs.length) drop();
507
+ else g.to(segs, { opacity: 0, scale: 0.85, duration: 0.2, ease: 'power2.in', onComplete: drop });
508
+ return api;
509
+ },
510
+ destroy() {
511
+ ac.abort();
512
+ timers.forEach(clearTimeout); timers.clear();
513
+ slide?.kill();
514
+ g.killTweensOf([root, vp, ...root.querySelectorAll('*')]);
515
+ if (dragging) document.body.classList.remove('is-dragging');
516
+ el.innerHTML = '';
517
+ },
518
+ };
519
+
520
+ recs = normAll(o.events);
521
+ render();
522
+ return api;
523
+ };