@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,311 @@
1
+ /* Date range picker: a month calendar for picking one date or a start and an end.
2
+ Tap a start date (it pops with a ripple), then move over the days: a light band and a small tag
3
+ follow you, counting the days (or nights). Tap the end date and the band fills in from start to
4
+ end like ink. Days that cannot be picked are struck out, and a range may not run across them:
5
+ the tag turns red and the day gives a shake. Months slide in from the side they come from.
6
+ Arrow keys move day by day, Page Up / Page Down month by month. */
7
+ import * as M from '@gecko-ui-kit/motion';
8
+ import { icon } from '@gecko-ui-kit/icons';
9
+ import { esc } from '../index.js';
10
+
11
+ const { g, RM, $$ } = M;
12
+ const DAY = 864e5;
13
+ /** 'YYYY-MM-DD' (or a Date) → days since 1970. Dates only: the time of day is ignored. */
14
+ const toN = (v) => {
15
+ if (v == null || v === '') return null;
16
+ if (typeof v === 'number') return Math.floor(v);
17
+ if (v instanceof Date) return Date.UTC(v.getFullYear(), v.getMonth(), v.getDate()) / DAY;
18
+ const [y, m, d] = String(v).slice(0, 10).split('-').map(Number);
19
+ return Date.UTC(y, m - 1, d) / DAY;
20
+ };
21
+ const toS = (n) => (n == null ? null : new Date(n * DAY).toISOString().slice(0, 10));
22
+ const parts = (n) => { const d = new Date(n * DAY); return { y: d.getUTCFullYear(), m: d.getUTCMonth(), d: d.getUTCDate(), w: d.getUTCDay() }; };
23
+ const monthOf = (n) => { const p = parts(n); return Date.UTC(p.y, p.m, 1) / DAY; };
24
+ const addMonths = (first, k) => { const p = parts(first); return Date.UTC(p.y, p.m + k, 1) / DAY; };
25
+ const daysIn = (first) => { const p = parts(first); return new Date(Date.UTC(p.y, p.m + 1, 0)).getUTCDate(); };
26
+ const fmt = (n, locale, opt) => new Intl.DateTimeFormat(locale, { timeZone: 'UTC', ...opt }).format(new Date(n * DAY));
27
+ const todayN = () => toN(new Date());
28
+
29
+ const WORDS = {
30
+ prev: 'Previous month', next: 'Next month',
31
+ count: (n, unit) => `${n} ${unit === 'nights' ? (n === 1 ? 'night' : 'nights') : n === 1 ? 'day' : 'days'}`,
32
+ pickEnd: 'Now pick the end date.',
33
+ picked: (text) => `Picked ${text}.`,
34
+ blocked: 'Runs over days that are not free',
35
+ tooShort: (text) => `At least ${text}`,
36
+ tooLong: (text) => `At most ${text}`,
37
+ off: 'not available', today: 'today',
38
+ };
39
+
40
+ /**
41
+ * formatRange({ start, end }, { locale: 'en-GB', count: 'days', words }) → '4–7 Dec 2026 · 4 days'
42
+ * A short label for a field or a button that shows the picked range.
43
+ */
44
+ export const formatRange = (v, { locale = 'en-GB', count = 'days', words = {}, withCount = true } = {}) => {
45
+ const W = { ...WORDS, ...words }, s = toN(v?.start), e = toN(v?.end);
46
+ if (s == null) return '';
47
+ const opt = { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' };
48
+ if (e == null || e === s) return fmt(s, locale, opt) + (withCount && e === s && count === 'days' ? ` · ${W.count(1, count)}` : '');
49
+ const f = new Intl.DateTimeFormat(locale, opt);
50
+ const text = f.formatRange ? f.formatRange(new Date(s * DAY), new Date(e * DAY)) : `${f.format(new Date(s * DAY))} – ${f.format(new Date(e * DAY))}`;
51
+ return text + (withCount ? ` · ${W.count(count === 'nights' ? e - s : e - s + 1, count)}` : '');
52
+ };
53
+
54
+ /**
55
+ * const dp = dateRange(el, {
56
+ * mode: 'range' | 'single',
57
+ * value: { start: '2026-12-04', end: '2026-12-07' } (or '2026-12-04' in single mode),
58
+ * months: 1 | 2 (two side by side; drops to one when the box is narrow),
59
+ * min, max: '2026-12-01' (days outside are not available),
60
+ * disabled: ['2026-12-24', { start, end }, …] or (date) => true, // days that cannot be picked
61
+ * count: 'days' (4–7 Dec = 4 days) | 'nights' (4–7 Dec = 3 nights),
62
+ * minDays: 1, maxDays: 0 (no limit), counted in the same unit,
63
+ * blockSpan: true (a range may not run across a day that is not free),
64
+ * presets: [{ label: 'Next 7 days', days: 7 } | { label, start, end }],
65
+ * locale: 'en-GB', weekStart: 1 (Monday; 0 = Sunday), words: { … },
66
+ * onChange({ start, end, count }, dp) // end is null while the end is still to be picked
67
+ * onInvalid(reason, dp) // 'blocked' | 'short' | 'long' | 'off'
68
+ * })
69
+ * dp.value · dp.set(value) · dp.clear() · dp.go('2027-01-01' | +1 | -1) · dp.destroy()
70
+ */
71
+ export const dateRange = (el, opts = {}) => {
72
+ el = $$(el)[0];
73
+ if (!el) return null;
74
+ const W = { ...WORDS, ...opts.words };
75
+ const o = { mode: 'range', months: 1, locale: 'en-GB', weekStart: 1, count: 'days', minDays: 1, maxDays: 0, blockSpan: true, presets: [], ...opts };
76
+ const single = o.mode === 'single';
77
+ const min = toN(o.min), max = toN(o.max), today = todayN();
78
+
79
+ // days that cannot be picked
80
+ const offSet = new Set(), offRanges = [];
81
+ if (Array.isArray(o.disabled)) o.disabled.forEach((d) => { if (d && typeof d === 'object' && !(d instanceof Date)) offRanges.push([toN(d.start), toN(d.end ?? d.start)]); else offSet.add(toN(d)); });
82
+ const isOff = (n) => (min != null && n < min) || (max != null && n > max) || offSet.has(n)
83
+ || offRanges.some(([a, b]) => n >= a && n <= b) || (typeof o.disabled === 'function' && !!o.disabled(toS(n)));
84
+
85
+ let s = null, e = null, hover = null, focusN = null, lastBad = null;
86
+ const v0 = typeof o.value === 'string' ? { start: o.value, end: o.value } : o.value;
87
+ if (v0?.start) { s = toN(v0.start); e = single ? s : toN(v0.end); }
88
+ let view = monthOf(s ?? (min != null && min > today ? min : today));
89
+ let shown = o.months;
90
+
91
+ const countOf = (a, b) => (o.count === 'nights' ? b - a : b - a + 1);
92
+ const countText = (n) => W.count(n, o.count);
93
+ const val = () => ({ start: toS(s), end: toS(e), count: s != null && e != null ? countOf(s, e) : null });
94
+ /** Why a range from a to b cannot be picked, or '' when it can. */
95
+ const why = (a, b) => {
96
+ if (isOff(a) || (o.count === 'days' && isOff(b))) return 'off';
97
+ const n = countOf(a, b);
98
+ if (n < Math.max(1, o.minDays)) return 'short';
99
+ if (o.maxDays && n > o.maxDays) return 'long';
100
+ if (o.blockSpan) { const last = o.count === 'nights' ? b - 1 : b; for (let k = a + 1; k <= last; k++) if (isOff(k)) return 'blocked'; }
101
+ return '';
102
+ };
103
+ const reasonText = (r) => (r === 'blocked' ? W.blocked : r === 'short' ? W.tooShort(countText(o.minDays)) : r === 'long' ? W.tooLong(countText(o.maxDays)) : W.off);
104
+
105
+ const root = document.createElement('div');
106
+ root.className = `rp${single ? ' rp--single' : ''}`;
107
+ root.setAttribute('role', 'group');
108
+ el.innerHTML = ''; el.append(root);
109
+
110
+ const presetBtns = () => (o.presets.length && !single
111
+ ? `<div class="rp__presets" role="group">${o.presets.map((p, i) => `<button type="button" class="rp__preset" data-p="${i}" aria-pressed="false">${esc(p.label)}</button>`).join('')}</div>` : '');
112
+
113
+ const monthHTML = (first, k) => {
114
+ const lead = (parts(first).w - o.weekStart + 7) % 7, n = daysIn(first);
115
+ const wk = Array.from({ length: 7 }, (_, i) => fmt(toN('2024-01-01') + ((o.weekStart + i + 6) % 7), o.locale, { weekday: 'narrow' }));
116
+ let cells = '';
117
+ for (let i = 0; i < lead; i++) cells += '<span class="rp__x" aria-hidden="true"></span>';
118
+ for (let d = 0; d < n; d++) {
119
+ const day = first + d, col = (lead + d) % 7;
120
+ const edge = `${col === 0 || d === 0 ? ' is-row-s' : ''}${col === 6 || d === n - 1 ? ' is-row-e' : ''}`;
121
+ const off = isOff(day);
122
+ const label = `${fmt(day, o.locale, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}${day === today ? `, ${W.today}` : ''}${off ? `, ${W.off}` : ''}`;
123
+ cells += `<button type="button" class="rp__d${edge}${day === today ? ' is-today' : ''}${off ? ' is-off' : ''}" data-n="${day}" tabindex="-1" aria-label="${esc(label)}"${off ? ' aria-disabled="true"' : ''}><span class="rp__bg"></span><span class="rp__n">${parts(day).d}</span></button>`;
124
+ }
125
+ return `<div class="rp__month" data-k="${k}"><div class="rp__title" aria-live="polite">${esc(fmt(first, o.locale, { month: 'long', year: 'numeric' }))}</div><div class="rp__wk" aria-hidden="true">${wk.map((w) => `<span>${esc(w)}</span>`).join('')}</div><div class="rp__grid">${cells}</div></div>`;
126
+ };
127
+
128
+ const render = (dir = 0) => {
129
+ const firstMonth = view, lastMonth = addMonths(view, shown - 1);
130
+ root.innerHTML = `${presetBtns()}<div class="rp__body"><div class="rp__nav"><button type="button" class="rp__arrow rp__arrow--prev" aria-label="${esc(W.prev)}"${min != null && firstMonth <= monthOf(min) ? ' disabled' : ''}>${icon('chevL')}</button><button type="button" class="rp__arrow rp__arrow--next" aria-label="${esc(W.next)}"${max != null && lastMonth >= monthOf(max) ? ' disabled' : ''}>${icon('chevR')}</button></div>`
131
+ + `<div class="rp__months">${Array.from({ length: shown }, (_, k) => monthHTML(addMonths(view, k), k)).join('')}</div></div>`
132
+ + '<div class="rp__tip" aria-hidden="true"></div><div class="rp__sr" role="status"></div>';
133
+ paint();
134
+ roving();
135
+ if (dir && !RM()) {
136
+ g.fromTo(root.querySelectorAll('.rp__grid, .rp__wk'), { x: 28 * dir, opacity: 0 }, { x: 0, opacity: 1, duration: 0.38, ease: 'power3.out', stagger: 0.03, clearProps: 'transform,opacity' });
137
+ g.fromTo(root.querySelectorAll('.rp__title'), { y: 10 * dir, opacity: 0 }, { y: 0, opacity: 1, duration: 0.32, ease: 'power2.out', clearProps: 'transform,opacity' });
138
+ }
139
+ };
140
+
141
+ const cells = () => [...root.querySelectorAll('.rp__d')];
142
+ const cellOf = (n) => root.querySelector(`.rp__d[data-n="${n}"]`);
143
+ const say = (t) => { const sr = root.querySelector('.rp__sr'); if (sr) sr.textContent = t; };
144
+
145
+ /** Put the classes on every day for the picked range and the preview. */
146
+ const paint = () => {
147
+ const picking = !single && s != null && e == null && hover != null && hover >= s;
148
+ const pv = picking ? why(s, hover) : '';
149
+ cells().forEach((c) => {
150
+ const n = +c.dataset.n;
151
+ const inR = s != null && e != null && n > s && n < e, isS = n === s, isE = e != null && n === e;
152
+ c.classList.toggle('is-s', isS); c.classList.toggle('is-e', isE && !single);
153
+ c.classList.toggle('is-one', isS && (e === s || e == null));
154
+ c.classList.toggle('is-in', inR);
155
+ c.classList.toggle('is-pv', picking && n > s && n < hover);
156
+ c.classList.toggle('is-pv-e', picking && n === hover && n !== s);
157
+ c.classList.toggle('is-pv-s', picking && isS && hover > s);
158
+ c.classList.toggle('is-bad', picking && !!pv && n > s && n <= hover);
159
+ c.setAttribute('aria-pressed', String(isS || isE));
160
+ });
161
+ root.querySelectorAll('.rp__preset').forEach((b) => { const r = presetRange(o.presets[+b.dataset.p]); b.setAttribute('aria-pressed', String(!!r && r[0] === s && r[1] === e)); });
162
+ tip(picking ? hover : null, pv);
163
+ };
164
+
165
+ /** The small tag over the day under the pointer: the count so far, or why it cannot be picked. */
166
+ let tipShown = false;
167
+ const tip = (n, bad) => {
168
+ const t = root.querySelector('.rp__tip'); if (!t) return;
169
+ const c = n != null && cellOf(n);
170
+ if (!c) { if (tipShown) { tipShown = false; if (RM()) t.classList.remove('is-on'); else g.to(t, { opacity: 0, scale: 0.85, duration: 0.15, onComplete: () => t.classList.remove('is-on') }); } return; }
171
+ t.textContent = bad ? reasonText(bad) : countText(countOf(s, n));
172
+ t.classList.toggle('is-bad', !!bad);
173
+ const rb = root.getBoundingClientRect(), cb = c.getBoundingClientRect();
174
+ const x = Math.max(4, Math.min(rb.width - t.offsetWidth - 4, cb.left - rb.left + cb.width / 2 - t.offsetWidth / 2)), y = cb.top - rb.top - t.offsetHeight - 6;
175
+ t.classList.add('is-on');
176
+ if (RM()) { g.set(t, { x, y, opacity: 1, scale: 1 }); }
177
+ else if (!tipShown) g.fromTo(t, { x, y: y + 6, opacity: 0, scale: 0.85 }, { y, opacity: 1, scale: 1, duration: 0.22, ease: 'back.out(2.4)', overwrite: true });
178
+ else g.to(t, { x, y, opacity: 1, scale: 1, duration: 0.16, ease: 'power2.out', overwrite: true });
179
+ tipShown = true;
180
+ };
181
+
182
+ /** Only one day takes Tab: the focused one, else the end, the start, today or the first free day. */
183
+ const roving = () => {
184
+ const list = cells(); if (!list.length) return;
185
+ const pick = [focusN, e, s, today].find((n) => n != null && cellOf(n)) ?? +list.find((c) => !c.classList.contains('is-off'))?.dataset.n ?? +list[0].dataset.n;
186
+ list.forEach((c) => { c.tabIndex = +c.dataset.n === pick ? 0 : -1; });
187
+ };
188
+
189
+ const pop = (c) => {
190
+ if (!c || RM()) return;
191
+ g.fromTo(c.querySelector('.rp__n'), { scale: 1 }, { keyframes: { scale: [1, 0.82, 1.1, 1] }, duration: 0.42, ease: 'power2.out', clearProps: 'transform' });
192
+ const ring = document.createElement('span'); ring.className = 'rp__ring'; c.append(ring);
193
+ g.fromTo(ring, { scale: 0.6, opacity: 0.9 }, { scale: 1.7, opacity: 0, duration: 0.55, ease: 'power2.out', onComplete: () => ring.remove() });
194
+ };
195
+ const shake = (c) => { if (c && !RM()) g.fromTo(c, { x: 0 }, { keyframes: { x: [0, -5, 4, -3, 2, 0] }, duration: 0.38, ease: 'power2.out', clearProps: 'transform' }); };
196
+ /** The band fills in from start to end, day by day. */
197
+ const fill = () => {
198
+ if (RM()) return;
199
+ const band = cells().filter((c) => c.classList.contains('is-in') || c.classList.contains('is-e') || (c.classList.contains('is-s') && !c.classList.contains('is-one'))).map((c) => c.querySelector('.rp__bg'));
200
+ g.fromTo(band, { scaleX: 0 }, { scaleX: 1, transformOrigin: '0% 50%', duration: 0.26, ease: 'power2.out', stagger: Math.min(0.03, 0.4 / Math.max(1, band.length)), clearProps: 'transform' });
201
+ pop(cellOf(e));
202
+ };
203
+
204
+ const emit = () => o.onChange?.(val(), api);
205
+ const choose = (n) => {
206
+ const c = cellOf(n);
207
+ const endPick = !single && s != null && e == null && n > s;
208
+ if (isOff(n) && !(endPick && o.count === 'nights')) { shake(c); o.onInvalid?.('off', api); return; } // with nights, the day you leave may be taken
209
+ focusN = n;
210
+ if (single) { s = e = n; hover = null; paint(); pop(c); say(W.picked(formatRange(val(), { locale: o.locale, count: o.count, words: W, withCount: false }))); emit(); return; }
211
+ if (s == null || e != null || n < s || n === lastBad) { // a new start (or a second tap on a day that could not end the range)
212
+ lastBad = null;
213
+ s = n; e = null; hover = null; paint(); pop(c); say(W.pickEnd); emit(); return;
214
+ }
215
+ if (n === s && o.count === 'nights') return;
216
+ const bad = why(s, n);
217
+ if (bad) { hover = n; lastBad = n; paint(); shake(c); o.onInvalid?.(bad, api); say(reasonText(bad)); return; }
218
+ lastBad = null;
219
+ e = n; hover = null; paint(); fill();
220
+ say(W.picked(formatRange(val(), { locale: o.locale, count: o.count, words: W })));
221
+ emit();
222
+ };
223
+
224
+ const presetRange = (p) => {
225
+ if (!p) return null;
226
+ if (p.start) return [toN(p.start), toN(p.end ?? p.start)];
227
+ if (p.days) { const a = Math.max(today, min ?? today); return [a, a + (o.count === 'nights' ? p.days : p.days - 1)]; }
228
+ return null;
229
+ };
230
+ const setRange = (a, b, { animate = true, quiet = false } = {}) => {
231
+ s = a; e = single ? a : b; hover = null; focusN = e ?? s;
232
+ const target = s == null ? view : monthOf(s);
233
+ const outside = s != null && (target < view || monthOf(e ?? s) > addMonths(view, shown - 1));
234
+ if (outside) { const dir = target < view ? -1 : 1; view = target; render(animate ? dir : 0); } else paint();
235
+ roving();
236
+ if (animate && e != null) fill();
237
+ if (!quiet) emit();
238
+ };
239
+
240
+ /* ---------- events ---------- */
241
+ const ac = new AbortController(), on = { signal: ac.signal };
242
+ root.addEventListener('click', (ev) => {
243
+ const d = ev.target.closest('.rp__d'); if (d) { choose(+d.dataset.n); return; }
244
+ const a = ev.target.closest('.rp__arrow'); if (a && !a.disabled) { api.go(a.classList.contains('rp__arrow--prev') ? -1 : 1); return; }
245
+ const p = ev.target.closest('.rp__preset');
246
+ if (p) { const r = presetRange(o.presets[+p.dataset.p]); if (r && !why(r[0], r[1])) setRange(r[0], r[1]); else { shake(p); o.onInvalid?.(r ? why(r[0], r[1]) : 'off', api); } }
247
+ }, on);
248
+ root.addEventListener('pointerover', (ev) => {
249
+ if (single || s == null || e != null || ev.pointerType === 'touch') return;
250
+ const d = ev.target.closest('.rp__d'); const n = d ? +d.dataset.n : null;
251
+ if (n !== hover) { hover = n; paint(); }
252
+ }, on);
253
+ root.addEventListener('pointerleave', () => { if (hover != null) { hover = null; paint(); } }, on);
254
+ root.addEventListener('keydown', (ev) => {
255
+ const d = ev.target.closest('.rp__d'); if (!d) return;
256
+ const n = +d.dataset.n, p = parts(n);
257
+ const lead = (p.w - o.weekStart + 7) % 7;
258
+ const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7, Home: -lead, End: 6 - lead }[ev.key];
259
+ let to = step != null ? n + step : null;
260
+ if (ev.key === 'PageUp' || ev.key === 'PageDown') { const m = addMonths(monthOf(n), ev.key === 'PageUp' ? -1 : 1); to = m + Math.min(p.d, daysIn(m)) - 1; }
261
+ if (to == null) return;
262
+ ev.preventDefault();
263
+ if (min != null && to < min) to = min; if (max != null && to > max) to = max;
264
+ focusN = to;
265
+ const first = view, last = addMonths(view, shown - 1);
266
+ if (monthOf(to) < first || monthOf(to) > last) { const dir = monthOf(to) < first ? -1 : 1; view = monthOf(to) < first ? monthOf(to) : addMonths(monthOf(to), -(shown - 1)); render(dir); }
267
+ roving();
268
+ if (!single && s != null && e == null) { hover = to >= s ? to : null; paint(); }
269
+ cellOf(to)?.focus();
270
+ }, on);
271
+ root.addEventListener('focusin', (ev) => { const d = ev.target.closest('.rp__d'); if (d) focusN = +d.dataset.n; }, on);
272
+
273
+ // two months side by side only when there is room
274
+ let raf = 0;
275
+ const ro = new ResizeObserver(() => {
276
+ cancelAnimationFrame(raf);
277
+ raf = requestAnimationFrame(() => { // next frame, so the change does not loop the observer
278
+ if (!root.isConnected) return;
279
+ const want = o.months > 1 && root.clientWidth < 540 ? 1 : o.months;
280
+ if (want !== shown) { shown = want; render(); }
281
+ });
282
+ });
283
+ ro.observe(root);
284
+
285
+ const api = {
286
+ el: root, opts: o,
287
+ get value() { return val(); },
288
+ /** Pick from code: { start, end } (or a date in single mode). null clears. */
289
+ set(v, { animate = true } = {}) {
290
+ if (v == null) return api.clear();
291
+ const x = typeof v === 'string' ? { start: v, end: v } : v;
292
+ setRange(toN(x.start), toN(x.end ?? (single ? x.start : null)), { animate, quiet: true });
293
+ return api;
294
+ },
295
+ clear() {
296
+ s = e = hover = null; focusN = null; paint(); roving(); say('');
297
+ emit(); return api;
298
+ },
299
+ /** Show another month: a date, or a number of months to move by. */
300
+ go(where) {
301
+ const next = typeof where === 'number' ? addMonths(view, where) : monthOf(toN(where));
302
+ if (next === view) return api;
303
+ const dir = next > view ? 1 : -1; view = next; render(dir);
304
+ say(fmt(view, o.locale, { month: 'long', year: 'numeric' }));
305
+ return api;
306
+ },
307
+ destroy() { ac.abort(); ro.disconnect(); cancelAnimationFrame(raf); el.innerHTML = ''; },
308
+ };
309
+ render();
310
+ return api;
311
+ };