@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,393 @@
1
+ /* Notification feed: a list of notifications, newest first, grouped by day. Unread ones carry a dot;
2
+ opening one, or "Mark all as read", lets the dots go (one after another, top to bottom).
3
+ A new notification slides in at the top. If the reader has scrolled down, the list stays still
4
+ and a "2 new" pill waits at the top instead. Rows can carry buttons (Accept / Decline) that show
5
+ their own progress and then turn into a short result ("Accepted"), and rows can be dismissed. */
6
+ import * as M from '@gecko-ui-kit/motion';
7
+ import { icon } from '@gecko-ui-kit/icons';
8
+ import { esc, av, bindTabs } from '../index.js';
9
+
10
+ const { g, RM, $$ } = M;
11
+ const WORDS = {
12
+ title: 'Notifications', all: 'All', unread: 'Unread', markAll: 'Mark all as read',
13
+ today: 'Today', yesterday: 'Yesterday', earlier: 'Earlier', now: 'Just now',
14
+ empty: 'No notifications', emptyBody: 'New ones will show up here.',
15
+ emptyUnread: 'You’re all caught up', emptyUnreadBody: 'Nothing unread right now.',
16
+ newer: (n) => `${n} new`, dismiss: 'Dismiss', unreadMark: 'Unread',
17
+ fresh: (t) => `New notification: ${t}`, allRead: 'All marked as read', dismissed: 'Dismissed',
18
+ failed: 'That didn’t work. Please try again.',
19
+ };
20
+ const ORDER = ['today', 'yesterday', 'earlier', 'all'];
21
+ const TONES = ['accent', 'good', 'warn', 'bad', 'plain', 'indigo', 'teal', 'rose', 'amber', 'violet', 'green', 'slate', 'sky'];
22
+
23
+ /**
24
+ * const nf = notifications(el, {
25
+ * items: [{
26
+ * id, time, // Date | ms | ISO string (default: now)
27
+ * title, body, meta, // plain text; meta is a small word after the time ("Roadmap")
28
+ * person: { name, ini, tone },// avatar + the name in bold before the title
29
+ * icon: 'chat', tone: 'accent'|'good'|'warn'|'bad'|'plain'|'indigo'…, // icon tile, or a small badge on the avatar
30
+ * html, // trusted markup instead of person + title
31
+ * href, // the row becomes a link
32
+ * read: false,
33
+ * actions: [{ id: 'accept', label: 'Accept', variant: 'primary', done: 'Accepted' }],
34
+ * dismissible: true,
35
+ * }],
36
+ * group: true, // Today · Yesterday · Earlier
37
+ * filter: 'all' | 'unread',
38
+ * header: true, tabs: true, markAll: true, dismissible: true,
39
+ * height: 420, // the list scrolls past this; 0 = grow with the list
40
+ * plain: false, // no border or background (for inside a popover or a card)
41
+ * locale: undefined, when: (date) => string, // your own time text
42
+ * words: { title, all, unread, markAll, today, yesterday, earlier, now, empty, … },
43
+ * onOpen(item, nf), onAction(item, actionId, nf) → Promise<string | false | void>,
44
+ * onDismiss(item, nf), onChange(unreadCount, nf)
45
+ * })
46
+ * nf.items · nf.unread · nf.filter · nf.add(item | items) · nf.update(id, patch) · nf.read(id | ids, read = true)
47
+ * nf.readAll() · nf.remove(id) · nf.setFilter('unread') · nf.setItems(items) · nf.destroy()
48
+ */
49
+ export const notifications = (el, opts = {}) => {
50
+ el = $$(el)[0];
51
+ if (!el) return null;
52
+ const o = { items: [], group: true, filter: 'all', header: true, tabs: true, markAll: true, dismissible: true, height: 420, plain: false,
53
+ locale: undefined, when: null, emptyIcon: 'bell', onOpen: null, onAction: null, onDismiss: null, onChange: null, ...opts };
54
+ const W = { ...WORDS, ...o.words };
55
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
56
+ const calls = [];
57
+ let filter = o.filter === 'unread' ? 'unread' : 'all', list = [], pending = [], seq = 0, dead = false;
58
+ const els = new Map(), groups = new Map(), keep = new Set();
59
+
60
+ const h = o.height ? (typeof o.height === 'number' ? `${o.height}px` : o.height) : 'none';
61
+ el.innerHTML = `<div class="nf${o.plain ? ' nf--plain' : ''}" style="--nf-h:${esc(h)}">`
62
+ + (o.header ? `<div class="nf__head"><b class="nf__h">${esc(W.title)}</b>${o.markAll ? `<button type="button" class="nf__all">${icon('check')}<span>${esc(W.markAll)}</span></button>` : ''}</div>` : '')
63
+ + (o.tabs ? `<div class="tabs nf__tabs" role="tablist" data-tabs="nf"><span class="tabs__line"></span>`
64
+ + `<button type="button" role="tab" data-v="all" aria-selected="${filter === 'all'}">${esc(W.all)}</button>`
65
+ + `<button type="button" role="tab" data-v="unread" aria-selected="${filter === 'unread'}">${esc(W.unread)}<span class="badge badge--accent nf__count" hidden></span></button></div>` : '')
66
+ + `<div class="nf__scroll"><button type="button" class="nf__pill" hidden>${icon('arrowR')}<span></span></button>`
67
+ + `<div class="nf__groups"></div><div class="nf__empty" hidden></div></div><span class="nf__sr" role="status"></span></div>`;
68
+ const root = el.firstElementChild, scroll = root.querySelector('.nf__scroll'), wrap = root.querySelector('.nf__groups');
69
+ const pill = root.querySelector('.nf__pill'), emptyEl = root.querySelector('.nf__empty'), countEl = root.querySelector('.nf__count');
70
+ const allBtn = root.querySelector('.nf__all'), tabsEl = root.querySelector('.nf__tabs');
71
+ const say = (t) => { const s = root.querySelector('.nf__sr'); s.textContent = ''; requestAnimationFrame(() => { s.textContent = t; }); };
72
+
73
+ /* ---------- time ---------- */
74
+ const toMs = (t) => (t == null ? Date.now() : t instanceof Date ? t.getTime() : typeof t === 'number' ? t : (Date.parse(t) || Date.now()));
75
+ const dayStart = (k) => { const d = new Date(); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() + k); return d.getTime(); };
76
+ const groupOf = (it) => (!o.group ? 'all' : it.ms >= dayStart(0) ? 'today' : it.ms >= dayStart(-1) ? 'yesterday' : 'earlier');
77
+ const when = (ms) => {
78
+ if (o.when) return String(o.when(new Date(ms)));
79
+ const s = Math.max(0, (Date.now() - ms) / 1000), L = o.locale;
80
+ const rtf = new Intl.RelativeTimeFormat(L, { numeric: 'auto', style: 'short' });
81
+ const clock = (x) => new Intl.DateTimeFormat(L, { hour: 'numeric', minute: '2-digit' }).format(x);
82
+ if (s < 45) return W.now;
83
+ if (s < 3600) return rtf.format(-Math.max(1, Math.round(s / 60)), 'minute');
84
+ if (ms >= dayStart(0)) return rtf.format(-Math.round(s / 3600), 'hour');
85
+ if (ms >= dayStart(-1)) return o.group ? clock(ms) : `${rtf.format(-1, 'day')}, ${clock(ms)}`;
86
+ return new Intl.DateTimeFormat(L, ms >= dayStart(-6) ? { weekday: 'short', hour: 'numeric', minute: '2-digit' } : { day: 'numeric', month: 'short' }).format(ms);
87
+ };
88
+
89
+ /* ---------- items ---------- */
90
+ const norm = (it) => { const ms = toMs(it.time); return { ...it, id: it.id != null ? String(it.id) : `n${++seq}`, ms, time: it.time ?? new Date(ms), read: !!it.read }; };
91
+ const pub = (it) => { const { ms, ...rest } = it; return rest; };
92
+ const byId = (id) => list.find((x) => x.id === String(id));
93
+ const unread = () => list.filter((x) => !x.read).length;
94
+ const shows = (it) => filter === 'all' || !it.read || keep.has(it.id);
95
+ const tone = (t) => (TONES.includes(t) ? t : 'accent');
96
+ const plainTitle = (it) => { if (it.html != null) { const d = document.createElement('div'); d.innerHTML = it.html; return d.textContent.trim(); } return `${it.person ? `${it.person.name} ` : ''}${it.title ?? ''}`.trim(); };
97
+
98
+ const lead = (it) => it.person
99
+ ? `<span class="nf__lead">${av(it.person)}${it.icon ? `<span class="nf__badge nf__tone--${tone(it.tone)}">${icon(it.icon)}</span>` : ''}</span>`
100
+ : `<span class="nf__lead"><span class="nf__ic nf__tone--${tone(it.tone)}">${icon(it.icon || 'bell')}</span></span>`;
101
+ const doneHtml = (t) => `<div class="nf__done">${icon('check')}<span>${esc(t)}</span></div>`;
102
+ const acts = (it) => (it.done ? doneHtml(it.done) : it.actions?.length
103
+ ? `<div class="nf__acts">${it.actions.map((a) => `<button type="button" class="btn btn--sm${a.variant ? ` btn--${esc(a.variant)}` : ''} nf__act" data-act="${esc(a.id)}">${esc(a.label)}</button>`).join('')}</div>` : '');
104
+ const rowHtml = (it) => {
105
+ const [a, b] = it.href ? [`<a class="nf__main" href="${esc(it.href)}">`, '</a>'] : ['<button type="button" class="nf__main">', '</button>'];
106
+ const title = it.html != null ? it.html : `${it.person ? `<b>${esc(it.person.name)}</b> ` : ''}${esc(it.title ?? '')}`;
107
+ return `<div class="nf__in">${lead(it)}<div class="nf__text">${a}<span class="nf__unr">${esc(W.unreadMark)}: </span><span class="nf__title">${title}</span>${b}`
108
+ + `${it.body ? `<p class="nf__body">${esc(it.body)}</p>` : ''}`
109
+ + `<span class="nf__meta"><time class="nf__time"></time>${it.meta ? `<span>${esc(it.meta)}</span>` : ''}</span>${acts(it)}</div>`
110
+ + `<i class="nf__dot" aria-hidden="true"></i>`
111
+ + `${o.dismissible && it.dismissible !== false ? `<button type="button" class="nf__x" aria-label="${esc(W.dismiss)}">${icon('close')}</button>` : ''}</div>`;
112
+ };
113
+ const stamp = (it, li) => {
114
+ const t = li.querySelector('.nf__time'), d = new Date(it.ms);
115
+ t.textContent = when(it.ms); t.dateTime = d.toISOString();
116
+ t.title = new Intl.DateTimeFormat(o.locale, { dateStyle: 'medium', timeStyle: 'short' }).format(d);
117
+ };
118
+ /** Unread look: tint + dot. animate: the dot pops in or lets go. */
119
+ const paint = (it, li, animate = false, delay = 0) => {
120
+ li.classList.toggle('is-unread', !it.read);
121
+ li.querySelector('.nf__unr').hidden = it.read;
122
+ const dot = li.querySelector('.nf__dot');
123
+ g.killTweensOf(dot);
124
+ if (!animate || RM()) g.set(dot, { scale: it.read ? 0 : 1 });
125
+ else if (it.read) g.to(dot, { scale: 0, duration: 0.28, delay, ease: 'back.in(2.2)' });
126
+ else g.fromTo(dot, { scale: 0 }, { scale: 1, duration: 0.45, delay, ease: 'back.out(3)' });
127
+ };
128
+ const makeRow = (it) => {
129
+ const li = document.createElement('li');
130
+ li.className = 'nf__row'; li.dataset.id = it.id; li.innerHTML = rowHtml(it);
131
+ stamp(it, li); paint(it, li); els.set(it.id, li);
132
+ return li;
133
+ };
134
+
135
+ /* ---------- groups ---------- */
136
+ const groupEl = (key) => {
137
+ let s = groups.get(key);
138
+ if (s) return [s, false];
139
+ s = document.createElement('section'); s.className = 'nf__grp'; s.dataset.g = key;
140
+ s.innerHTML = `${key !== 'all' ? `<h4 class="nf__gh">${esc(W[key])}</h4>` : ''}<ul class="nf__list" role="list"></ul>`;
141
+ const next = ORDER.slice(ORDER.indexOf(key) + 1).map((k) => groups.get(k)).find(Boolean);
142
+ wrap.insertBefore(s, next || null); groups.set(key, s);
143
+ return [s, true];
144
+ };
145
+ /** Put a row in its group, in time order (list is already sorted newest first). */
146
+ const place = (it) => {
147
+ const key = groupOf(it), [s, made] = groupEl(key), ul = s.querySelector('.nf__list');
148
+ const li = els.get(it.id) || makeRow(it), i = list.indexOf(it), next = list[i + 1];
149
+ ul.insertBefore(li, next && groupOf(next) === key ? els.get(next.id) : null);
150
+ li.hidden = !shows(it);
151
+ if (made) s.hidden = li.hidden;
152
+ return { li, s, made };
153
+ };
154
+ const insert = (it) => { let i = list.findIndex((x) => x.ms < it.ms); if (i < 0) i = list.length; list.splice(i, 0, it); return place(it); };
155
+
156
+ /* ---------- show / hide with a height tween ---------- */
157
+ const collapse = (node, done) => {
158
+ node.__want = false;
159
+ if (RM() || node.hidden || !node.offsetHeight) { node.hidden = true; done?.(); return; }
160
+ g.killTweensOf(node);
161
+ g.to(node, { height: 0, opacity: 0, duration: 0.28, ease: 'power2.inOut', onComplete: () => { if (node.__want === false) node.hidden = true; g.set(node, { clearProps: 'height,opacity' }); done?.(); } });
162
+ };
163
+ const expand = (node, delay = 0) => {
164
+ node.__want = true;
165
+ const was = node.hidden; node.hidden = false;
166
+ if (RM()) { g.set(node, { clearProps: 'height,opacity' }); return; }
167
+ g.killTweensOf(node);
168
+ if (was) g.set(node, { height: 0, opacity: 0 });
169
+ g.to(node, { height: 'auto', opacity: 1, duration: 0.38, delay, ease: 'power3.out', clearProps: 'height,opacity' });
170
+ };
171
+ const showEmpty = (animate) => {
172
+ const none = !list.some(shows), was = !emptyEl.hidden;
173
+ if (none) {
174
+ const u = filter === 'unread' && list.length;
175
+ emptyEl.innerHTML = `<div class="empty"><span class="empty__icon">${icon(u ? 'check' : o.emptyIcon)}</span><b>${esc(u ? W.emptyUnread : W.empty)}</b><p>${esc(u ? W.emptyUnreadBody : W.emptyBody)}</p></div>`;
176
+ }
177
+ emptyEl.hidden = !none;
178
+ if (none && !was && animate && !RM()) g.fromTo(emptyEl.firstChild, { y: 8, opacity: 0, scale: 0.97 }, { y: 0, opacity: 1, scale: 1, duration: 0.45, delay: 0.2, ease: 'power3.out', clearProps: 'all' });
179
+ };
180
+ /** Bring rows and groups in line with the filter; empty groups go away. */
181
+ const refresh = (animate = true) => {
182
+ for (const [key, s] of groups) {
183
+ const rows = [...s.querySelectorAll('.nf__row')];
184
+ if (!rows.length) { groups.delete(key); collapse(s, () => s.remove()); continue; }
185
+ const want = rows.map((li) => shows(byId(li.dataset.id))), any = want.includes(true);
186
+ if (!any) { if (!s.hidden) collapse(s, () => rows.forEach((li) => { li.hidden = true; })); else rows.forEach((li) => { li.hidden = true; }); continue; }
187
+ if (s.hidden || s.__want === false) { rows.forEach((li, k) => { li.hidden = !want[k]; li.__want = want[k]; }); animate ? expand(s) : (s.hidden = false, s.__want = true); continue; }
188
+ rows.forEach((li, k) => { if (want[k] && (li.hidden || li.__want === false)) animate ? expand(li) : (li.hidden = false, li.__want = true); else if (!want[k] && !li.hidden) animate ? collapse(li) : (li.hidden = true); });
189
+ }
190
+ showEmpty(animate);
191
+ };
192
+
193
+ /* ---------- counts ---------- */
194
+ let lastCount = null;
195
+ const sync = (tell = true) => {
196
+ const n = unread();
197
+ if (countEl) {
198
+ countEl.hidden = !n;
199
+ if (n && lastCount !== null && n !== lastCount && !RM()) g.fromTo(countEl, { scale: 1.4 }, { scale: 1, duration: 0.45, ease: 'back.out(3)', clearProps: 'transform' });
200
+ countEl.textContent = n;
201
+ }
202
+ if (allBtn) allBtn.disabled = !n;
203
+ const changed = n !== lastCount; lastCount = n;
204
+ if (tell && changed) o.onChange?.(n, api);
205
+ };
206
+
207
+ /* ---------- build ---------- */
208
+ const build = (animate) => {
209
+ g.killTweensOf(wrap.querySelectorAll('*'));
210
+ wrap.replaceChildren(); els.clear(); groups.clear(); keep.clear(); pending = []; pill.hidden = true;
211
+ list.sort((a, b) => b.ms - a.ms).forEach(place);
212
+ for (const s of groups.values()) s.hidden = ![...s.querySelectorAll('.nf__row')].some((li) => !li.hidden);
213
+ showEmpty(false); sync(false);
214
+ if (animate && !RM()) {
215
+ const rows = $$('.nf__row', wrap).filter((li) => !li.hidden).slice(0, 10).map((li) => li.firstChild);
216
+ g.from(rows, { y: 10, opacity: 0, duration: 0.45, stagger: 0.04, ease: 'power3.out', clearProps: 'transform,opacity' });
217
+ }
218
+ };
219
+ list = (o.items || []).map(norm);
220
+ build(true);
221
+
222
+ /* ---------- actions ---------- */
223
+ const setRead = (id, read = true, delay = 0) => {
224
+ const it = byId(id); if (!it || it.read === read) return false;
225
+ it.read = read;
226
+ if (read && filter === 'unread') keep.add(it.id);
227
+ paint(it, els.get(it.id), true, delay);
228
+ return true;
229
+ };
230
+ const visibleRow = (li) => li && !li.hidden && !li.closest('.nf__grp').hidden;
231
+ const readAll = () => {
232
+ const ids = list.filter((x) => !x.read).map((x) => x.id);
233
+ if (!ids.length) return;
234
+ let k = 0;
235
+ ids.forEach((id) => setRead(id, true, visibleRow(els.get(id)) ? Math.min(k++, 14) * 0.04 : 0));
236
+ say(W.allRead); sync();
237
+ if (filter === 'unread') {
238
+ const go = () => { keep.clear(); refresh(true); };
239
+ if (RM()) go(); else calls.push(g.delayedCall(0.3 + Math.min(k, 14) * 0.04, go));
240
+ }
241
+ };
242
+
243
+ const showPill = () => {
244
+ pill.querySelector('span').textContent = W.newer(pending.length);
245
+ if (!pill.hidden) { M.pop(pill); return; }
246
+ pill.hidden = false;
247
+ if (!RM()) g.fromTo(pill, { y: -14, opacity: 0 }, { y: 0, opacity: 1, duration: 0.4, ease: 'back.out(2)', clearProps: 'transform,opacity' });
248
+ };
249
+ const clearPending = () => {
250
+ if (!pending.length) return;
251
+ pending.forEach((id) => els.get(id)?.classList.add('is-fresh'));
252
+ pending = []; pill.hidden = true;
253
+ };
254
+
255
+ const add = (input) => {
256
+ const arr = (Array.isArray(input) ? input : [input]).filter(Boolean).map(norm).filter((it) => !els.has(it.id));
257
+ if (!arr.length) return [];
258
+ const atTop = scroll.scrollTop <= 4, h0 = scroll.scrollHeight;
259
+ const placed = arr.sort((a, b) => a.ms - b.ms).map(insert);
260
+ const shown = placed.filter((p) => !p.li.hidden);
261
+ if (atTop || scroll.scrollHeight <= scroll.clientHeight + 4) {
262
+ shown.forEach(({ li, s, made }) => {
263
+ li.classList.add('is-fresh');
264
+ if (made || s.hidden) { s.hidden = false; expand(s); } else expand(li);
265
+ });
266
+ } else {
267
+ shown.forEach(({ s }) => { s.hidden = false; s.__want = true; });
268
+ scroll.scrollTop += scroll.scrollHeight - h0; // keep what the reader is looking at in place
269
+ pending.push(...shown.map((p) => p.li.dataset.id)); if (shown.length) showPill();
270
+ }
271
+ showEmpty(true);
272
+ const newest = arr[arr.length - 1];
273
+ say(arr.length > 1 ? W.newer(arr.length) : W.fresh(plainTitle(newest)));
274
+ sync();
275
+ return arr.map(pub);
276
+ };
277
+
278
+ const remove = (id, user = false) => {
279
+ const it = byId(id); if (!it) return false;
280
+ const li = els.get(it.id);
281
+ list = list.filter((x) => x !== it); els.delete(it.id); keep.delete(it.id); pending = pending.filter((x) => x !== it.id);
282
+ if (!pending.length) pill.hidden = true;
283
+ const gone = () => { li.remove(); refresh(true); };
284
+ if (!visibleRow(li) || RM()) gone();
285
+ else {
286
+ li.__want = false; g.killTweensOf([li, li.firstChild]);
287
+ g.timeline({ onComplete: gone })
288
+ .to(li.firstChild, { x: 48, opacity: 0, duration: 0.22, ease: 'power2.in' })
289
+ .to(li, { height: 0, duration: 0.26, ease: 'power2.inOut' });
290
+ }
291
+ if (user) { say(W.dismissed); o.onDismiss?.(pub(it), api); }
292
+ sync();
293
+ return true;
294
+ };
295
+
296
+ const runAction = async (it, btn) => {
297
+ const a = (it.actions || []).find((x) => String(x.id) === btn.dataset.act), box = btn.closest('.nf__acts');
298
+ if (!a || box.classList.contains('is-busy')) return;
299
+ const btns = [...box.querySelectorAll('button')];
300
+ const idle = () => { box.classList.remove('is-busy'); btns.forEach((b) => { b.disabled = false; }); btn.classList.remove('is-busy'); btn.removeAttribute('aria-busy'); };
301
+ box.classList.add('is-busy'); btns.forEach((b) => { b.disabled = true; }); btn.classList.add('is-busy'); btn.setAttribute('aria-busy', 'true');
302
+ let res;
303
+ try { res = await o.onAction?.(pub(it), a.id, api); } catch {
304
+ if (dead || !els.has(it.id)) return;
305
+ idle(); M.shake(btn); btn.focus(); say(W.failed); return;
306
+ }
307
+ if (dead || !els.has(it.id)) return;
308
+ if (res === false) { idle(); return; }
309
+ setRead(it.id, true); sync();
310
+ const label = typeof res === 'string' ? res : a.done;
311
+ if (!label) { idle(); return; }
312
+ it.done = label;
313
+ const h0 = box.offsetHeight, back = box.contains(document.activeElement);
314
+ box.insertAdjacentHTML('afterend', doneHtml(label));
315
+ const done = box.nextElementSibling; box.remove(); say(label);
316
+ if (back) els.get(it.id)?.querySelector('.nf__main')?.focus({ preventScroll: true });
317
+ if (RM()) return;
318
+ g.fromTo(done, { height: h0, opacity: 0, y: 4 }, { height: 'auto', opacity: 1, y: 0, duration: 0.38, ease: 'power3.out', clearProps: 'all' });
319
+ g.fromTo(done.querySelector('svg'), { scale: 0, rotation: -40 }, { scale: 1, rotation: 0, duration: 0.5, delay: 0.08, ease: 'back.out(3)', clearProps: 'transform' });
320
+ };
321
+
322
+ /* ---------- events ---------- */
323
+ on(wrap, 'click', (e) => {
324
+ const li = e.target.closest('.nf__row'); if (!li) return;
325
+ const it = byId(li.dataset.id); if (!it) return;
326
+ const act = e.target.closest('.nf__act');
327
+ if (act) { runAction(it, act); return; }
328
+ if (e.target.closest('.nf__x')) {
329
+ const mains = $$('.nf__main', wrap).filter((m) => visibleRow(m.closest('.nf__row')));
330
+ const i = mains.indexOf(li.querySelector('.nf__main')), next = mains[i + 1] || mains[i - 1];
331
+ if (li.contains(document.activeElement)) next?.focus({ preventScroll: true });
332
+ remove(it.id, true); return;
333
+ }
334
+ if (e.target.closest('.nf__main')) { if (setRead(it.id, true)) sync(); o.onOpen?.(pub(it), api); }
335
+ });
336
+ on(wrap, 'keydown', (e) => {
337
+ const m = e.target.closest?.('.nf__main'); if (!m) return;
338
+ const mains = $$('.nf__main', wrap).filter((x) => visibleRow(x.closest('.nf__row'))), i = mains.indexOf(m);
339
+ const go = (k) => { e.preventDefault(); mains[Math.max(0, Math.min(mains.length - 1, k))]?.focus(); };
340
+ if (e.key === 'ArrowDown') go(i + 1);
341
+ else if (e.key === 'ArrowUp') go(i - 1);
342
+ else if (e.key === 'Home') go(0);
343
+ else if (e.key === 'End') go(mains.length - 1);
344
+ else if ((e.key === 'Delete' || e.key === 'Backspace') && m.closest('.nf__row').querySelector('.nf__x')) {
345
+ e.preventDefault(); (mains[i + 1] || mains[i - 1])?.focus({ preventScroll: true }); remove(m.closest('.nf__row').dataset.id, true);
346
+ }
347
+ });
348
+ on(wrap, 'animationend', (e) => { e.target.closest('.nf__row')?.classList.remove('is-fresh'); });
349
+ on(pill, 'click', () => { scroll.scrollTo({ top: 0, behavior: RM() ? 'auto' : 'smooth' }); if (RM()) clearPending(); });
350
+ on(scroll, 'scroll', () => { if (scroll.scrollTop <= 4) clearPending(); }, { passive: true });
351
+ allBtn && on(allBtn, 'click', () => { M.pop(allBtn); readAll(); });
352
+
353
+ const setFilter = (f, fromTab = false) => {
354
+ f = f === 'unread' ? 'unread' : 'all';
355
+ if (tabsEl && !fromTab) { const b = tabsEl.querySelector(`[data-v="${f}"]`); if (b.getAttribute('aria-selected') !== 'true') { b.click(); return; } }
356
+ if (f === filter) return;
357
+ filter = f; keep.clear(); clearPending(); scroll.scrollTop = 0; refresh(true);
358
+ };
359
+ if (tabsEl) bindTabs(tabsEl, (name, v) => setFilter(v, true));
360
+
361
+ /* times tick on; a new day regroups everything */
362
+ let day = dayStart(0);
363
+ const timer = setInterval(() => {
364
+ if (dayStart(0) !== day) { day = dayStart(0); build(false); return; }
365
+ list.forEach((it) => { const li = els.get(it.id); if (li) stamp(it, li); });
366
+ }, 30000);
367
+
368
+ const api = {
369
+ root,
370
+ get items() { return list.map(pub); },
371
+ get unread() { return unread(); },
372
+ get filter() { return filter; },
373
+ add,
374
+ update(id, patch = {}) {
375
+ const it = byId(id); if (!it) return false;
376
+ const timeChanged = 'time' in patch;
377
+ Object.assign(it, patch, { id: it.id });
378
+ if (timeChanged) { it.ms = toMs(it.time); list.splice(list.indexOf(it), 1); const li = els.get(it.id); els.delete(it.id); li.remove(); insert(it); refresh(false); }
379
+ else { const li = els.get(it.id); li.innerHTML = rowHtml(it); stamp(it, li); paint(it, li); if (filter === 'unread' && it.read) keep.add(it.id); refresh(true); }
380
+ sync(); return true;
381
+ },
382
+ read(ids, read = true) { let n = 0; (Array.isArray(ids) ? ids : [ids]).forEach((id) => { n += setRead(id, read); }); if (n) sync(); return n; },
383
+ readAll,
384
+ remove: (id) => remove(id),
385
+ setFilter: (f) => setFilter(f),
386
+ setItems(items = []) { list = items.map(norm); build(true); },
387
+ destroy() {
388
+ dead = true; ac.abort(); clearInterval(timer); calls.forEach((c) => c.kill());
389
+ g.killTweensOf(root.querySelectorAll('*')); el.innerHTML = '';
390
+ },
391
+ };
392
+ return api;
393
+ };
package/src/otp.js ADDED
@@ -0,0 +1,112 @@
1
+ /* Code field (one-time code / PIN): one box per character.
2
+ Typing moves to the next box, Backspace goes back, paste or the phone's code autofill
3
+ fills every box at once. Each character pops in. When the code is checked, otpState()
4
+ plays the answer: 'good' turns the boxes green in a wave, then gathers them into a tick;
5
+ 'bad' shakes them red and clears them for another try. */
6
+ import * as M from '@gecko-ui-kit/motion';
7
+ import { esc } from '../index.js';
8
+
9
+ const { g, D, RM, $$ } = M;
10
+ const TICK = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5.5 12.5l4 4L18.5 7.5"/></svg>';
11
+
12
+ /** otp({ length: 6, split: false, mask: false, letters: false, label: 'Verification code', name }) → HTML */
13
+ export const otp = ({ length = 6, split = false, mask = false, letters = false, label = 'Verification code', name = '' } = {}) => {
14
+ const half = split ? Math.ceil(length / 2) : -1;
15
+ const box = (i) => `<input class="otp__box" type="${mask ? 'password' : 'text'}" inputmode="${letters ? 'text' : 'numeric'}"${letters ? '' : ' pattern="[0-9]*"'} autocomplete="${i === 0 ? 'one-time-code' : 'off'}" autocapitalize="characters" spellcheck="false" aria-label="${esc(label)}, ${i + 1} of ${length}">`;
16
+ return `<div class="otp${letters ? ' otp--letters' : ''}" role="group" aria-label="${esc(label)}" data-otp="${esc(name || 'code')}" data-len="${length}"${letters ? ' data-letters' : ''}>${Array.from({ length }, (_, i) => (i === half ? '<span class="otp__dash" aria-hidden="true"></span>' : '') + box(i)).join('')}<span class="otp__done" aria-hidden="true">${TICK}</span></div>`;
17
+ };
18
+
19
+ const boxes = (el) => $$('.otp__box', el);
20
+ const clean = (el, s) => (el.hasAttribute('data-letters') ? String(s).toUpperCase().replace(/[^A-Z0-9]/g, '') : String(s).replace(/\D/g, ''));
21
+ /** The code typed so far ('' for empty boxes at the end). */
22
+ export const otpValue = (el) => boxes(el).map((b) => b.value).join('');
23
+
24
+ const popIn = (b) => {
25
+ b.classList.toggle('is-filled', !!b.value);
26
+ if (b.value && !RM()) g.fromTo(b, { scale: 0.86, y: 3 }, { scale: 1, y: 0, duration: 0.45, ease: 'back.out(3)', overwrite: 'auto', clearProps: 'transform' });
27
+ };
28
+
29
+ /** Wire every .otp inside root. onComplete(code, el) runs when the last box is filled. */
30
+ export const bindOtp = (root, onComplete) => $$(root.matches?.('.otp') ? [root] : $$('.otp[data-otp]', root)).forEach((el) => {
31
+ el.__otpDone ||= [];
32
+ if (onComplete && !el.__otpDone.includes(onComplete)) el.__otpDone.push(onComplete);
33
+ if (el.__otp) return; el.__otp = true;
34
+ const list = boxes(el);
35
+ const check = () => {
36
+ const code = otpValue(el);
37
+ if (code.length === list.length && !el.classList.contains('is-good')) { list[list.length - 1].blur(); el.__otpDone.forEach((fn) => fn(code, el)); }
38
+ };
39
+ /** Write text into the boxes from index i on; focus the next empty one. */
40
+ const fill = (i, text) => {
41
+ const chars = [...clean(el, text)].slice(0, list.length - i);
42
+ chars.forEach((ch, k) => { list[i + k].value = ch; popIn(list[i + k]); });
43
+ const next = list.find((b) => !b.value) || list[Math.min(i + chars.length, list.length - 1)];
44
+ next.focus(); check();
45
+ };
46
+ list.forEach((b, i) => {
47
+ b.addEventListener('focus', () => { el.classList.remove('is-bad'); requestAnimationFrame(() => b.select()); });
48
+ b.addEventListener('input', (e) => {
49
+ const v = b.value;
50
+ if (e.inputType === 'insertText' && e.data?.length === 1) {
51
+ const ch = clean(el, e.data);
52
+ b.value = ch; popIn(b);
53
+ if (ch) { (list[i + 1] || b).focus(); check(); } else M.shake(b);
54
+ } else if (v.length > 1) { b.value = ''; fill(i, v); } // paste / phone autofill / IME
55
+ else { b.value = clean(el, v); popIn(b); if (b.value) check(); }
56
+ });
57
+ b.addEventListener('paste', (e) => { e.preventDefault(); fill(i, e.clipboardData?.getData('text') || ''); });
58
+ b.addEventListener('keydown', (e) => {
59
+ if (e.key === 'Backspace' && !b.value && i > 0) { e.preventDefault(); const p = list[i - 1]; p.value = ''; popIn(p); p.focus(); }
60
+ else if (e.key === 'ArrowLeft' && i > 0) { e.preventDefault(); list[i - 1].focus(); }
61
+ else if (e.key === 'ArrowRight' && i < list.length - 1) { e.preventDefault(); list[i + 1].focus(); }
62
+ else if (e.key === 'Home') { e.preventDefault(); list[0].focus(); }
63
+ else if (e.key === 'End') { e.preventDefault(); list[list.length - 1].focus(); }
64
+ });
65
+ });
66
+ });
67
+
68
+ /** Empty every box and put the cursor in the first one. */
69
+ export const otpClear = (el, { focus = true } = {}) => {
70
+ if (!el) return;
71
+ g.killTweensOf([el, ...boxes(el), el.querySelector('.otp__done'), el.querySelector('.otp__done path')]);
72
+ el.classList.remove('is-good', 'is-bad', 'is-done');
73
+ boxes(el).forEach((b) => { b.value = ''; b.disabled = false; b.classList.remove('is-filled'); g.set(b, { clearProps: 'all' }); });
74
+ g.set(el.querySelector('.otp__done'), { clearProps: 'all' });
75
+ if (focus) boxes(el)[0]?.focus();
76
+ };
77
+
78
+ /**
79
+ * otpState(el, 'good' | 'bad' | '') — play the answer and return the timeline.
80
+ * good: a green wave, then the boxes gather into one tick (gather: false keeps the green boxes).
81
+ * bad: red + shake, then the boxes empty for another try (clear: false keeps what was typed).
82
+ */
83
+ export const otpState = (el, state, { gather = true, clear = true } = {}) => {
84
+ if (!el) return g.timeline();
85
+ const list = boxes(el), done = el.querySelector('.otp__done'), path = done?.querySelector('path');
86
+ const tl = g.timeline();
87
+ if (!state) { otpClear(el, { focus: false }); return tl; }
88
+ if (state === 'bad') {
89
+ el.classList.remove('is-good'); el.classList.add('is-bad');
90
+ if (!RM()) tl.fromTo(el, { x: 0 }, { keyframes: { x: [0, -10, 9, -6, 4, 0] }, duration: 0.45, ease: 'power2.out', clearProps: 'transform' });
91
+ if (clear) {
92
+ tl.to(list, { opacity: 0, y: 6, duration: D(0.2), stagger: D(0.03), ease: 'power2.in' }, RM() ? 0 : '+=0.35')
93
+ .add(() => { list.forEach((b) => { b.value = ''; b.classList.remove('is-filled'); }); el.classList.remove('is-bad'); })
94
+ .to(list, { opacity: 1, y: 0, duration: D(0.3), stagger: D(0.03), ease: 'power3.out', clearProps: 'opacity,transform' })
95
+ .add(() => list[0].focus());
96
+ }
97
+ return tl;
98
+ }
99
+ // good
100
+ list.forEach((b) => { b.disabled = true; });
101
+ el.classList.remove('is-bad');
102
+ if (RM()) { el.classList.add('is-good'); if (gather) { el.classList.add('is-done'); g.set(list, { opacity: 0 }); g.set(done, { opacity: 1, scale: 1 }); g.set(path, { strokeDashoffset: 0 }); } return tl; }
103
+ tl.add(() => el.classList.add('is-good'));
104
+ tl.fromTo(list, { y: 0 }, { keyframes: { y: [0, -7, 0] }, duration: 0.42, ease: 'power2.inOut', stagger: 0.045 });
105
+ if (!gather) return tl;
106
+ const box = el.getBoundingClientRect(), mid = box.left + box.width / 2;
107
+ tl.to(list, { x: (k) => { const r = list[k].getBoundingClientRect(); return mid - (r.left + r.width / 2); }, scale: 0.55, opacity: 0, duration: 0.45, ease: 'power3.in', stagger: { each: 0.02, from: 'edges' } }, '+=0.1')
108
+ .add(() => el.classList.add('is-done'), '-=0.12')
109
+ .fromTo(done, { opacity: 0, scale: 0.4 }, { opacity: 1, scale: 1, duration: 0.6, ease: 'back.out(2.2)' }, '-=0.14')
110
+ .fromTo(path, { strokeDashoffset: 22 }, { strokeDashoffset: 0, duration: 0.4, ease: 'power2.out' }, '-=0.38');
111
+ return tl;
112
+ };