@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,378 @@
1
+ /* File drop zone: drop files on it, click it (it is a real button), or paste. While files are
2
+ dragged anywhere over the page the zone lights up; right over it, it lifts and glows. Each file
3
+ becomes a row that slides in (one after another), with an icon for its type (a small preview for
4
+ images), its size and a progress bar that fills smoothly while it uploads. A finished upload pops
5
+ a tick; a failed one shows why with Retry. Files that are too big, of the wrong type or one too
6
+ many get a row that says why, the zone shakes and a screen reader hears it. Removed rows fold
7
+ away. You bring the upload function; without one the files are only listed, ready for a form. */
8
+ import * as M from '@gecko-ui-kit/motion';
9
+ import { icon } from '@gecko-ui-kit/icons';
10
+ import { esc } from '../index.js';
11
+
12
+ const { g, RM, $$ } = M;
13
+ const UP = 'upload';
14
+ const KB = 1024, MB = KB * KB, GB = MB * KB;
15
+
16
+ /** 2400000 → "2.3 MB" */
17
+ const fmtSize = (b) => {
18
+ b = Math.max(0, +b || 0);
19
+ const one = (v, u) => `${v >= 10 ? Math.round(v) : Math.round(v * 10) / 10} ${u}`;
20
+ return b < KB ? `${b} B` : b < MB ? one(b / KB, 'KB') : b < GB ? one(b / MB, 'MB') : one(b / GB, 'GB');
21
+ };
22
+ const WORDS = {
23
+ label: 'Files',
24
+ title: 'Drop files here',
25
+ browse: 'or click to browse',
26
+ compact: 'Drop files or click to browse',
27
+ drop: 'Release to add',
28
+ kinds: { image: 'images', video: 'videos', audio: 'audio' },
29
+ /** x: { types: 'PDF, images', size: '2 MB', maxSize, maxFiles, multiple, accept } */
30
+ hint: (x) => [x.types, x.size && `up to ${x.size} each`, x.multiple && x.maxFiles && `${x.maxFiles} files max`].filter(Boolean).join(' · '),
31
+ queued: 'Waiting',
32
+ uploading: (pct) => `${pct}%`,
33
+ done: 'Uploaded',
34
+ ready: '',
35
+ failed: 'Upload failed',
36
+ cancelled: 'Cancelled',
37
+ retry: 'Retry',
38
+ cancel: 'Cancel upload',
39
+ remove: 'Remove',
40
+ tooBig: (max) => `Too big — the limit is ${max}`,
41
+ wrongType: 'This type of file isn’t allowed',
42
+ tooMany: (n) => `Only ${n} ${n === 1 ? 'file' : 'files'} allowed`,
43
+ added: (n) => `${n} ${n === 1 ? 'file' : 'files'} added`,
44
+ removed: (name) => `${name} removed`,
45
+ uploaded: (name) => `${name} uploaded`,
46
+ problem: (name, why) => `${name}: ${why}`,
47
+ size: fmtSize,
48
+ };
49
+ const ICONS = { image: 'image', pdf: 'file', sheet: 'table', archive: 'box', media: 'play', doc: 'file' };
50
+ let seq = 0;
51
+
52
+ /** Does a file match an accept string like '.pdf,image/*'? */
53
+ const accepts = (file, accept) => {
54
+ if (!accept) return true;
55
+ const name = (file.name || '').toLowerCase(), type = (file.type || '').toLowerCase();
56
+ return accept.split(',').map((a) => a.trim().toLowerCase()).filter(Boolean).some((a) =>
57
+ a.startsWith('.') ? name.endsWith(a) : a.endsWith('/*') ? type.startsWith(a.slice(0, -1)) : type === a);
58
+ };
59
+ /** '.pdf,image/*' → 'PDF, images' (for the hint). */
60
+ const typesText = (accept, kinds) => {
61
+ const out = [...new Set(String(accept || '').split(',').map((a) => a.trim().toLowerCase()).filter(Boolean).map((a) => {
62
+ if (a.startsWith('.')) return a.slice(1).toUpperCase();
63
+ const [major, minor] = a.split('/');
64
+ if (minor === '*') return kinds[major] || major;
65
+ return (minor || major).replace(/^x-/, '').split(/[.+-]/)[0].toUpperCase();
66
+ }))].join(', ');
67
+ return out.charAt(0).toUpperCase() + out.slice(1);
68
+ };
69
+ const kindOf = (f) => {
70
+ const t = (f.type || '').toLowerCase(), ext = ((f.name || '').split('.').pop() || '').toLowerCase();
71
+ if (t.startsWith('image/')) return 'image';
72
+ if (t === 'application/pdf' || ext === 'pdf') return 'pdf';
73
+ if (/sheet|excel|csv/.test(t) || /^(xlsx?|csv|ods|numbers)$/.test(ext)) return 'sheet';
74
+ if (/zip|compressed|tar|rar|7z/.test(t) || /^(zip|rar|7z|tar|gz)$/.test(ext)) return 'archive';
75
+ if (t.startsWith('video/') || t.startsWith('audio/')) return 'media';
76
+ return 'doc';
77
+ };
78
+
79
+ /**
80
+ * const fd = fileDrop(el, {
81
+ * accept: '.pdf,image/*', // like <input accept> ('' = anything)
82
+ * multiple: true, // false: one file; a new one replaces it
83
+ * maxSize: 10 * 1024 * 1024, // bytes per file (0 = no limit)
84
+ * maxFiles: 0, // most files (0 = no limit)
85
+ * upload: async (file, { progress, signal, id }) => result, // call progress(0…1); without it files are only listed
86
+ * auto: true, // start uploading as files are added (false: call fd.upload())
87
+ * concurrent: 3, // uploads at the same time
88
+ * compact: false, // a slim one-line zone
89
+ * words: { title, browse, compact, drop, hint, kinds, queued, uploading, done, ready, failed, cancelled,
90
+ * retry, cancel, remove, tooBig, wrongType, tooMany, added, removed, uploaded, problem, size },
91
+ * onChange(files, fd), onError({ id, file, name, reason, message, error }, fd)
92
+ * // reason: 'type' | 'size' | 'count' | 'upload'
93
+ * })
94
+ * fd.files → [{ id, file, name, size, type, status: 'queued'|'uploading'|'done'|'error', progress, error, reason, result }]
95
+ * fd.value (results of finished uploads, or the File objects when there is no upload) · fd.busy
96
+ * fd.add(files) · fd.remove(id) · fd.retry(id) · fd.cancel(id) · fd.clear() · fd.browse() · fd.upload() → Promise · fd.destroy()
97
+ */
98
+ export const fileDrop = (el, opts = {}) => {
99
+ el = $$(el)[0];
100
+ if (!el) return null;
101
+ const o = { accept: '', multiple: true, maxSize: 0, maxFiles: 0, upload: null, auto: true, concurrent: 3, compact: false, words: null, onChange: null, onError: null, ...opts };
102
+ const W = { ...WORDS, ...o.words, kinds: { ...WORDS.kinds, ...o.words?.kinds } };
103
+ const id = `fd${++seq}`;
104
+ const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
105
+ const hintText = typeof W.hint === 'function'
106
+ ? W.hint({ types: typesText(o.accept, W.kinds), size: o.maxSize ? W.size(o.maxSize) : '', maxSize: o.maxSize, maxFiles: o.multiple ? o.maxFiles : 1, multiple: o.multiple, accept: o.accept })
107
+ : W.hint;
108
+
109
+ el.innerHTML = `<div class="fd${o.compact ? ' fd--compact' : ''}${o.upload ? '' : ' fd--local'}">`
110
+ + `<input class="fd__input" type="file" tabindex="-1" aria-hidden="true"${o.accept ? ` accept="${esc(o.accept)}"` : ''}${o.multiple ? ' multiple' : ''}>`
111
+ + `<button type="button" class="fd__zone"><span class="fd__ico">${icon(UP)}</span>`
112
+ + `<span class="fd__words"><span class="fd__txt"><b class="fd__title">${esc(o.compact ? W.compact : W.title)}</b>${o.compact ? '' : `<span class="fd__browse">${esc(W.browse)}</span>`}`
113
+ + `${hintText ? `<small class="fd__hint">${esc(hintText)}</small>` : ''}</span>`
114
+ + `<span class="fd__drop" aria-hidden="true">${esc(W.drop)}</span></span></button>`
115
+ + `<ul class="fd__list" role="list" aria-label="${esc(W.label)}"></ul>`
116
+ + '<span class="fd__sr" role="status"></span></div>';
117
+ const root = el.firstElementChild, zone = root.querySelector('.fd__zone'), input = root.querySelector('.fd__input');
118
+ const list = root.querySelector('.fd__list'), ico = root.querySelector('.fd__ico'), sr = root.querySelector('.fd__sr');
119
+
120
+ /** @type {{ id, file, name, size, type, kind, status, progress, error, reason, result, url, el, ac, go, err }[]} */
121
+ let items = [];
122
+ let active = 0, waiters = [], depth = 0, pageT = 0, sayT = 0, made = 0;
123
+ const say = (t) => { clearTimeout(sayT); sr.textContent = ''; sayT = setTimeout(() => { sr.textContent = t; }, 30); };
124
+ const byId = (x) => items.find((i) => i.id === x);
125
+ const pub = (x) => ({ id: x.id, file: x.file, name: x.name, size: x.size, type: x.type, status: x.status, progress: x.progress, error: x.error, reason: x.reason, result: x.result });
126
+ const counted = () => items.filter((x) => !['type', 'size', 'count'].includes(x.reason)).length;
127
+ const changed = () => { root.classList.toggle('has-files', items.length > 0); o.onChange?.(items.map(pub), api); };
128
+
129
+ /* ---------- rows ---------- */
130
+ const rowHTML = (x) => {
131
+ const ext = (x.name.includes('.') ? x.name.split('.').pop() : '').slice(0, 4).toUpperCase();
132
+ const n = esc(x.name);
133
+ return `<li class="fd__row" data-id="${x.id}"><div class="fd__card">`
134
+ + `<span class="fd__thumb fd__thumb--${x.kind}">${x.url ? `<img alt="" src="${esc(x.url)}" decoding="async">` : `${icon(ICONS[x.kind])}${ext ? `<b class="fd__ext">${esc(ext)}</b>` : ''}`}</span>`
135
+ + `<span class="fd__meta"><span class="fd__name" title="${n}">${n}</span>`
136
+ + `<span class="fd__sub"><span class="fd__size">${esc(W.size(x.size))}</span><span class="fd__state"></span></span>`
137
+ + `<span class="fd__bar" role="progressbar" aria-label="${n}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><i></i></span></span>`
138
+ + `<span class="fd__acts"><span class="fd__ok" aria-hidden="true">${icon('check')}</span>`
139
+ + `<button type="button" class="fd__btn fd__retry" data-act="retry" aria-label="${esc(W.retry)}: ${n}" title="${esc(W.retry)}">${icon('refresh')}</button>`
140
+ + `<button type="button" class="fd__btn fd__cancel" data-act="cancel" aria-label="${esc(W.cancel)}: ${n}" title="${esc(W.cancel)}">${icon('close')}</button>`
141
+ + `<button type="button" class="fd__btn fd__remove" data-act="remove" aria-label="${esc(W.remove)}: ${n}" title="${esc(W.remove)}">${icon('trash')}</button>`
142
+ + '</span></div></li>';
143
+ };
144
+ const build = (x) => {
145
+ const t = document.createElement('template'); t.innerHTML = rowHTML(x);
146
+ const li = t.content.firstElementChild; x.el = li;
147
+ const img = li.querySelector('.fd__thumb img');
148
+ if (img) {
149
+ img.addEventListener('load', () => { if (!RM()) g.fromTo(img, { opacity: 0, scale: 1.15 }, { opacity: 1, scale: 1, duration: 0.4, ease: 'power2.out', clearProps: 'opacity,transform' }); }, { once: true, signal: ac.signal });
150
+ img.addEventListener('error', () => { img.parentElement.innerHTML = icon(ICONS[x.kind]); }, { once: true, signal: ac.signal }); // a type the browser can't show
151
+ }
152
+ paint(x, true);
153
+ return li;
154
+ };
155
+
156
+ /** Show an item's state on its row; the bar eases to the new progress. */
157
+ const paint = (x, quiet = false) => {
158
+ const li = x.el; if (!li) return;
159
+ ['queued', 'uploading', 'done', 'error'].forEach((s) => li.classList.toggle(`is-${s}`, x.status === s));
160
+ li.classList.toggle('is-rejected', ['type', 'size', 'count'].includes(x.reason));
161
+ const pct = Math.round(x.progress * 100);
162
+ li.querySelector('.fd__state').textContent = x.status === 'queued' ? W.queued : x.status === 'uploading' ? W.uploading(pct)
163
+ : x.status === 'error' ? x.error : o.upload ? W.done : W.ready;
164
+ const bar = li.querySelector('.fd__bar'), fill = bar.firstElementChild;
165
+ bar.setAttribute('aria-valuenow', String(pct));
166
+ const v = x.status === 'done' ? 1 : x.progress;
167
+ if (quiet || RM()) { g.killTweensOf(fill); g.set(fill, { scaleX: v }); return; }
168
+ g.to(fill, { scaleX: v, duration: 0.45, ease: 'power2.out', overwrite: true });
169
+ };
170
+
171
+ /** New rows open up and slide in, one after another. */
172
+ const enter = (lis) => {
173
+ if (RM() || !lis.length) return;
174
+ lis.forEach((li, i) => {
175
+ const h = li.offsetHeight, mt = parseFloat(getComputedStyle(li).marginTop) || 0;
176
+ g.fromTo(li, { height: 0, marginTop: 0, overflow: 'hidden' }, { height: h, marginTop: mt, duration: 0.34, delay: i * 0.06, ease: 'power3.out', clearProps: 'height,marginTop,overflow' });
177
+ g.fromTo(li.firstElementChild, { x: -18, opacity: 0 }, { x: 0, opacity: 1, duration: 0.42, delay: i * 0.06 + 0.04, ease: 'power3.out', clearProps: 'transform,opacity' });
178
+ });
179
+ };
180
+ /** A row folds away, then leaves the page. */
181
+ const leave = (li, delay = 0) => {
182
+ if (!li) return;
183
+ li.classList.add('is-gone');
184
+ if (RM()) { li.remove(); return; }
185
+ g.killTweensOf([li, li.firstElementChild]);
186
+ li.style.overflow = 'hidden';
187
+ g.to(li.firstElementChild, { x: 18, opacity: 0, duration: 0.22, delay, ease: 'power2.in' });
188
+ g.to(li, { height: 0, marginTop: 0, duration: 0.3, delay: delay + 0.1, ease: 'power2.inOut', onComplete: () => li.remove() });
189
+ };
190
+
191
+ /** Focus the first button that shows in a row. */
192
+ const focusIn = (li) => {
193
+ const b = li && [...li.querySelectorAll('.fd__btn')].find((x) => x.offsetParent);
194
+ b?.focus({ preventScroll: true });
195
+ return !!b;
196
+ };
197
+
198
+ /* ---------- uploads ---------- */
199
+ const settle = () => { if (!api.busy) { const w = waiters; waiters = []; w.forEach((f) => f(api.value)); } };
200
+ const pump = () => {
201
+ if (o.upload) {
202
+ while (active < Math.max(1, o.concurrent)) {
203
+ const x = items.find((i) => i.status === 'queued' && (o.auto || i.go));
204
+ if (!x) break;
205
+ send(x);
206
+ }
207
+ }
208
+ settle();
209
+ };
210
+ const send = async (x) => {
211
+ active++;
212
+ x.status = 'uploading'; x.progress = 0; x.error = null; x.reason = null; x.err = null; paint(x);
213
+ const c = new AbortController(); x.ac = c;
214
+ try {
215
+ const result = await o.upload(x.file, { signal: c.signal, id: x.id, progress: (p) => {
216
+ if (c.signal.aborted || x.status !== 'uploading') return;
217
+ x.progress = Math.max(0, Math.min(1, +p || 0)); paint(x);
218
+ } });
219
+ if (c.signal.aborted) return;
220
+ x.status = 'done'; x.progress = 1; x.result = result; paint(x);
221
+ if (!RM() && x.el) g.fromTo(x.el.querySelector('.fd__ok'), { scale: 0, rotation: -35 }, { scale: 1, rotation: 0, duration: 0.5, delay: 0.25, ease: 'back.out(2.6)', clearProps: 'transform' });
222
+ say(W.uploaded(x.name)); changed();
223
+ } catch (err) {
224
+ if (c.signal.aborted) return;
225
+ x.status = 'error'; x.reason = 'upload'; x.error = W.failed; x.err = err; paint(x);
226
+ if (x.el) M.shake(x.el.firstElementChild);
227
+ say(W.problem(x.name, W.failed));
228
+ o.onError?.({ id: x.id, file: x.file, name: x.name, reason: 'upload', message: W.failed, error: err }, api);
229
+ changed();
230
+ } finally {
231
+ active--; if (x.ac === c) x.ac = null; pump();
232
+ }
233
+ };
234
+
235
+ /* ---------- adding & removing ---------- */
236
+ const drop = (x) => { x.ac?.abort(); x.ac = null; if (x.url) { const u = x.url; x.url = null; setTimeout(() => URL.revokeObjectURL(u), 500); } };
237
+ const take = (x) => { // out of the list (no row animation)
238
+ const i = items.indexOf(x); if (i < 0) return;
239
+ items.splice(i, 1); drop(x);
240
+ };
241
+
242
+ const api = {
243
+ el: root, opts: o,
244
+ get files() { return items.map(pub); },
245
+ /** What to save: each finished upload's result (or the File when there is no upload function), in order. */
246
+ get value() { return items.filter((x) => x.status === 'done').map((x) => (o.upload ? x.result : x.file)); },
247
+ get busy() { return items.some((x) => x.status === 'uploading' || (x.status === 'queued' && (o.auto || x.go))); },
248
+ /** Add files (a FileList or an array of File). Returns the rows added (rejected ones included). */
249
+ add(files) {
250
+ let fs = [...(files || [])].filter((f) => f instanceof Blob);
251
+ if (!fs.length) return [];
252
+ let shake = false;
253
+ const problems = [];
254
+ if (!o.multiple) {
255
+ if (fs.length > 1) { problems.push(W.tooMany(1)); shake = true; }
256
+ fs = fs.slice(0, 1);
257
+ if (accepts(fs[0], o.accept) && !(o.maxSize && fs[0].size > o.maxSize)) [...items].forEach((x) => { take(x); leave(x.el); }); // the new one replaces the old
258
+ }
259
+ let room = o.maxFiles && o.multiple ? o.maxFiles - counted() : Infinity;
260
+ const fresh = fs.map((f) => {
261
+ const name = f.name || 'file';
262
+ let reason = null;
263
+ if (!accepts(f, o.accept)) reason = 'type';
264
+ else if (o.maxSize && f.size > o.maxSize) reason = 'size';
265
+ else if (room <= 0) reason = 'count';
266
+ else room--;
267
+ const kind = kindOf(f);
268
+ const error = reason === 'type' ? W.wrongType : reason === 'size' ? W.tooBig(W.size(o.maxSize)) : reason === 'count' ? W.tooMany(o.maxFiles) : null;
269
+ return { id: `${id}-${(++made).toString(36)}`, file: f, name, size: f.size, type: f.type, kind, status: reason ? 'error' : o.upload ? 'queued' : 'done', progress: reason || o.upload ? 0 : 1,
270
+ error, reason, result: null, url: !reason && kind === 'image' && typeof URL.createObjectURL === 'function' ? URL.createObjectURL(f) : null, el: null, ac: null, go: false };
271
+ });
272
+ fresh.forEach((x) => build(x));
273
+ items.push(...fresh);
274
+ list.append(...fresh.map((x) => x.el));
275
+ enter(fresh.map((x) => x.el));
276
+ const bad = fresh.filter((x) => x.reason);
277
+ bad.forEach((x) => problems.push(W.problem(x.name, x.error)));
278
+ if (bad.length) shake = true;
279
+ if (shake) M.shake(zone);
280
+ const good = fresh.length - bad.length;
281
+ say([good ? W.added(good) : '', ...problems].filter(Boolean).join('. '));
282
+ bad.forEach((x) => o.onError?.({ id: x.id, file: x.file, name: x.name, reason: x.reason, message: x.error, error: null }, api));
283
+ changed();
284
+ pump();
285
+ return fresh.map(pub);
286
+ },
287
+ remove(fid) {
288
+ const x = byId(fid); if (!x) return api;
289
+ const at = items.indexOf(x);
290
+ const hadFocus = x.el?.contains(document.activeElement);
291
+ take(x);
292
+ if (hadFocus && !focusIn(items[at]?.el || items[at - 1]?.el)) zone.focus({ preventScroll: true });
293
+ leave(x.el);
294
+ say(W.removed(x.name)); changed(); pump();
295
+ return api;
296
+ },
297
+ /** Try a failed or cancelled upload again. */
298
+ retry(fid) {
299
+ const x = byId(fid);
300
+ if (!x || !o.upload || x.status !== 'error' || !['upload', 'cancelled'].includes(x.reason)) return api;
301
+ x.status = 'queued'; x.progress = 0; x.error = null; x.reason = null; x.go = true; paint(x); changed(); pump();
302
+ return api;
303
+ },
304
+ /** Stop an upload; the row stays with Retry. */
305
+ cancel(fid) {
306
+ const x = byId(fid);
307
+ if (!x || (x.status !== 'uploading' && x.status !== 'queued')) return api;
308
+ x.ac?.abort(); x.ac = null;
309
+ x.status = 'error'; x.reason = 'cancelled'; x.error = W.cancelled; paint(x);
310
+ say(W.problem(x.name, W.cancelled)); changed(); pump();
311
+ return api;
312
+ },
313
+ clear() {
314
+ if (!items.length) return api;
315
+ const gone = [...items];
316
+ items = [];
317
+ gone.forEach((x, i) => { drop(x); leave(x.el, i * 0.03); });
318
+ changed(); settle();
319
+ return api;
320
+ },
321
+ /** Open the file picker. */
322
+ browse() { input.click(); return api; },
323
+ /** Start the uploads that are waiting (for auto: false). Resolves with value when nothing is left to send. */
324
+ upload() {
325
+ items.forEach((x) => { if (x.status === 'queued') x.go = true; });
326
+ pump();
327
+ return api.busy ? new Promise((r) => waiters.push(r)) : Promise.resolve(api.value);
328
+ },
329
+ destroy() {
330
+ ac.abort(); clearTimeout(pageT); clearTimeout(sayT);
331
+ items.forEach(drop);
332
+ g.killTweensOf([zone, ico, ...root.querySelectorAll('.fd__row, .fd__card, .fd__bar i, .fd__ok, .fd__thumb img')]);
333
+ items = []; waiters = [];
334
+ el.innerHTML = '';
335
+ },
336
+ };
337
+
338
+ /* ---------- events ---------- */
339
+ on(zone, 'click', () => api.browse());
340
+ on(input, 'change', () => { api.add(input.files); input.value = ''; });
341
+ on(list, 'click', (e) => {
342
+ const b = e.target.closest('.fd__btn'), row = e.target.closest('.fd__row');
343
+ if (!b || !row) return;
344
+ const act = b.dataset.act;
345
+ if (act === 'remove') { api.remove(row.dataset.id); return; }
346
+ if (act === 'retry') api.retry(row.dataset.id); else if (act === 'cancel') api.cancel(row.dataset.id);
347
+ focusIn(row); // the button pressed has gone: keep the focus in the row
348
+ });
349
+
350
+ // dragging files: anywhere over the page lights the zone; over the box it lifts and glows
351
+ const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes('Files');
352
+ const lift = (up) => {
353
+ root.classList.toggle('is-over', up);
354
+ if (RM()) return;
355
+ g.to(zone, { y: up ? -3 : 0, scale: up ? 1.012 : 1, duration: up ? 0.35 : 0.25, ease: up ? 'back.out(2)' : 'power2.out', overwrite: 'auto' });
356
+ g.to(ico, { y: up ? -5 : 0, scale: up ? 1.12 : 1, duration: up ? 0.4 : 0.25, ease: up ? 'back.out(2.4)' : 'power2.out', overwrite: 'auto' });
357
+ };
358
+ const pageOff = () => { clearTimeout(pageT); root.classList.remove('is-page'); if (depth) { depth = 0; lift(false); } };
359
+ // dragover keeps firing while a drag is over the page, so a short timer notices when it has left
360
+ on(document, 'dragover', (e) => { if (!hasFiles(e)) return; root.classList.add('is-page'); clearTimeout(pageT); pageT = setTimeout(pageOff, 260); });
361
+ on(document, 'drop', pageOff);
362
+ on(root, 'dragenter', (e) => { if (!hasFiles(e)) return; e.preventDefault(); if (++depth === 1) lift(true); });
363
+ on(root, 'dragover', (e) => { if (!hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; });
364
+ on(root, 'dragleave', () => { if (depth > 0 && --depth === 0) lift(false); });
365
+ on(root, 'drop', (e) => {
366
+ if (!hasFiles(e)) return;
367
+ e.preventDefault(); depth = 0; lift(false); pageOff();
368
+ api.add(e.dataTransfer.files);
369
+ });
370
+ // paste files (a screenshot, files copied in a file manager) while the zone or a row has focus
371
+ on(root, 'paste', (e) => {
372
+ const fs = [...(e.clipboardData?.files || [])];
373
+ if (!fs.length) return;
374
+ e.preventDefault(); api.add(fs);
375
+ });
376
+
377
+ return api;
378
+ };
package/src/gauge.js ADDED
@@ -0,0 +1,169 @@
1
+ /* Goal gauge: one number on a half-circle dial, like today's sales against a daily goal. When it scrolls
2
+ into view the arc fills from the left, the needle swings across and settles on the value with a small
3
+ overshoot, and the number underneath counts up. set() swings from wherever the needle is now, so a new
4
+ value never starts again from zero. Optional coloured zones (for example bad / warn / good) tint the
5
+ track, and the filled arc takes the colour of the zone it has reached. An optional goal tick marks the
6
+ target; once the value reaches it the line under the number says so. Past the maximum the arc stays
7
+ full and the number keeps counting. It is a role="meter" with the value read out as text. */
8
+ import * as M from '@gecko-ui-kit/motion';
9
+ import { esc } from '../index.js';
10
+
11
+ const { g, RM, $$ } = M;
12
+ const NS = 'http://www.w3.org/2000/svg';
13
+ const WORDS = {
14
+ label: 'Gauge',
15
+ goal: (goal) => `Goal ${goal}`,
16
+ reached: 'Goal reached',
17
+ valuetext: (value, goal, zone) => `${value}${zone ? ` (${zone})` : ''}${goal ? `, goal ${goal}` : ''}`,
18
+ };
19
+ const TONES = { accent: 'var(--accent)', good: 'var(--good)', warn: 'var(--warn)', bad: 'var(--bad)', ink: 'var(--ink-2)', muted: 'var(--muted)' };
20
+ const HUES = ['indigo', 'teal', 'rose', 'amber', 'violet', 'green', 'slate', 'sky'];
21
+ const toColor = (t) => (!t ? 'var(--accent)' : TONES[t] || (HUES.includes(t) ? `var(--hue-${t})` : String(t)));
22
+
23
+ const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
24
+ const r2 = (v) => Math.round(v * 100) / 100;
25
+ const num = (v, d = 0) => (Number.isFinite(+v) ? +v : d);
26
+ const decimals = (v) => { const s = String(v), i = s.indexOf('.'); return i < 0 || /e/i.test(s) ? 0 : Math.min(2, s.length - i - 1); };
27
+
28
+ /* The dial lives in a 200-wide box: centre (100, 100), radius 80, so the arc runs from (20, 100) over the top to (180, 100). */
29
+ const CX = 100, CY = 100, R = 80, SW = 16;
30
+ const ARC = `M${CX - R} ${CY}A${R} ${R} 0 0 1 ${CX + R} ${CY}`;
31
+ const at = (f, r) => [r2(CX - r * Math.cos(Math.PI * f)), r2(CY - r * Math.sin(Math.PI * f))];
32
+
33
+ /**
34
+ * const gg = gauge(el, {
35
+ * value: 864, min: 0, max: 1200,
36
+ * goal: 1000, // a tick on the arc + "Goal 1,000" under the number (null = none)
37
+ * zones: [{ to: 400, tone: 'bad', label: 'Low' }, { to: 800, tone: 'warn' }, { to: 1200, tone: 'good' }],
38
+ * // each zone runs from the one before (or min) up to `to`
39
+ * tone: 'accent', // colour of the filled arc when there are no zones
40
+ * format: (v) => string, // the number, the ends and the read-out
41
+ * label: "Today's sales", // shown under the number, and the meter's name for screen readers
42
+ * size: 240, // px across (shrinks with a narrow parent)
43
+ * needle: true, // false = no needle; the number moves up inside the arc
44
+ * ends: true, // min and max under the two ends of the arc
45
+ * words: { label, goal, reached, valuetext },
46
+ * })
47
+ * gg.set(value) // swings from where it is now
48
+ * gg.value · gg.destroy()
49
+ */
50
+ export const gauge = (el, opts = {}) => {
51
+ el = $$(el)[0];
52
+ if (!el) return null;
53
+ const o = { value: 0, min: 0, max: 100, goal: null, zones: null, tone: 'accent', format: null, label: '', size: 240, needle: true, ends: true, words: null, ...opts };
54
+ const W = { ...WORDS, ...o.words };
55
+ const ac = new AbortController(); // no listeners yet; kept so destroy() matches the other charts
56
+ const min = num(o.min, 0), max = num(o.max, 100) > min ? num(o.max, 100) : min + 1;
57
+ const goal = o.goal == null || o.goal === '' ? null : num(o.goal, null);
58
+ const fmt = (v) => (o.format ? String(o.format(v)) : Number(v).toLocaleString());
59
+ const frac = (v) => (v - min) / (max - min);
60
+ const zones = (o.zones || []).map((z) => ({ to: clamp(num(z.to, max), min, max), color: toColor(z.tone), label: z.label ?? '' })).sort((a, b) => a.to - b.to);
61
+ zones.forEach((z, k) => { z.from = k ? zones[k - 1].to : min; });
62
+ const zoneAt = (v) => zones.find((z) => v <= z.to) || (zones.length && v > max ? zones[zones.length - 1] : null);
63
+ const name = o.label || W.label;
64
+ const size = Math.max(120, num(o.size, 240)), H = o.ends ? 120 : 110;
65
+ const nLen = R - SW / 2 - 9, tip = CY - nLen;
66
+
67
+ const zoneSvg = zones.map((z) => {
68
+ const a = frac(z.from) * 100, len = frac(z.to) * 100 - a;
69
+ return len > 0 ? `<path class="gge__zone" d="${ARC}" pathLength="100" stroke-dasharray="${r2(len)} 200" stroke-dashoffset="${r2(-a)}" style="--c:${esc(z.color)}"/>` : '';
70
+ }).join('');
71
+ let goalSvg = '';
72
+ if (goal != null) {
73
+ const f = clamp(frac(goal), 0, 1), [x1, y1] = at(f, R - SW / 2 - 4), [x2, y2] = at(f, R + SW / 2 + 4);
74
+ goalSvg = `<line class="gge__goal" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}"/>`;
75
+ }
76
+ el.innerHTML = `<div class="gge${o.needle ? '' : ' gge--inside'}${zones.length ? ' gge--zones' : ''}" style="--gge-size:${size}px">`
77
+ + `<div class="gge__dial" role="meter" aria-label="${esc(name)}" aria-valuemin="${min}" aria-valuemax="${max}">`
78
+ + `<svg class="gge__svg" viewBox="0 0 200 ${H}" aria-hidden="true" xmlns="${NS}">`
79
+ + `<path class="gge__track" d="${ARC}"/>${zoneSvg}`
80
+ + `<path class="gge__fill" d="${ARC}" pathLength="100" stroke-dasharray="0 200"/>${goalSvg}`
81
+ + (o.needle ? `<g class="gge__needle"><path d="M${CX - 3.6} ${CY}L${CX - 0.9} ${r2(tip)}Q${CX} ${r2(tip - 2)} ${CX + 0.9} ${r2(tip)}L${CX + 3.6} ${CY}Z"/><circle class="gge__hub" cx="${CX}" cy="${CY}" r="7"/><circle class="gge__pin" cx="${CX}" cy="${CY}" r="2"/></g>` : '')
82
+ + (o.ends ? `<text class="gge__end" x="${CX - R}" y="${CY + 17}" text-anchor="middle">${esc(fmt(min))}</text><text class="gge__end" x="${CX + R}" y="${CY + 17}" text-anchor="middle">${esc(fmt(max))}</text>` : '')
83
+ + `</svg><div class="gge__read" aria-hidden="true"><b class="gge__num"></b>${o.label ? `<span class="gge__label">${esc(o.label)}</span>` : ''}${goal != null ? '<span class="gge__target"></span>' : ''}</div></div>`
84
+ + '<span class="gge__sr" role="status"></span></div>';
85
+ const root = el.firstElementChild, $ = (s) => root.querySelector(s);
86
+ const dial = $('.gge__dial'), fill = $('.gge__fill'), needle = $('.gge__needle'), goalEl = $('.gge__goal');
87
+ const numEl = $('.gge__num'), target = $('.gge__target'), live = $('[role="status"]');
88
+ const say = (t) => { live.textContent = ''; live.textContent = t; };
89
+
90
+ /* ---------- state: F drives the arc + number, N the needle (it overshoots a little) ---------- */
91
+ let value = num(o.value, min);
92
+ const F = { v: min }, N = { v: min };
93
+ let dp = decimals(value), lastColor = '';
94
+ const draw = () => {
95
+ const f = clamp(frac(F.v), 0, 1);
96
+ fill.setAttribute('stroke-dasharray', `${r2(f * 100)} 200`);
97
+ const c = zones.length ? zoneAt(F.v)?.color || toColor(o.tone) : toColor(o.tone);
98
+ if (c !== lastColor) { lastColor = c; fill.style.setProperty('--c', c); }
99
+ numEl.textContent = fmt(Math.round(F.v * 10 ** dp) / 10 ** dp);
100
+ if (needle) needle.setAttribute('transform', `rotate(${r2(clamp(frac(N.v), -0.04, 1.04) * 180 - 90)} ${CX} ${CY})`);
101
+ };
102
+ const aria = () => {
103
+ const z = zoneAt(value);
104
+ dial.setAttribute('aria-valuenow', String(clamp(value, min, max)));
105
+ dial.setAttribute('aria-valuetext', W.valuetext(fmt(value), goal != null ? fmt(goal) : '', z?.label || ''));
106
+ const reached = goal != null && value >= goal;
107
+ root.classList.toggle('is-reached', reached);
108
+ if (target) target.textContent = reached ? W.reached : W.goal(fmt(goal));
109
+ return reached;
110
+ };
111
+
112
+ let played = false, io = null, wasReached = false;
113
+ const swing = (to) => {
114
+ g.killTweensOf([F, N]);
115
+ if (RM()) { F.v = N.v = to; draw(); return; }
116
+ const dist = Math.abs(frac(to) - frac(F.v));
117
+ const dur = 0.55 + Math.min(1, dist) * 0.65;
118
+ g.to(F, { v: to, duration: dur + 0.1, ease: 'power3.out', onUpdate: draw, onComplete: draw });
119
+ if (needle) g.to(N, { v: to, duration: dur + 0.35, ease: 'back.out(1.7)', onUpdate: draw });
120
+ else N.v = to;
121
+ };
122
+ const celebrate = (reached) => {
123
+ if (reached && !wasReached && !RM()) {
124
+ if (goalEl) g.fromTo(goalEl, { scale: 1.9, transformOrigin: '50% 50%' }, { scale: 1, duration: 0.6, delay: 0.5, ease: 'back.out(3)', clearProps: 'transform' });
125
+ if (target) g.fromTo(target, { y: 4, opacity: 0 }, { y: 0, opacity: 1, duration: 0.4, delay: 0.55, ease: 'back.out(2)', clearProps: 'transform,opacity' });
126
+ }
127
+ wasReached = reached;
128
+ };
129
+ const play = () => {
130
+ if (played || ac.signal.aborted) return;
131
+ played = true; io?.disconnect(); io = null;
132
+ swing(value);
133
+ celebrate(goal != null && value >= goal);
134
+ };
135
+
136
+ /* ---------- build ---------- */
137
+ aria();
138
+ if (RM()) { F.v = N.v = value; played = true; wasReached = goal != null && value >= goal; }
139
+ draw();
140
+ if (!played) {
141
+ if (typeof IntersectionObserver !== 'function') play();
142
+ else {
143
+ io = new IntersectionObserver((en) => { if (en.some((x) => x.isIntersecting)) play(); }, { threshold: 0.4 });
144
+ io.observe(root);
145
+ }
146
+ }
147
+
148
+ const api = {
149
+ root,
150
+ get value() { return value; },
151
+ set(v) {
152
+ value = num(v, value);
153
+ dp = decimals(value);
154
+ const reached = aria();
155
+ if (!played) return api; // not on screen yet: the intro will swing to it
156
+ swing(value);
157
+ celebrate(reached);
158
+ say(dial.getAttribute('aria-valuetext'));
159
+ return api;
160
+ },
161
+ destroy() {
162
+ ac.abort(); io?.disconnect(); io = null;
163
+ g.killTweensOf([F, N]);
164
+ g.killTweensOf(root.querySelectorAll('*'));
165
+ el.innerHTML = '';
166
+ },
167
+ };
168
+ return api;
169
+ };