@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.
- package/LICENSE +21 -0
- package/README.md +712 -2
- package/index.js +198 -0
- package/package.json +42 -4
- package/src/accordion.js +208 -0
- package/src/alert.js +205 -0
- package/src/authform.js +285 -0
- package/src/breadcrumbs.js +204 -0
- package/src/calendar.js +523 -0
- package/src/carousel.js +266 -0
- package/src/combobox.js +421 -0
- package/src/daterange.js +311 -0
- package/src/donut.js +346 -0
- package/src/filedrop.js +378 -0
- package/src/gauge.js +169 -0
- package/src/grid.js +298 -0
- package/src/heatmap.js +332 -0
- package/src/kanban.js +319 -0
- package/src/leaderboard.js +201 -0
- package/src/linechart.js +550 -0
- package/src/multiselect.js +324 -0
- package/src/notifications.js +393 -0
- package/src/otp.js +112 -0
- package/src/pagination.js +242 -0
- package/src/password.js +245 -0
- package/src/rangeslider.js +266 -0
- package/src/rating.js +171 -0
- package/src/signature.js +213 -0
- package/src/skeleton.js +254 -0
- package/src/spinner.js +38 -0
- package/src/stepper.js +211 -0
- package/src/swipe.js +280 -0
- package/src/tagsinput.js +369 -0
- package/src/timeline.js +340 -0
- package/src/timepicker.js +290 -0
- package/src/tree.js +490 -0
- package/src/upload.js +416 -0
- package/src/virtuallist.js +373 -0
- package/src/wizard.js +392 -0
- package/style.css +1761 -0
package/src/timeline.js
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/* Booking timeline: rows of things people book (bikes, rooms, staff, tasks) against days.
|
|
2
|
+
Each booking is a bar: drag it to another day or another row, or stretch it from either end;
|
|
3
|
+
it moves in whole days (a booking that starts at 10:00 still starts at 10:00). While you drag,
|
|
4
|
+
a dashed outline shows where it will land with the dates on a tag, and turns red if it would
|
|
5
|
+
clash with another booking; letting go on a clash springs the bar back with a shake. Every
|
|
6
|
+
change can be undone. A line marks "now", and a booking still out after its end time turns
|
|
7
|
+
red by itself. On a phone, hold a bar for a moment to pick it up (a plain swipe still scrolls).
|
|
8
|
+
Arrow keys move a focused bar, Shift + arrows change its length. */
|
|
9
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
10
|
+
import { esc } from '../index.js';
|
|
11
|
+
|
|
12
|
+
const { g, RM, $$ } = M;
|
|
13
|
+
const DAY = 864e5;
|
|
14
|
+
const pad = (v) => String(v).padStart(2, '0');
|
|
15
|
+
/** A date or date-time → days since 1970 as a number (10:00 = .4167). Clock times are taken as
|
|
16
|
+
* written; a string with Z or an offset (or a Date) is turned into this device's local time. */
|
|
17
|
+
const dn = (v) => {
|
|
18
|
+
if (typeof v === 'number') return v;
|
|
19
|
+
if (v instanceof Date || /T.*(Z|[+-]\d\d:?\d\d)$/.test(String(v))) {
|
|
20
|
+
const d = new Date(v); return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes()) / DAY;
|
|
21
|
+
}
|
|
22
|
+
const s = String(v), [y, m, d] = s.slice(0, 10).split('-').map(Number), [hh = 0, mm = 0] = s.length > 10 ? s.slice(11, 16).split(':').map(Number) : [];
|
|
23
|
+
return Date.UTC(y, m - 1, d, hh, mm) / DAY;
|
|
24
|
+
};
|
|
25
|
+
const ds = (n, time = false) => new Date(Math.round(n * DAY)).toISOString().slice(0, time ? 16 : 10);
|
|
26
|
+
const nowDays = () => dn(new Date());
|
|
27
|
+
const STATUS = { booked: 1, out: 1, late: 1, done: 1, service: 1 };
|
|
28
|
+
const WORDS = {
|
|
29
|
+
day: 'day', days: 'days',
|
|
30
|
+
clash: (name) => `Clashes with ${name}`,
|
|
31
|
+
clashBack: (name) => `That clashes with ${name}, so it went back.`,
|
|
32
|
+
picked: (name) => `Picked up ${name}. Move it, then let go.`,
|
|
33
|
+
undone: (name) => `Undone: ${name} is back.`,
|
|
34
|
+
booking: 'a booking',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* const tl = timeline(el, {
|
|
39
|
+
* rows: [{ id, label, sub, icon }], // what is booked: bikes, rooms, people
|
|
40
|
+
* items: [{ id, row, start, end, label, status, color, edit }],
|
|
41
|
+
* // start/end: '2026-12-04' or '2026-12-04T10:00' (end = when it comes back)
|
|
42
|
+
* // status: 'booked' | 'out' (in use now) | 'late' | 'done' | 'service'
|
|
43
|
+
* // edit: true | false (locked) | 'end' (can only be made longer, e.g. a bike already out)
|
|
44
|
+
* from: first day shown (default today), days: 14, locale: 'en-GB', title: 'Bookings',
|
|
45
|
+
* edit: true, overlap: false (true lets bookings share a row), minDays: 1,
|
|
46
|
+
* now: true (a line at the current time), late: true ('out' past its end shows as late),
|
|
47
|
+
* dayWidth, rowHeight, labelWidth (px; default from CSS, narrower on phones),
|
|
48
|
+
* sub: (item, days) => '3 days', // the second line on each bar
|
|
49
|
+
* words: { day, days, clash(name), clashBack(name), picked(name), undone(name), booking },
|
|
50
|
+
* onChange(item, before), onOpen(item, bar), onAdd({ row, start }), onClash(item, other)
|
|
51
|
+
* })
|
|
52
|
+
* tl.items() · tl.setItems(list) · tl.add(item) · tl.update(id, patch) · tl.remove(id)
|
|
53
|
+
* tl.undo() · tl.go('2026-12-20' | +7 | -7) · tl.today() · tl.from · tl.destroy()
|
|
54
|
+
*/
|
|
55
|
+
export const timeline = (el, opts = {}) => {
|
|
56
|
+
el = $$(el)[0];
|
|
57
|
+
if (!el) return null;
|
|
58
|
+
const W = { ...WORDS, ...opts.words };
|
|
59
|
+
const o = { days: 14, locale: 'en-GB', title: 'Bookings', edit: true, overlap: false, minDays: 1, now: true, late: true,
|
|
60
|
+
sub: (it, n) => `${n} ${n === 1 ? W.day : W.days}`, ...opts };
|
|
61
|
+
const norm = (it) => { const s = dn(it.start); return { status: 'booked', ...it, s, e: Math.max(dn(it.end), s + 1 / 24), t: /T\d/.test(String(it.start)) || it.start instanceof Date }; };
|
|
62
|
+
const pub = (it) => { const { s, e, t, ...rest } = it; return { ...rest, start: ds(s, t), end: ds(e, t) }; };
|
|
63
|
+
const span = (s, e) => Math.max(1, Math.ceil(e - s - 0.01)); // whole days, rounded up
|
|
64
|
+
let rows = (o.rows || []).map((r) => ({ ...r }));
|
|
65
|
+
let items = (o.items || []).map(norm);
|
|
66
|
+
const startDay = (v) => Math.floor(dn(v));
|
|
67
|
+
let from = startDay(o.from || o.today || new Date());
|
|
68
|
+
const today = startDay(o.today || new Date());
|
|
69
|
+
const lead = Math.max(0, Math.min(o.days - 1, today - from)); // how many days before today the view starts; today() keeps it
|
|
70
|
+
const history = [];
|
|
71
|
+
let drag = null, eatClick = false;
|
|
72
|
+
|
|
73
|
+
const vars = [o.dayWidth && `--tl-day:${o.dayWidth}px`, o.rowHeight && `--tl-row:${o.rowHeight}px`, o.labelWidth && `--tl-label:${o.labelWidth}px`].filter(Boolean).join(';');
|
|
74
|
+
el.innerHTML = `<div class="tl${o.edit ? '' : ' tl--readonly'}" role="region" aria-label="${esc(o.title)}" style="${vars}"><div class="tl__scroll"><div class="tl__grid"></div></div><div class="tl__sr" role="status"></div></div>`;
|
|
75
|
+
const root = el.firstElementChild, scroller = root.querySelector('.tl__scroll'), grid = root.querySelector('.tl__grid'), sr = root.querySelector('.tl__sr');
|
|
76
|
+
const say = (t) => { sr.textContent = t; };
|
|
77
|
+
const dayW = () => parseFloat(getComputedStyle(root).getPropertyValue('--tl-day')) || 56;
|
|
78
|
+
const fmt = (n, opt) => new Date(Math.round(n * DAY)).toLocaleDateString(o.locale, { timeZone: 'UTC', ...opt });
|
|
79
|
+
const when = (n, t) => fmt(n, t ? { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' } : { day: 'numeric', month: 'short' });
|
|
80
|
+
const range = (s, e, t = false) => `${when(s, t)} → ${when(e, t)}`;
|
|
81
|
+
const rowOf = (id) => rows.find((r) => String(r.id) === String(id));
|
|
82
|
+
const byId = (id) => items.find((x) => String(x.id) === String(id));
|
|
83
|
+
const barOf = (id) => grid.querySelector(`.tl__bar[data-id="${CSS.escape(String(id))}"]`);
|
|
84
|
+
const laneOf = (rowId) => grid.querySelector(`.tl__row[data-row="${CSS.escape(String(rowId))}"] .tl__lane`);
|
|
85
|
+
const clashWith = (it, s, e, row) => (o.overlap ? null : items.find((x) => x !== it && String(x.row) === String(row) && x.s < e && s < x.e));
|
|
86
|
+
const lock = (it) => (!o.edit || it.edit === false || (it.edit == null && it.status === 'done') ? 'all' : it.edit === 'end' ? 'start' : '');
|
|
87
|
+
const nameOf = (it) => it?.label ?? W.booking;
|
|
88
|
+
|
|
89
|
+
/* ---------- drawing ---------- */
|
|
90
|
+
const shown = (it) => (o.late && it.status === 'out' && it.e < nowDays() ? 'late' : STATUS[it.status] ? it.status : 'booked');
|
|
91
|
+
const fill = (bar, it) => {
|
|
92
|
+
const lk = lock(it);
|
|
93
|
+
bar.className = `tl__bar is-${shown(it)}${lk === 'all' ? ' is-locked' : lk === 'start' ? ' is-lock-s' : ''}`;
|
|
94
|
+
if (it.color) bar.style.setProperty('--tl-c', it.color); else bar.style.removeProperty('--tl-c');
|
|
95
|
+
const a = Math.max(it.s, from), b = Math.min(it.e, from + o.days);
|
|
96
|
+
bar.style.setProperty('--k', a - from); bar.style.setProperty('--n', b - a);
|
|
97
|
+
bar.classList.toggle('is-cut-s', it.s < from); bar.classList.toggle('is-cut-e', it.e > from + o.days);
|
|
98
|
+
bar.querySelector('.tl__txt').innerHTML = `<b>${esc(it.label ?? '')}</b><small>${esc(o.sub(pub(it), span(it.s, it.e)))}</small>`;
|
|
99
|
+
bar.setAttribute('aria-label', `${rowOf(it.row)?.label ?? ''}: ${it.label ?? ''}, ${range(it.s, it.e, it.t)}, ${o.sub(pub(it), span(it.s, it.e))}`);
|
|
100
|
+
};
|
|
101
|
+
const makeBar = (it) => {
|
|
102
|
+
const bar = document.createElement('button');
|
|
103
|
+
bar.type = 'button'; bar.dataset.id = it.id;
|
|
104
|
+
bar.innerHTML = '<span class="tl__grip tl__grip--s" aria-hidden="true"></span><span class="tl__txt"></span><span class="tl__grip tl__grip--e" aria-hidden="true"></span>';
|
|
105
|
+
fill(bar, it); return bar;
|
|
106
|
+
};
|
|
107
|
+
const visible = (it) => it.e > from && it.s < from + o.days;
|
|
108
|
+
/** Put an item's bar in the right lane (creating or removing it as needed). Returns the bar or null. */
|
|
109
|
+
const place = (it) => {
|
|
110
|
+
let bar = barOf(it.id);
|
|
111
|
+
const lane = laneOf(it.row);
|
|
112
|
+
if (!visible(it) || !lane) { bar?.remove(); return null; }
|
|
113
|
+
if (!bar) bar = makeBar(it); else fill(bar, it);
|
|
114
|
+
if (bar.parentElement !== lane) { const had = document.activeElement === bar; lane.append(bar); if (had) bar.focus({ preventScroll: true }); }
|
|
115
|
+
return bar;
|
|
116
|
+
};
|
|
117
|
+
const drawNow = () => {
|
|
118
|
+
const line = grid.querySelector('.tl__now'); if (!line) return;
|
|
119
|
+
const k = nowDays() - from; line.hidden = k < 0 || k > o.days; line.style.setProperty('--k', k);
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const render = (intro = false) => {
|
|
123
|
+
const N = o.days, ks = Array.from({ length: N }, (_, k) => from + k);
|
|
124
|
+
root.style.setProperty('--tl-days', N);
|
|
125
|
+
const m1 = fmt(from, { month: 'short', year: 'numeric' }), m2 = fmt(from + N - 1, { month: 'short', year: 'numeric' });
|
|
126
|
+
const cls = (n) => { const w = new Date(n * DAY).getUTCDay(); return `${w === 0 || w === 6 ? ' is-wk' : ''}${n === today ? ' is-today' : ''}`; };
|
|
127
|
+
grid.innerHTML = `<div class="tl__head"><div class="tl__corner"><b>${esc(o.title)}</b><small>${esc(m1 === m2 ? m1 : `${fmt(from, { month: 'short' })} – ${m2}`)}</small></div><div class="tl__days">${ks.map((n) => `<div class="tl__day${cls(n)}"${n === today ? ' aria-current="date"' : ''}><small>${esc(fmt(n, { weekday: 'short' }))}</small><b>${fmt(n, { day: 'numeric' })}</b></div>`).join('')}</div></div>`
|
|
128
|
+
+ `<div class="tl__body"><div class="tl__cols" aria-hidden="true">${ks.map((n) => `<i class="tl__col${cls(n)}"></i>`).join('')}</div>${o.now ? '<i class="tl__now" aria-hidden="true"></i>' : ''}`
|
|
129
|
+
+ rows.map((r) => `<div class="tl__row" data-row="${esc(r.id)}"><div class="tl__label">${r.icon ? `<span class="tl__ic">${r.icon}</span>` : ''}<span class="tl__name"><b>${esc(r.label)}</b>${r.sub ? `<small>${esc(r.sub)}</small>` : ''}</span></div><div class="tl__lane"></div></div>`).join('')
|
|
130
|
+
+ '</div>';
|
|
131
|
+
drawNow();
|
|
132
|
+
const bars = items.map(place).filter(Boolean);
|
|
133
|
+
if (intro && !RM() && bars.length) g.fromTo(bars, { scaleX: 0, opacity: 0 }, { scaleX: 1, opacity: 1, transformOrigin: '0% 50%', duration: 0.5, ease: 'power3.out', stagger: 0.035, clearProps: 'transform,opacity' });
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/* ---------- changing a booking ---------- */
|
|
137
|
+
/** Animate a bar from where it was on screen (first) to where it is now. */
|
|
138
|
+
const flip = (bar, first) => {
|
|
139
|
+
if (!bar || !first || RM()) return;
|
|
140
|
+
const last = bar.getBoundingClientRect();
|
|
141
|
+
g.fromTo(bar, { x: first.left - last.left, y: first.top - last.top, width: first.width }, { x: 0, y: 0, width: last.width, duration: 0.45, ease: 'back.out(1.5)', clearProps: 'transform,width' });
|
|
142
|
+
};
|
|
143
|
+
const shake = (bar) => { if (bar && !RM()) g.fromTo(bar, { x: 0 }, { keyframes: { x: [0, -7, 6, -4, 2, 0] }, duration: 0.42, ease: 'power2.out', clearProps: 'transform' }); };
|
|
144
|
+
const refuse = (it, other) => { say(W.clashBack(nameOf(other))); o.onClash?.(pub(it), pub(other), api); };
|
|
145
|
+
|
|
146
|
+
/** Try to move item to { s, e, row }. Clashes are refused. first = the bar's rect before (for the glide). */
|
|
147
|
+
const apply = (it, to, first, { record = true, quiet = false, check = true } = {}) => {
|
|
148
|
+
const other = check && clashWith(it, to.s, to.e, to.row);
|
|
149
|
+
if (other) { shake(barOf(it.id)); refuse(it, other); return false; }
|
|
150
|
+
if (to.s === it.s && to.e === it.e && String(to.row) === String(it.row)) return false;
|
|
151
|
+
const before = pub(it);
|
|
152
|
+
if (record) history.push({ id: it.id, s: it.s, e: it.e, row: it.row });
|
|
153
|
+
Object.assign(it, { s: to.s, e: to.e, row: to.row });
|
|
154
|
+
flip(place(it), first);
|
|
155
|
+
if (!quiet) say(`${nameOf(it)}: ${rowOf(it.row)?.label ?? ''}, ${range(it.s, it.e, it.t)}`);
|
|
156
|
+
o.onChange?.(pub(it), before, api);
|
|
157
|
+
return true;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/* ---------- dragging ---------- */
|
|
161
|
+
const lift = (st) => {
|
|
162
|
+
st.live = true; eatClick = true;
|
|
163
|
+
const { bar } = st;
|
|
164
|
+
st.left0 = bar.offsetLeft; st.w0 = bar.offsetWidth; st.sx0 = scroller.scrollLeft; st.sy0 = scroller.scrollTop;
|
|
165
|
+
st.rowIdx = rows.findIndex((r) => String(r.id) === String(st.it.row));
|
|
166
|
+
st.rowH = bar.closest('.tl__row').offsetHeight;
|
|
167
|
+
st.labelW = grid.querySelector('.tl__label')?.offsetWidth || 0;
|
|
168
|
+
bar.classList.add('is-drag'); root.classList.add('is-dragging');
|
|
169
|
+
try { bar.setPointerCapture(st.pid); } catch { /* fine */ }
|
|
170
|
+
st.ghost = document.createElement('div'); st.ghost.className = 'tl__ghost'; st.ghost.innerHTML = '<span></span>';
|
|
171
|
+
if (!RM()) g.fromTo(bar, { scale: 1 }, { scale: 1.04, duration: 0.18, ease: 'back.out(3)' });
|
|
172
|
+
};
|
|
173
|
+
const follow = (st, e) => {
|
|
174
|
+
const { it, bar, mode } = st, D = dayW();
|
|
175
|
+
const dx = e.clientX - st.x0 + (scroller.scrollLeft - st.sx0), dy = e.clientY - st.y0 + (scroller.scrollTop - st.sy0);
|
|
176
|
+
const step = Math.round(dx / D);
|
|
177
|
+
let s = it.s, en = it.e, r = st.rowIdx;
|
|
178
|
+
if (mode === 'move') {
|
|
179
|
+
s += step; en += step; r = Math.max(0, Math.min(rows.length - 1, st.rowIdx + Math.round(dy / st.rowH)));
|
|
180
|
+
g.set(bar, { x: dx, y: dy });
|
|
181
|
+
} else if (mode === 'start') {
|
|
182
|
+
s = Math.min(it.s + step, it.e - o.minDays);
|
|
183
|
+
const px = Math.min(dx, st.w0 - D * o.minDays);
|
|
184
|
+
bar.style.left = `${st.left0 + px}px`; bar.style.width = `${st.w0 - px}px`;
|
|
185
|
+
} else {
|
|
186
|
+
en = Math.max(it.e + step, it.s + o.minDays);
|
|
187
|
+
bar.style.width = `${Math.max(D * o.minDays - 6, st.w0 + dx)}px`;
|
|
188
|
+
}
|
|
189
|
+
const row = rows[r].id, other = clashWith(it, s, en, row);
|
|
190
|
+
st.to = { s, e: en, row }; st.other = other;
|
|
191
|
+
const lane = laneOf(row);
|
|
192
|
+
if (st.ghost.parentElement !== lane) lane.append(st.ghost);
|
|
193
|
+
const a = Math.max(s, from), b = Math.min(en, from + o.days);
|
|
194
|
+
st.ghost.style.setProperty('--k', a - from); st.ghost.style.setProperty('--n', Math.max(0, b - a));
|
|
195
|
+
st.ghost.hidden = b <= a;
|
|
196
|
+
st.ghost.classList.toggle('is-clash', !!other); bar.classList.toggle('is-clash', !!other);
|
|
197
|
+
st.ghost.firstChild.textContent = other ? W.clash(nameOf(other)) : `${range(s, en)} · ${o.sub(pub({ ...it, s, e: en }), span(s, en))}`;
|
|
198
|
+
// keep scrolling while the bar is pulled near an edge
|
|
199
|
+
const box = scroller.getBoundingClientRect(), edge = 36;
|
|
200
|
+
if (e.clientX > box.right - edge) scroller.scrollLeft += 10; else if (e.clientX < box.left + st.labelW + edge) scroller.scrollLeft -= 10;
|
|
201
|
+
};
|
|
202
|
+
const end = (st, cancel) => {
|
|
203
|
+
const { bar, it } = st;
|
|
204
|
+
st.ghost?.remove(); root.classList.remove('is-dragging'); bar.classList.remove('is-drag', 'is-clash');
|
|
205
|
+
const first = bar.getBoundingClientRect();
|
|
206
|
+
if (!cancel && st.to && !st.other && apply(it, st.to, null)) {
|
|
207
|
+
const now = barOf(it.id);
|
|
208
|
+
if (now) {
|
|
209
|
+
now.style.left = ''; now.style.width = ''; g.set(now, { clearProps: 'transform' });
|
|
210
|
+
flip(now, first);
|
|
211
|
+
if (!RM()) g.fromTo(now, { scaleY: 0.86 }, { scaleY: 1, duration: 0.45, ease: 'back.out(3)', delay: 0.3, clearProps: 'transform' });
|
|
212
|
+
}
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
// back to where it was (with a shake if it clashed)
|
|
216
|
+
const back = g.timeline({ onComplete: () => { bar.style.left = ''; bar.style.width = ''; g.set(bar, { clearProps: 'transform' }); } });
|
|
217
|
+
if (RM()) back.progress(1);
|
|
218
|
+
else {
|
|
219
|
+
back.to(bar, { x: 0, y: 0, scale: 1, left: st.left0, width: st.w0, duration: 0.45, ease: 'back.out(1.6)' });
|
|
220
|
+
if (st.other) back.to(bar, { keyframes: { x: [0, -7, 6, -4, 2, 0] }, duration: 0.42, ease: 'power2.out' });
|
|
221
|
+
}
|
|
222
|
+
if (st.other) refuse(it, st.other);
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const ac = new AbortController(), on = { signal: ac.signal };
|
|
226
|
+
grid.addEventListener('pointerdown', (e) => {
|
|
227
|
+
if (e.button > 0) return;
|
|
228
|
+
const bar = e.target.closest('.tl__bar'); const it = bar && byId(bar.dataset.id);
|
|
229
|
+
if (!it) return;
|
|
230
|
+
const lk = lock(it);
|
|
231
|
+
let mode = e.target.closest('.tl__grip--s') ? 'start' : e.target.closest('.tl__grip--e') ? 'end' : 'move';
|
|
232
|
+
if (lk === 'all') return;
|
|
233
|
+
if (lk === 'start') { if (mode !== 'end' && e.pointerType !== 'touch') return; mode = 'end'; } // only longer: a hold on a phone stretches it
|
|
234
|
+
drag = { bar, it, mode, x0: e.clientX, y0: e.clientY, pid: e.pointerId, touch: e.pointerType === 'touch', live: false };
|
|
235
|
+
eatClick = false;
|
|
236
|
+
if (drag.touch) { const st = drag; st.timer = setTimeout(() => { if (drag === st) { lift(st); say(W.picked(nameOf(it))); } }, 380); }
|
|
237
|
+
}, on);
|
|
238
|
+
addEventListener('pointermove', (e) => {
|
|
239
|
+
const st = drag; if (!st || e.pointerId !== st.pid) return;
|
|
240
|
+
const far = Math.hypot(e.clientX - st.x0, e.clientY - st.y0);
|
|
241
|
+
if (!st.live) {
|
|
242
|
+
if (st.touch) { if (far > 8) { clearTimeout(st.timer); drag = null; } return; } // a swipe: let it scroll
|
|
243
|
+
if (far < 4) return;
|
|
244
|
+
lift(st);
|
|
245
|
+
}
|
|
246
|
+
follow(st, e);
|
|
247
|
+
}, on);
|
|
248
|
+
const up = (cancel) => (e) => {
|
|
249
|
+
const st = drag; if (!st || e.pointerId !== st.pid) return;
|
|
250
|
+
clearTimeout(st.timer); drag = null;
|
|
251
|
+
if (st.live) { end(st, cancel); setTimeout(() => { eatClick = false; }, 0); } // the click right after a drag is eaten, later ones are not
|
|
252
|
+
};
|
|
253
|
+
addEventListener('pointerup', up(false), on);
|
|
254
|
+
addEventListener('pointercancel', up(true), on);
|
|
255
|
+
root.addEventListener('touchmove', (e) => { if (drag?.live) e.preventDefault(); }, { passive: false, signal: ac.signal });
|
|
256
|
+
root.addEventListener('contextmenu', (e) => { if (e.target.closest('.tl__bar')) e.preventDefault(); }, on);
|
|
257
|
+
|
|
258
|
+
grid.addEventListener('click', (e) => {
|
|
259
|
+
if (eatClick) { eatClick = false; return; } // the click that ends a drag (it may land on a lane or another bar)
|
|
260
|
+
const bar = e.target.closest('.tl__bar');
|
|
261
|
+
if (bar) { const it = byId(bar.dataset.id); if (it) o.onOpen?.(pub(it), bar, api); return; }
|
|
262
|
+
const lane = e.target.closest('.tl__lane');
|
|
263
|
+
if (lane && o.onAdd && o.edit) {
|
|
264
|
+
const k = Math.floor((e.clientX - lane.getBoundingClientRect().left) / dayW());
|
|
265
|
+
o.onAdd({ row: rowOf(lane.parentElement.dataset.row)?.id ?? lane.parentElement.dataset.row, start: ds(from + k) }, api);
|
|
266
|
+
}
|
|
267
|
+
}, on);
|
|
268
|
+
grid.addEventListener('keydown', (e) => {
|
|
269
|
+
const bar = e.target.closest('.tl__bar'); const it = bar && byId(bar.dataset.id);
|
|
270
|
+
if (!it) return;
|
|
271
|
+
const lk = lock(it); if (lk === 'all') return;
|
|
272
|
+
const r = rows.findIndex((x) => String(x.id) === String(it.row));
|
|
273
|
+
const to = { s: it.s, e: it.e, row: it.row };
|
|
274
|
+
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
|
|
275
|
+
const d = e.key === 'ArrowLeft' ? -1 : 1;
|
|
276
|
+
if (e.shiftKey || lk === 'start') to.e = Math.max(it.s + o.minDays, it.e + d); else { to.s += d; to.e += d; }
|
|
277
|
+
} else if (lk === 'start') return;
|
|
278
|
+
else if (e.key === 'ArrowUp' && r > 0) to.row = rows[r - 1].id;
|
|
279
|
+
else if (e.key === 'ArrowDown' && r < rows.length - 1) to.row = rows[r + 1].id;
|
|
280
|
+
else return;
|
|
281
|
+
e.preventDefault();
|
|
282
|
+
apply(it, to, bar.getBoundingClientRect());
|
|
283
|
+
barOf(it.id)?.focus();
|
|
284
|
+
}, on);
|
|
285
|
+
const tick = setInterval(() => { drawNow(); items.forEach((it) => { if (it.status === 'out') { const b = barOf(it.id); if (b) fill(b, it); } }); }, 60000);
|
|
286
|
+
|
|
287
|
+
/* ---------- API ---------- */
|
|
288
|
+
const api = {
|
|
289
|
+
el: root,
|
|
290
|
+
get from() { return ds(from); },
|
|
291
|
+
items: () => items.map(pub),
|
|
292
|
+
setItems(list) { items = (list || []).map(norm); history.length = 0; render(); return api; },
|
|
293
|
+
add(item) {
|
|
294
|
+
const it = norm(item);
|
|
295
|
+
const other = clashWith(it, it.s, it.e, it.row);
|
|
296
|
+
if (other) { refuse(it, other); return null; }
|
|
297
|
+
items.push(it); const bar = place(it);
|
|
298
|
+
if (bar && !RM()) g.fromTo(bar, { scaleX: 0, opacity: 0 }, { scaleX: 1, opacity: 1, transformOrigin: '0% 50%', duration: 0.5, ease: 'back.out(1.6)', clearProps: 'transform,opacity' });
|
|
299
|
+
say(`${nameOf(it)}: ${range(it.s, it.e, it.t)}`);
|
|
300
|
+
return pub(it);
|
|
301
|
+
},
|
|
302
|
+
update(id, patch) {
|
|
303
|
+
const it = byId(id); if (!it) return null;
|
|
304
|
+
const first = barOf(id)?.getBoundingClientRect();
|
|
305
|
+
const { start, end, row, ...rest } = patch;
|
|
306
|
+
Object.assign(it, rest);
|
|
307
|
+
const to = { s: start != null ? dn(start) : it.s, e: end != null ? dn(end) : it.e, row: row ?? it.row };
|
|
308
|
+
if (!apply(it, to, first)) place(it); // nothing moved (or it clashed): still show the new label / status
|
|
309
|
+
return pub(it);
|
|
310
|
+
},
|
|
311
|
+
remove(id) {
|
|
312
|
+
const it = byId(id); if (!it) return api;
|
|
313
|
+
items = items.filter((x) => x !== it);
|
|
314
|
+
const bar = barOf(id);
|
|
315
|
+
if (bar) { if (RM()) bar.remove(); else g.to(bar, { scaleX: 0, opacity: 0, transformOrigin: '0% 50%', duration: 0.3, ease: 'power2.in', onComplete: () => bar.remove() }); }
|
|
316
|
+
return api;
|
|
317
|
+
},
|
|
318
|
+
/** Put the last change back. Returns false when there is nothing to undo. */
|
|
319
|
+
undo() {
|
|
320
|
+
const h = history.pop(); if (!h) return false;
|
|
321
|
+
const it = byId(h.id); if (!it) return api.undo();
|
|
322
|
+
const ok = apply(it, { s: h.s, e: h.e, row: h.row }, barOf(it.id)?.getBoundingClientRect(), { record: false, quiet: true, check: false });
|
|
323
|
+
if (ok) say(W.undone(nameOf(it)));
|
|
324
|
+
return ok;
|
|
325
|
+
},
|
|
326
|
+
/** Show other days: a date, or a number of days to move by (+7 = a week later). */
|
|
327
|
+
go(where) {
|
|
328
|
+
const next = typeof where === 'number' ? from + where : startDay(where);
|
|
329
|
+
if (next === from) return api;
|
|
330
|
+
const dir = next > from ? 1 : -1; from = next; render();
|
|
331
|
+
if (!RM()) g.fromTo(grid.querySelectorAll('.tl__days, .tl__lane'), { x: 36 * dir, opacity: 0 }, { x: 0, opacity: 1, duration: 0.42, ease: 'power3.out', stagger: 0.02, clearProps: 'transform,opacity' });
|
|
332
|
+
say(range(from, from + o.days - 1));
|
|
333
|
+
return api;
|
|
334
|
+
},
|
|
335
|
+
today() { return api.go(today - lead - from); },
|
|
336
|
+
destroy() { ac.abort(); clearInterval(tick); el.innerHTML = ''; },
|
|
337
|
+
};
|
|
338
|
+
render(true);
|
|
339
|
+
return api;
|
|
340
|
+
};
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/* Time picker, two looks.
|
|
2
|
+
'wheel': hour and minute columns you scroll, drag or flick like a phone's clock. The numbers curve
|
|
3
|
+
away round a drum, the one in the middle band is the value, and it always settles on a time that
|
|
4
|
+
is allowed (outside opening hours or taken times are dimmed and skipped).
|
|
5
|
+
'slots': a grid of time buttons in Morning / Afternoon / Evening. The highlight slides from the
|
|
6
|
+
old time to the new one, stretching a little on the way; taken times are crossed out. */
|
|
7
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
8
|
+
import { esc } from '../index.js';
|
|
9
|
+
|
|
10
|
+
const { g, RM, $$ } = M;
|
|
11
|
+
const WORDS = { label: 'Time', hours: 'Hours', minutes: 'Minutes', period: 'AM or PM', am: 'AM', pm: 'PM', morning: 'Morning', afternoon: 'Afternoon', evening: 'Evening', taken: 'Not available', none: 'No times left' };
|
|
12
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
13
|
+
const toMin = (t) => { const m = /^(\d{1,2}):(\d{2})/.exec(String(t ?? '')); return m ? Math.min(1439, +m[1] * 60 + +m[2]) : null; };
|
|
14
|
+
const toTime = (n) => `${pad(Math.floor(n / 60))}:${pad(n % 60)}`;
|
|
15
|
+
|
|
16
|
+
/** '14:30' → '14:30', or '2:30 PM' with hour12. */
|
|
17
|
+
export const formatTime = (t, { hour12 = false, am = 'AM', pm = 'PM' } = {}) => {
|
|
18
|
+
const n = toMin(t); if (n == null) return '';
|
|
19
|
+
if (!hour12) return toTime(n);
|
|
20
|
+
const h = Math.floor(n / 60);
|
|
21
|
+
return `${h % 12 || 12}:${pad(n % 60)} ${h < 12 ? am : pm}`;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* const tp = timePicker(el, {
|
|
26
|
+
* look: 'wheel' | 'slots',
|
|
27
|
+
* value: '09:30', // 'HH:MM', 24-hour (wheel: defaults to the nearest allowed time to now)
|
|
28
|
+
* step: 5, // minutes between choices (slots: 30)
|
|
29
|
+
* min: '08:00', max: '20:00',
|
|
30
|
+
* disabled: ['12:00', '12:30'] | (time) => true, // times that can't be picked
|
|
31
|
+
* hour12: false, // show 2:30 PM instead of 14:30 (the value stays 24-hour)
|
|
32
|
+
* words: { hours, minutes, morning, taken, … },
|
|
33
|
+
* onChange(value, tp)
|
|
34
|
+
* })
|
|
35
|
+
* tp.value · tp.set('10:00') · tp.setDisabled(list | fn) · tp.destroy()
|
|
36
|
+
* Wheel size: --tp-item (38px row) · --tp-rows (5 rows shown).
|
|
37
|
+
*/
|
|
38
|
+
export const timePicker = (el, opts = {}) => {
|
|
39
|
+
el = $$(el)[0];
|
|
40
|
+
if (!el) return null;
|
|
41
|
+
const wheel = (opts.look || 'wheel') !== 'slots';
|
|
42
|
+
const o = { look: wheel ? 'wheel' : 'slots', value: null, step: wheel ? 5 : 30, min: '00:00', max: '23:59', disabled: null, hour12: false, onChange: null, ...opts };
|
|
43
|
+
const W = { ...WORDS, ...o.words };
|
|
44
|
+
const step = Math.max(1, Math.min(60, +o.step || 5));
|
|
45
|
+
const lo = toMin(o.min) ?? 0, hi = toMin(o.max) ?? 1439;
|
|
46
|
+
let blocked = () => false;
|
|
47
|
+
const setBlocked = (d) => { blocked = typeof d === 'function' ? (n) => !!d(toTime(n)) : (() => { const s = new Set((d || []).map(toMin)); return (n) => s.has(n); })(); };
|
|
48
|
+
setBlocked(o.disabled);
|
|
49
|
+
const ok = (n) => n >= lo && n <= hi && (n % 60) % step === 0 && !blocked(n);
|
|
50
|
+
const fmt = (n) => formatTime(toTime(n), { hour12: o.hour12, am: W.am, pm: W.pm });
|
|
51
|
+
/** Every allowed time, in order. */
|
|
52
|
+
const every = () => { const out = []; for (let h = Math.floor(lo / 60); h <= Math.floor(hi / 60); h++) for (let m = 0; m < 60; m += step) { const n = h * 60 + m; if (n >= lo && n <= hi) out.push(n); } return out; };
|
|
53
|
+
const allowed = () => every().filter(ok);
|
|
54
|
+
const nearest = (n) => { const a = allowed(); if (!a.length) return null; return a.reduce((b, x) => (Math.abs(x - n) < Math.abs(b - n) ? x : b), a[0]); };
|
|
55
|
+
|
|
56
|
+
let value = toMin(o.value);
|
|
57
|
+
const ac = new AbortController(), on = { signal: ac.signal };
|
|
58
|
+
let api;
|
|
59
|
+
|
|
60
|
+
/* ======================= wheel ======================= */
|
|
61
|
+
const buildWheel = () => {
|
|
62
|
+
const H = Array.from({ length: 24 }, (_, i) => i).filter((h) => h * 60 + 59 >= lo && h * 60 <= hi);
|
|
63
|
+
const Mi = Array.from({ length: Math.ceil(60 / step) }, (_, i) => i * step);
|
|
64
|
+
// columns: hours (24h or 12h), minutes, and AM/PM for 12h
|
|
65
|
+
const cols = o.hour12
|
|
66
|
+
? [{ key: 'h', label: W.hours, items: [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((h) => ({ v: h % 12, text: String(h) })) },
|
|
67
|
+
{ key: 'm', label: W.minutes, items: Mi.map((m) => ({ v: m, text: pad(m) })) },
|
|
68
|
+
{ key: 'p', label: W.period, items: [{ v: 0, text: W.am }, { v: 12, text: W.pm }] }]
|
|
69
|
+
: [{ key: 'h', label: W.hours, items: H.map((h) => ({ v: h, text: pad(h) })) },
|
|
70
|
+
{ key: 'm', label: W.minutes, items: Mi.map((m) => ({ v: m, text: pad(m) })) }];
|
|
71
|
+
|
|
72
|
+
el.innerHTML = `<div class="tp tp--wheel" role="group" aria-label="${esc(W.label)}"><div class="tp__band" aria-hidden="true"></div>`
|
|
73
|
+
+ cols.map((c, ci) => `${ci === 1 ? '<span class="tp__sep" aria-hidden="true">:</span>' : ''}<div class="tp__col tp__col--${c.key}" tabindex="0" role="spinbutton" aria-label="${esc(c.label)}"><div class="tp__track">${c.items.map((x, i) => `<div class="tp__item" data-i="${i}">${esc(x.text)}</div>`).join('')}</div></div>`).join('')
|
|
74
|
+
+ '</div>';
|
|
75
|
+
const root = el.firstElementChild;
|
|
76
|
+
const colEls = [...root.querySelectorAll('.tp__col')];
|
|
77
|
+
cols.forEach((c, i) => { c.el = colEls[i]; c.rows = [...colEls[i].querySelectorAll('.tp__item')]; c.i = 0; });
|
|
78
|
+
const C = Object.fromEntries(cols.map((c) => [c.key, c]));
|
|
79
|
+
const rowH = () => cols[0].rows[0]?.offsetHeight || 38;
|
|
80
|
+
|
|
81
|
+
// what each column's choices mean, given the others
|
|
82
|
+
const timeOf = (pick) => {
|
|
83
|
+
const h = o.hour12 ? C.h.items[pick.h].v + C.p.items[pick.p].v : C.h.items[pick.h].v;
|
|
84
|
+
return h * 60 + C.m.items[pick.m].v;
|
|
85
|
+
};
|
|
86
|
+
const current = () => Object.fromEntries(cols.map((c) => [c.key, c.i]));
|
|
87
|
+
const indexFor = (n) => {
|
|
88
|
+
const h = Math.floor(n / 60), m = n % 60;
|
|
89
|
+
const out = { m: C.m.items.findIndex((x) => x.v === m) };
|
|
90
|
+
if (o.hour12) { out.h = C.h.items.findIndex((x) => x.v === h % 12); out.p = h < 12 ? 0 : 1; }
|
|
91
|
+
else out.h = C.h.items.findIndex((x) => x.v === h);
|
|
92
|
+
return out;
|
|
93
|
+
};
|
|
94
|
+
/** Dim the choices that can't make an allowed time with the other columns as they are. */
|
|
95
|
+
const shade = () => {
|
|
96
|
+
const cur = current();
|
|
97
|
+
cols.forEach((c) => c.items.forEach((_, i) => {
|
|
98
|
+
let any = false;
|
|
99
|
+
if (c.key === 'm') any = ok(timeOf({ ...cur, m: i }));
|
|
100
|
+
else if (c.key === 'h') any = C.m.items.some((_, mi) => ok(timeOf({ ...cur, h: i, m: mi })));
|
|
101
|
+
else any = C.h.items.some((_, hi2) => C.m.items.some((_, mi) => ok(timeOf({ ...cur, p: i, h: hi2, m: mi }))));
|
|
102
|
+
c.rows[i].classList.toggle('is-off', !any);
|
|
103
|
+
}));
|
|
104
|
+
};
|
|
105
|
+
/** Curve the rows round the drum, from how far each is from the middle. */
|
|
106
|
+
const paint = (c) => {
|
|
107
|
+
const h = rowH(), mid = c.el.scrollTop / h, rm = RM();
|
|
108
|
+
c.rows.forEach((r, i) => {
|
|
109
|
+
const d = i - mid, a = Math.min(Math.abs(d), 3);
|
|
110
|
+
r.style.opacity = String(Math.max(0.12, 1 - a * 0.28));
|
|
111
|
+
r.style.transform = rm ? '' : `rotateX(${Math.max(-70, Math.min(70, -d * 20))}deg) scale(${1 - a * 0.05})`;
|
|
112
|
+
r.classList.toggle('is-mid', Math.abs(d) < 0.5);
|
|
113
|
+
});
|
|
114
|
+
};
|
|
115
|
+
const aria = () => cols.forEach((c) => { c.el.setAttribute('aria-valuetext', c.items[c.i].text); c.el.setAttribute('aria-valuenow', String(c.i)); c.el.setAttribute('aria-valuemin', '0'); c.el.setAttribute('aria-valuemax', String(c.items.length - 1)); });
|
|
116
|
+
const go = (c, i, smooth = true) => {
|
|
117
|
+
c.i = i;
|
|
118
|
+
c.el.scrollTo({ top: i * rowH(), behavior: smooth && !RM() ? 'smooth' : 'auto' });
|
|
119
|
+
if (!smooth || RM()) paint(c);
|
|
120
|
+
};
|
|
121
|
+
const show = (n, smooth = true) => { const idx = indexFor(n); cols.forEach((c) => { if (idx[c.key] >= 0) go(c, idx[c.key], smooth); }); shade(); aria(); };
|
|
122
|
+
|
|
123
|
+
const commit = (n) => {
|
|
124
|
+
if (n == null) return;
|
|
125
|
+
const changed = n !== value; value = n;
|
|
126
|
+
aria();
|
|
127
|
+
if (changed) o.onChange?.(toTime(n), api);
|
|
128
|
+
};
|
|
129
|
+
/** After a column stops: read it, and move to the nearest allowed time if needed. */
|
|
130
|
+
const settle = (c) => {
|
|
131
|
+
const i = Math.max(0, Math.min(c.items.length - 1, Math.round(c.el.scrollTop / rowH())));
|
|
132
|
+
c.i = i;
|
|
133
|
+
const n = timeOf(current());
|
|
134
|
+
if (ok(n)) { if (Math.abs(c.el.scrollTop - i * rowH()) > 1) go(c, i); shade(); commit(n); return; }
|
|
135
|
+
// not allowed: keep this column's choice if possible, else the nearest time overall
|
|
136
|
+
const keep = allowed().filter((x) => indexFor(x)[c.key] === i);
|
|
137
|
+
const target = keep.length ? keep.reduce((b, x) => (Math.abs(x - n) < Math.abs(b - n) ? x : b), keep[0]) : nearest(n);
|
|
138
|
+
if (target == null) return;
|
|
139
|
+
show(target); commit(target);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
cols.forEach((c) => {
|
|
143
|
+
let t = null, raf = 0;
|
|
144
|
+
c.el.addEventListener('scroll', () => {
|
|
145
|
+
if (!raf) raf = requestAnimationFrame(() => { raf = 0; paint(c); });
|
|
146
|
+
clearTimeout(t); if (!c.drag) t = setTimeout(() => settle(c), 130);
|
|
147
|
+
}, { passive: true, signal: ac.signal });
|
|
148
|
+
// clicking a row scrolls it to the middle
|
|
149
|
+
c.el.addEventListener('click', (e) => { const r = e.target.closest('.tp__item'); if (!r || c.moved) return; go(c, +r.dataset.i); }, on);
|
|
150
|
+
// a mouse drags the column (touch and trackpads scroll it themselves)
|
|
151
|
+
c.el.addEventListener('pointerdown', (e) => {
|
|
152
|
+
if (e.pointerType !== 'mouse' || e.button > 0) return;
|
|
153
|
+
e.preventDefault(); c.el.focus({ preventScroll: true });
|
|
154
|
+
const y0 = e.clientY, s0 = c.el.scrollTop; let last = e.clientY, lt = performance.now(), v = 0;
|
|
155
|
+
c.drag = true; c.moved = false; c.el.classList.add('is-drag');
|
|
156
|
+
const move = (ev) => {
|
|
157
|
+
const now = performance.now(); v = (ev.clientY - last) / Math.max(1, now - lt); last = ev.clientY; lt = now;
|
|
158
|
+
if (Math.abs(ev.clientY - y0) > 3) c.moved = true;
|
|
159
|
+
c.el.scrollTop = s0 - (ev.clientY - y0);
|
|
160
|
+
};
|
|
161
|
+
const up = () => {
|
|
162
|
+
removeEventListener('pointermove', move); removeEventListener('pointerup', up); removeEventListener('pointercancel', up);
|
|
163
|
+
c.el.classList.remove('is-drag'); c.drag = false;
|
|
164
|
+
const h = rowH(), fling = RM() ? 0 : -v * 140; // a flick carries on a little
|
|
165
|
+
const i = Math.max(0, Math.min(c.items.length - 1, Math.round((c.el.scrollTop + fling) / h)));
|
|
166
|
+
go(c, i); setTimeout(() => { c.moved = false; }, 0);
|
|
167
|
+
setTimeout(() => settle(c), RM() ? 0 : 320);
|
|
168
|
+
};
|
|
169
|
+
addEventListener('pointermove', move); addEventListener('pointerup', up); addEventListener('pointercancel', up);
|
|
170
|
+
}, on);
|
|
171
|
+
c.el.addEventListener('keydown', (e) => {
|
|
172
|
+
const n = { ArrowUp: -1, ArrowDown: 1, PageUp: -5, PageDown: 5 }[e.key];
|
|
173
|
+
let i = c.i;
|
|
174
|
+
if (n) { i = c.i + n; for (let k = 0; k < c.items.length && c.rows[Math.max(0, Math.min(c.items.length - 1, i))]?.classList.contains('is-off'); k++) i += Math.sign(n); }
|
|
175
|
+
else if (e.key === 'Home') i = c.rows.findIndex((r) => !r.classList.contains('is-off'));
|
|
176
|
+
else if (e.key === 'End') i = c.rows.length - 1 - [...c.rows].reverse().findIndex((r) => !r.classList.contains('is-off'));
|
|
177
|
+
else return;
|
|
178
|
+
e.preventDefault();
|
|
179
|
+
go(c, Math.max(0, Math.min(c.items.length - 1, i)), false); settle(c);
|
|
180
|
+
}, on);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
const ro = new ResizeObserver(() => { cols.forEach((c) => { c.el.scrollTop = c.i * rowH(); paint(c); }); });
|
|
184
|
+
ro.observe(root);
|
|
185
|
+
ac.signal.addEventListener('abort', () => ro.disconnect());
|
|
186
|
+
|
|
187
|
+
value = value != null && ok(value) ? value : nearest(value ?? (() => { const d = new Date(); return d.getHours() * 60 + d.getMinutes(); })());
|
|
188
|
+
if (value != null) show(value, false); else { shade(); aria(); }
|
|
189
|
+
return {
|
|
190
|
+
root,
|
|
191
|
+
set: (n, silent) => { const t = ok(n) ? n : nearest(n); if (t == null) return; show(t, !silent); if (silent) value = t; else commit(t); },
|
|
192
|
+
refresh: () => { shade(); if (value != null && !ok(value)) { const t = nearest(value); if (t != null) { show(t); commit(t); } } },
|
|
193
|
+
};
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
/* ======================= slots ======================= */
|
|
197
|
+
const buildSlots = () => {
|
|
198
|
+
el.innerHTML = `<div class="tp tp--slots" role="group" aria-label="${esc(W.label)}"><div class="tp__slots"><span class="tp__mark" aria-hidden="true"></span></div><p class="tp__empty" hidden>${esc(W.none)}</p></div>`;
|
|
199
|
+
const root = el.firstElementChild, wrap = root.querySelector('.tp__slots'), mark = wrap.querySelector('.tp__mark');
|
|
200
|
+
const part = (n) => (n < 720 ? W.morning : n < 1020 ? W.afternoon : W.evening);
|
|
201
|
+
const render = () => {
|
|
202
|
+
const all = every();
|
|
203
|
+
let html = '', grp = null;
|
|
204
|
+
all.forEach((n) => {
|
|
205
|
+
if (part(n) !== grp) { grp = part(n); html += `<span class="tp__group">${esc(grp)}</span>`; }
|
|
206
|
+
const off = !ok(n);
|
|
207
|
+
html += `<button type="button" class="tp__slot${off ? ' is-off' : ''}${n === value ? ' is-on' : ''}" data-t="${n}" aria-pressed="${n === value}"${off ? ` disabled title="${esc(W.taken)}"` : ''} tabindex="-1">${esc(fmt(n))}</button>`;
|
|
208
|
+
});
|
|
209
|
+
wrap.querySelectorAll('.tp__group, .tp__slot').forEach((x) => x.remove());
|
|
210
|
+
wrap.insertAdjacentHTML('beforeend', html);
|
|
211
|
+
root.querySelector('.tp__empty').hidden = all.some(ok);
|
|
212
|
+
roving();
|
|
213
|
+
};
|
|
214
|
+
const slots = () => [...wrap.querySelectorAll('.tp__slot')];
|
|
215
|
+
const live = () => slots().filter((b) => !b.disabled);
|
|
216
|
+
const slotOf = (n) => wrap.querySelector(`.tp__slot[data-t="${n}"]`);
|
|
217
|
+
const roving = (focus) => {
|
|
218
|
+
const l = live(), cur = (value != null && slotOf(value) && !slotOf(value).disabled ? slotOf(value) : null) || focus || l[0];
|
|
219
|
+
l.forEach((b) => { b.tabIndex = b === cur ? 0 : -1; });
|
|
220
|
+
};
|
|
221
|
+
/** Slide the highlight to a slot (stretching between the two places). */
|
|
222
|
+
const moveMark = (b, animate) => {
|
|
223
|
+
if (!b) { g.to(mark, { opacity: 0, duration: RM() ? 0 : 0.15 }); return; }
|
|
224
|
+
const to = { x: b.offsetLeft, y: b.offsetTop, width: b.offsetWidth, height: b.offsetHeight };
|
|
225
|
+
const shown = +getComputedStyle(mark).opacity > 0.5;
|
|
226
|
+
if (!animate || RM()) { g.killTweensOf(mark); g.set(mark, { ...to, opacity: 1, scale: 1 }); return; }
|
|
227
|
+
if (!shown) { g.set(mark, to); g.fromTo(mark, { opacity: 0, scale: 0.6 }, { opacity: 1, scale: 1, duration: 0.35, ease: 'back.out(2)', overwrite: true }); return; }
|
|
228
|
+
const from = { x: +g.getProperty(mark, 'x'), y: +g.getProperty(mark, 'y'), width: mark.offsetWidth, height: mark.offsetHeight };
|
|
229
|
+
const sameRow = Math.abs(from.y - to.y) < 2;
|
|
230
|
+
g.killTweensOf(mark); const tl = g.timeline();
|
|
231
|
+
if (sameRow) { // stretch across, then let the back end catch up
|
|
232
|
+
const left = Math.min(from.x, to.x), right = Math.max(from.x + from.width, to.x + to.width);
|
|
233
|
+
tl.to(mark, { x: left, width: right - left, duration: 0.16, ease: 'power2.in' })
|
|
234
|
+
.to(mark, { x: to.x, width: to.width, duration: 0.3, ease: 'power3.out' });
|
|
235
|
+
} else tl.to(mark, { ...to, duration: 0.4, ease: 'power3.inOut' })
|
|
236
|
+
.fromTo(mark, { scaleX: 1 }, { keyframes: { scaleX: [1, 1.08, 1], scaleY: [1, 0.9, 1] }, duration: 0.4, ease: 'power2.out' }, 0);
|
|
237
|
+
tl.set(mark, { opacity: 1 }, 0);
|
|
238
|
+
};
|
|
239
|
+
const choose = (n, { silent = false, animate = true } = {}) => {
|
|
240
|
+
const prev = value; value = n;
|
|
241
|
+
slots().forEach((b) => { const on = +b.dataset.t === n; b.classList.toggle('is-on', on); b.setAttribute('aria-pressed', String(on)); });
|
|
242
|
+
moveMark(n == null ? null : slotOf(n), animate);
|
|
243
|
+
roving();
|
|
244
|
+
if (!silent && prev !== n) o.onChange?.(n == null ? null : toTime(n), api);
|
|
245
|
+
};
|
|
246
|
+
wrap.addEventListener('click', (e) => { const b = e.target.closest('.tp__slot'); if (!b || b.disabled) return; choose(+b.dataset.t); }, on);
|
|
247
|
+
wrap.addEventListener('keydown', (e) => {
|
|
248
|
+
const b = e.target.closest('.tp__slot'); if (!b) return;
|
|
249
|
+
const l = live(), i = l.indexOf(b);
|
|
250
|
+
let next = null;
|
|
251
|
+
if (e.key === 'ArrowRight') next = l[i + 1];
|
|
252
|
+
else if (e.key === 'ArrowLeft') next = l[i - 1];
|
|
253
|
+
else if (e.key === 'Home') next = l[0];
|
|
254
|
+
else if (e.key === 'End') next = l.at(-1);
|
|
255
|
+
else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { // the slot above or below, closest across
|
|
256
|
+
const dir = e.key === 'ArrowDown' ? 1 : -1, cx = b.offsetLeft + b.offsetWidth / 2;
|
|
257
|
+
const rows = l.filter((x) => Math.sign(x.offsetTop - b.offsetTop) === dir);
|
|
258
|
+
if (rows.length) { const y = dir > 0 ? Math.min(...rows.map((x) => x.offsetTop)) : Math.max(...rows.map((x) => x.offsetTop)); next = rows.filter((x) => x.offsetTop === y).reduce((a, x) => (Math.abs(x.offsetLeft + x.offsetWidth / 2 - cx) < Math.abs(a.offsetLeft + a.offsetWidth / 2 - cx) ? x : a)); }
|
|
259
|
+
} else return;
|
|
260
|
+
e.preventDefault();
|
|
261
|
+
if (next) { l.forEach((x) => { x.tabIndex = x === next ? 0 : -1; }); next.focus(); }
|
|
262
|
+
}, on);
|
|
263
|
+
const ro = new ResizeObserver(() => { if (value != null && slotOf(value)) moveMark(slotOf(value), false); });
|
|
264
|
+
ro.observe(wrap);
|
|
265
|
+
ac.signal.addEventListener('abort', () => ro.disconnect());
|
|
266
|
+
|
|
267
|
+
if (value != null && !ok(value)) value = null;
|
|
268
|
+
render(); g.set(mark, { opacity: 0 });
|
|
269
|
+
if (value != null) requestAnimationFrame(() => moveMark(slotOf(value), false));
|
|
270
|
+
return {
|
|
271
|
+
root,
|
|
272
|
+
set: (n, silent) => choose(n != null && ok(n) ? n : null, { silent }),
|
|
273
|
+
refresh: () => { render(); const keep = value != null && ok(value) ? value : null; choose(keep, { silent: keep === value, animate: false }); },
|
|
274
|
+
};
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
const view = wheel ? buildWheel() : buildSlots();
|
|
278
|
+
api = {
|
|
279
|
+
el: view.root, opts: o,
|
|
280
|
+
/** 'HH:MM' (24-hour), or null when nothing is picked (slots). */
|
|
281
|
+
get value() { return value == null ? null : toTime(value); },
|
|
282
|
+
/** Pick a time ('HH:MM'); on the wheel a time that isn't allowed goes to the nearest one that is. */
|
|
283
|
+
set(t, { silent = false } = {}) { view.set(toMin(t), silent); return api; },
|
|
284
|
+
/** Change which times are taken: a list of 'HH:MM' or (time) => true. */
|
|
285
|
+
setDisabled(d) { setBlocked(d); view.refresh(); return api; },
|
|
286
|
+
format: (t) => formatTime(t ?? api.value, { hour12: o.hour12, am: W.am, pm: W.pm }),
|
|
287
|
+
destroy() { ac.abort(); g.killTweensOf(el.querySelectorAll('*')); el.innerHTML = ''; },
|
|
288
|
+
};
|
|
289
|
+
return api;
|
|
290
|
+
};
|