@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/upload.js
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/* Photo upload: drop photos on it, click to browse, or paste. Each photo appears as a tile that flies
|
|
2
|
+
in from where it was dropped and sharpens as it loads. While it uploads, a dark veil drains away
|
|
3
|
+
from the bottom up and a ring counts the percent; when it is done a tick pops and fades. A failed
|
|
4
|
+
upload turns red with a Retry button. Drag tiles to reorder them (the first one is the cover);
|
|
5
|
+
the others slide out of the way. Too big, wrong type or too many: the box shakes and says why.
|
|
6
|
+
You bring the upload function; without one the files are just kept, ready for a form. */
|
|
7
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
8
|
+
import { icon } from '@gecko-ui-kit/icons';
|
|
9
|
+
import { esc } from '../index.js';
|
|
10
|
+
|
|
11
|
+
const { g, RM, D, $$ } = M;
|
|
12
|
+
const MB = 1024 * 1024;
|
|
13
|
+
const WORDS = {
|
|
14
|
+
label: 'Photos',
|
|
15
|
+
title: 'Drop photos here',
|
|
16
|
+
browse: 'or click to choose',
|
|
17
|
+
add: 'Add',
|
|
18
|
+
drop: 'Drop to add',
|
|
19
|
+
hint: (o) => [o.maxSize ? `Up to ${o.maxSize} MB each` : '', o.max ? `${o.max} photos max` : ''].filter(Boolean).join(' · '),
|
|
20
|
+
cover: 'Cover',
|
|
21
|
+
remove: 'Remove',
|
|
22
|
+
retry: 'Retry',
|
|
23
|
+
failed: 'Upload failed',
|
|
24
|
+
uploading: 'Uploading',
|
|
25
|
+
waiting: 'Waiting',
|
|
26
|
+
done: 'Uploaded',
|
|
27
|
+
tooBig: (name, mb) => `${name} is larger than ${mb} MB`,
|
|
28
|
+
wrongType: (name) => `${name} is not a supported file`,
|
|
29
|
+
tooMany: (max) => `You can add up to ${max} photos`,
|
|
30
|
+
added: (n) => `${n} ${n === 1 ? 'photo' : 'photos'} added`,
|
|
31
|
+
removed: (name) => `${name} removed`,
|
|
32
|
+
moved: (name, i, n) => `${name} moved to ${i} of ${n}`,
|
|
33
|
+
keys: 'Alt + arrow keys to move, Delete to remove',
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
let seq = 0;
|
|
37
|
+
const uid = () => `pu${Date.now().toString(36)}${(seq++).toString(36)}`;
|
|
38
|
+
|
|
39
|
+
/** Does a file match an accept string like 'image/*,.heic'? */
|
|
40
|
+
const accepts = (file, accept) => {
|
|
41
|
+
if (!accept) return true;
|
|
42
|
+
const name = (file.name || '').toLowerCase(), type = (file.type || '').toLowerCase();
|
|
43
|
+
return accept.split(',').map((x) => x.trim().toLowerCase()).filter(Boolean).some((a) =>
|
|
44
|
+
a.startsWith('.') ? name.endsWith(a) : a.endsWith('/*') ? type.startsWith(a.slice(0, -1)) : type === a);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** Make a big photo smaller before it is uploaded (keeps it upright, re-encodes it). */
|
|
48
|
+
const shrink = async (file, { max = 2000, quality = 0.85, type } = {}) => {
|
|
49
|
+
if (!/^image\/(jpeg|png|webp)$/.test(file.type) || typeof createImageBitmap !== 'function') return file;
|
|
50
|
+
let bmp;
|
|
51
|
+
try { bmp = await createImageBitmap(file, { imageOrientation: 'from-image' }); } catch { return file; }
|
|
52
|
+
const s = Math.min(1, max / Math.max(bmp.width, bmp.height));
|
|
53
|
+
const out = type || (file.type === 'image/png' ? 'image/png' : 'image/jpeg');
|
|
54
|
+
if (s === 1 && out === file.type) { bmp.close?.(); return file; }
|
|
55
|
+
const c = document.createElement('canvas');
|
|
56
|
+
c.width = Math.round(bmp.width * s); c.height = Math.round(bmp.height * s);
|
|
57
|
+
c.getContext('2d').drawImage(bmp, 0, 0, c.width, c.height); bmp.close?.();
|
|
58
|
+
const blob = await new Promise((res) => c.toBlob(res, out, quality));
|
|
59
|
+
if (!blob || (s === 1 && blob.size >= file.size)) return file;
|
|
60
|
+
const ext = out.split('/')[1].replace('jpeg', 'jpg');
|
|
61
|
+
return new File([blob], file.name.replace(/\.[^.]+$/, '') + '.' + ext, { type: out, lastModified: file.lastModified });
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const RING = '<svg viewBox="0 0 44 44" aria-hidden="true"><circle class="pu__track" cx="22" cy="22" r="19"/><circle class="pu__arc" cx="22" cy="22" r="19" pathLength="1" stroke-dasharray="1" stroke-dashoffset="1"/></svg>';
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* const up = photoUpload(el, {
|
|
68
|
+
* accept: 'image/*', // like <input accept>: 'image/jpeg,image/png,.heic'
|
|
69
|
+
* max: 8, // most photos (0 = no limit)
|
|
70
|
+
* maxSize: 10, // MB per photo (0 = no limit)
|
|
71
|
+
* value: [{ url, … }], // photos that are already uploaded
|
|
72
|
+
* upload: async (file, { progress, signal, item }) => ({ url }), // your upload; call progress(0…1)
|
|
73
|
+
* concurrent: 2, // uploads at the same time
|
|
74
|
+
* resize: { max: 2000, quality: 0.85 }, // make big photos smaller first (optional)
|
|
75
|
+
* cover: true, // label the first photo "Cover"
|
|
76
|
+
* sortable: true, readOnly: false, capture: 'environment' (open the camera on phones),
|
|
77
|
+
* words: { title, browse, hint, … },
|
|
78
|
+
* onChange(items, up), onReject(file, reason, up), onUploaded(item, up), onError(item, error, up)
|
|
79
|
+
* })
|
|
80
|
+
* up.items · up.value (the results, in order) · up.busy · up.settled() → Promise
|
|
81
|
+
* up.add(files) · up.remove(id) · up.move(id, index) · up.retry(id) · up.clear() · up.open() · up.setValue(list) · up.destroy()
|
|
82
|
+
* Size: --pu-size (112px, smallest tile) · --pu-ratio (1) · --pu-gap (10px).
|
|
83
|
+
*/
|
|
84
|
+
export const photoUpload = (el, opts = {}) => {
|
|
85
|
+
el = $$(el)[0];
|
|
86
|
+
if (!el) return null;
|
|
87
|
+
const o = { accept: 'image/*', max: 8, maxSize: 10, value: [], upload: null, concurrent: 2, resize: null, cover: true, sortable: true, readOnly: false, capture: null, onChange: null, onReject: null, onUploaded: null, onError: null, ...opts };
|
|
88
|
+
const W = { ...WORDS, ...o.words };
|
|
89
|
+
const hint = typeof W.hint === 'function' ? W.hint(o) : W.hint;
|
|
90
|
+
|
|
91
|
+
el.innerHTML = `<div class="pu${o.cover ? ' pu--cover' : ''}${o.readOnly ? ' is-readonly' : ''}">`
|
|
92
|
+
+ `<input class="pu__input" type="file" tabindex="-1" aria-hidden="true"${o.accept ? ` accept="${esc(o.accept)}"` : ''}${o.max === 1 ? '' : ' multiple'}${o.capture ? ` capture="${esc(o.capture)}"` : ''}>`
|
|
93
|
+
+ `<ul class="pu__grid" role="list" aria-label="${esc(W.label)}" data-drop="${esc(W.drop)}">`
|
|
94
|
+
+ (o.readOnly ? '' : `<li class="pu__add"><button type="button" class="pu__pick"><span class="pu__ico">${icon('image')}</span>`
|
|
95
|
+
+ `<span class="pu__big"><b>${esc(W.title)}</b><small>${esc(W.browse)}</small>${hint ? `<small class="pu__hint">${esc(hint)}</small>` : ''}</span>`
|
|
96
|
+
+ `<span class="pu__small"><b>${esc(W.add)}</b><small class="pu__count"></small></span></button></li>`)
|
|
97
|
+
+ `</ul><p class="pu__msg" role="alert"></p><span class="pu__sr" role="status"></span></div>`;
|
|
98
|
+
const root = el.firstElementChild, grid = root.querySelector('.pu__grid'), input = root.querySelector('.pu__input');
|
|
99
|
+
const addLi = root.querySelector('.pu__add'), pick = root.querySelector('.pu__pick');
|
|
100
|
+
|
|
101
|
+
/** @type {{ id, name, size, type, file, src, status, progress, result, error, el, ac, own }[]} */
|
|
102
|
+
let items = [];
|
|
103
|
+
let msgT = null, active = 0, waiters = [];
|
|
104
|
+
const say = (t) => { root.querySelector('.pu__sr').textContent = t; };
|
|
105
|
+
const tiles = () => [...grid.querySelectorAll(':scope > .pu__tile')];
|
|
106
|
+
const byId = (id) => items.find((x) => x.id === id);
|
|
107
|
+
const pub = (x) => ({ id: x.id, name: x.name, size: x.size, type: x.type, file: x.file, url: x.src, status: x.status, progress: x.progress, result: x.result, error: x.error });
|
|
108
|
+
|
|
109
|
+
/** Move things in the grid, then slide every tile from where it was to where it is now. */
|
|
110
|
+
const flip = (mutate, skip) => {
|
|
111
|
+
const els = [...grid.children];
|
|
112
|
+
const before = new Map(els.map((x) => [x, x.getBoundingClientRect()]));
|
|
113
|
+
mutate();
|
|
114
|
+
if (RM()) return;
|
|
115
|
+
before.forEach((r, x) => {
|
|
116
|
+
if (x === skip || !x.isConnected || x.classList.contains('is-gone')) return;
|
|
117
|
+
const n = x.getBoundingClientRect(), dx = r.left - n.left, dy = r.top - n.top;
|
|
118
|
+
if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) g.fromTo(x, { x: dx, y: dy }, { x: 0, y: 0, duration: 0.38, ease: 'power3.out', overwrite: 'auto', clearProps: 'transform' });
|
|
119
|
+
});
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const room = () => (o.max ? o.max - items.length : Infinity);
|
|
123
|
+
const shape = () => {
|
|
124
|
+
root.classList.toggle('is-empty', !items.length);
|
|
125
|
+
root.classList.toggle('is-full', !!o.max && items.length >= o.max);
|
|
126
|
+
const c = root.querySelector('.pu__count'); if (c) c.textContent = o.max ? `${items.length} / ${o.max}` : '';
|
|
127
|
+
tiles().forEach((t, i) => {
|
|
128
|
+
const x = byId(t.dataset.id); if (!x) return;
|
|
129
|
+
const st = { queued: W.waiting, uploading: `${W.uploading} ${Math.round(x.progress * 100)}%`, error: W.failed, done: '' }[x.status];
|
|
130
|
+
t.setAttribute('aria-label', [x.name, `${i + 1} / ${items.length}`, o.cover && i === 0 ? W.cover : '', st].filter(Boolean).join(', '));
|
|
131
|
+
});
|
|
132
|
+
};
|
|
133
|
+
const changed = () => { shape(); o.onChange?.(items.map(pub), api); };
|
|
134
|
+
|
|
135
|
+
const tell = (text) => {
|
|
136
|
+
const m = root.querySelector('.pu__msg'); m.textContent = text; clearTimeout(msgT);
|
|
137
|
+
if (!RM()) { M.shake(addLi && !root.classList.contains('is-full') ? addLi : grid); g.fromTo(m, { y: -4, opacity: 0 }, { y: 0, opacity: 1, duration: 0.25 }); }
|
|
138
|
+
msgT = setTimeout(() => { m.textContent = ''; }, 4500);
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/* ---------- tiles ---------- */
|
|
142
|
+
const tileHTML = (x) => `<li class="pu__tile" data-id="${x.id}" role="listitem"${o.readOnly ? '' : ` tabindex="0" title="${esc(W.keys)}"`}>`
|
|
143
|
+
+ `<img class="pu__img" alt="" draggable="false" decoding="async"><span class="pu__veil"></span>`
|
|
144
|
+
+ `<span class="pu__state"><span class="pu__ring">${RING}<b>0%</b></span><span class="pu__tick">${icon('check')}</span>`
|
|
145
|
+
+ `<span class="pu__err">${icon('alert')}<small>${esc(W.failed)}</small><button type="button" class="pu__retry">${esc(W.retry)}</button></span></span>`
|
|
146
|
+
+ `<span class="pu__badge">${esc(W.cover)}</span>`
|
|
147
|
+
+ (o.readOnly ? '' : `<button type="button" class="pu__x" aria-label="${esc(W.remove)}: ${esc(x.name)}" title="${esc(W.remove)}">${icon('close')}</button>`)
|
|
148
|
+
+ '</li>';
|
|
149
|
+
|
|
150
|
+
const build = (x) => {
|
|
151
|
+
const t = document.createElement('template'); t.innerHTML = tileHTML(x);
|
|
152
|
+
const li = t.content.firstElementChild; x.el = li;
|
|
153
|
+
const img = li.querySelector('.pu__img');
|
|
154
|
+
img.addEventListener('load', () => {
|
|
155
|
+
li.classList.remove('is-broken');
|
|
156
|
+
if (!RM()) g.fromTo(img, { opacity: 0, scale: 1.08, filter: 'blur(10px)' }, { opacity: 1, scale: 1, filter: 'blur(0px)', duration: 0.55, ease: 'power2.out', clearProps: 'filter,transform' });
|
|
157
|
+
}, { once: true });
|
|
158
|
+
img.addEventListener('error', () => { li.classList.add('is-broken'); li.dataset.ext = (x.name.split('.').pop() || '').slice(0, 4).toUpperCase(); }, { once: true });
|
|
159
|
+
img.src = x.src || '';
|
|
160
|
+
paint(x, true);
|
|
161
|
+
return li;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
/** Show an item's state on its tile. */
|
|
165
|
+
const paint = (x, quiet = false) => {
|
|
166
|
+
const li = x.el; if (!li) return;
|
|
167
|
+
['queued', 'uploading', 'done', 'error'].forEach((s) => li.classList.toggle(`is-${s}`, x.status === s));
|
|
168
|
+
const pct = Math.round(x.progress * 100);
|
|
169
|
+
li.querySelector('.pu__ring b').textContent = `${pct}%`;
|
|
170
|
+
const arc = li.querySelector('.pu__arc'), veil = li.querySelector('.pu__veil');
|
|
171
|
+
const v = x.status === 'uploading' ? x.progress : x.status === 'queued' ? 0 : 1;
|
|
172
|
+
x.vt?.kill(); x.vt = null;
|
|
173
|
+
if (quiet || RM()) { arc.setAttribute('stroke-dashoffset', String(1 - v)); veil.style.clipPath = x.status === 'error' ? '' : `inset(0 0 ${v * 100}% 0)`; return; }
|
|
174
|
+
g.to(arc, { attr: { 'stroke-dashoffset': 1 - v }, duration: 0.3, ease: 'power2.out', overwrite: true });
|
|
175
|
+
if (x.status === 'error') { veil.style.clipPath = ''; return; } // the whole tile turns red
|
|
176
|
+
const p = { v: parseFloat((veil.style.clipPath.match(/([\d.]+)%\)/) || [])[1] || 0) / 100 };
|
|
177
|
+
x.vt = g.to(p, { v, duration: 0.3, ease: 'power2.out', onUpdate: () => { veil.style.clipPath = `inset(0 0 ${p.v * 100}% 0)`; } });
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
/* ---------- uploads ---------- */
|
|
181
|
+
const settle = () => { if (!api.busy) { const w = waiters; waiters = []; w.forEach((f) => f(api.value)); } };
|
|
182
|
+
const pump = () => {
|
|
183
|
+
if (!o.upload) return;
|
|
184
|
+
while (active < Math.max(1, o.concurrent)) {
|
|
185
|
+
const x = items.find((i) => i.status === 'queued' && i.ready);
|
|
186
|
+
if (!x) break;
|
|
187
|
+
send(x);
|
|
188
|
+
}
|
|
189
|
+
settle();
|
|
190
|
+
};
|
|
191
|
+
const send = async (x) => {
|
|
192
|
+
active++; x.status = 'uploading'; x.progress = 0; x.error = null; paint(x); shape();
|
|
193
|
+
const ac = new AbortController(); x.ac = ac;
|
|
194
|
+
try {
|
|
195
|
+
const result = await o.upload(x.file, { signal: ac.signal, item: pub(x), progress: (p) => { if (ac.signal.aborted || x.status !== 'uploading') return; x.progress = Math.max(0, Math.min(1, +p || 0)); paint(x); shape(); } });
|
|
196
|
+
if (ac.signal.aborted) return;
|
|
197
|
+
x.status = 'done'; x.progress = 1; x.result = result; paint(x);
|
|
198
|
+
if (!RM() && x.el) { const tk = x.el.querySelector('.pu__tick'); g.timeline().fromTo(tk, { scale: 0.3, opacity: 0 }, { scale: 1, opacity: 1, duration: 0.4, ease: 'back.out(2.2)' }).to(tk, { scale: 0.8, opacity: 0, duration: 0.3, ease: 'power2.in', delay: 0.6 }); }
|
|
199
|
+
say(`${x.name}: ${W.done}`); o.onUploaded?.(pub(x), api); changed();
|
|
200
|
+
} catch (err) {
|
|
201
|
+
if (ac.signal.aborted) return;
|
|
202
|
+
x.status = 'error'; x.error = err; paint(x);
|
|
203
|
+
if (x.el && !RM()) M.shake(x.el);
|
|
204
|
+
say(`${x.name}: ${W.failed}`); o.onError?.(pub(x), err, api); changed();
|
|
205
|
+
} finally {
|
|
206
|
+
active--; x.ac = null; pump();
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
/* ---------- adding & removing ---------- */
|
|
211
|
+
const fresh = (file) => ({ id: uid(), name: file.name || 'photo', size: file.size, type: file.type, file, src: URL.createObjectURL(file), own: true, status: o.upload ? 'queued' : 'done', progress: 0, result: o.upload ? null : file, error: null, ready: !o.resize });
|
|
212
|
+
|
|
213
|
+
const insert = (list, from) => {
|
|
214
|
+
if (!list.length) return;
|
|
215
|
+
const wasEmpty = !items.length;
|
|
216
|
+
list.forEach((x) => build(x));
|
|
217
|
+
const before = addLi?.getBoundingClientRect();
|
|
218
|
+
flip(() => { list.forEach((x) => grid.insertBefore(x.el, addLi || null)); items.push(...list); shape(); }, addLi);
|
|
219
|
+
if (RM()) return;
|
|
220
|
+
list.forEach((x, i) => {
|
|
221
|
+
if (from) { // fly in from where they were dropped
|
|
222
|
+
const r = x.el.getBoundingClientRect();
|
|
223
|
+
g.fromTo(x.el, { x: from.x - (r.left + r.width / 2), y: from.y - (r.top + r.height / 2), scale: 0.3, rotation: (i % 2 ? 1 : -1) * 8, opacity: 0 }, { x: 0, y: 0, scale: 1, rotation: 0, opacity: 1, duration: 0.6, delay: i * 0.06, ease: 'power3.out', clearProps: 'transform,opacity' });
|
|
224
|
+
} else g.fromTo(x.el, { scale: 0.6, opacity: 0 }, { scale: 1, opacity: 1, duration: 0.45, delay: i * 0.05, ease: 'back.out(1.7)', clearProps: 'transform,opacity' });
|
|
225
|
+
});
|
|
226
|
+
if (addLi && wasEmpty) g.fromTo(addLi, { opacity: 0, scale: 0.85 }, { opacity: 1, scale: 1, duration: 0.4, delay: 0.1, ease: 'power3.out', clearProps: 'transform,opacity' });
|
|
227
|
+
else if (addLi && before) { const n = addLi.getBoundingClientRect(); if (Math.abs(before.left - n.left) + Math.abs(before.top - n.top) > 1) g.fromTo(addLi, { x: before.left - n.left, y: before.top - n.top }, { x: 0, y: 0, duration: 0.38, ease: 'power3.out', clearProps: 'transform' }); }
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
const drop = (x) => { x.ac?.abort(); x.vt?.kill(); if (x.own) setTimeout(() => URL.revokeObjectURL(x.src), 1000); };
|
|
231
|
+
|
|
232
|
+
const api = {
|
|
233
|
+
el: root, opts: o,
|
|
234
|
+
get items() { return items.map(pub); },
|
|
235
|
+
/** What to save: each photo's upload result (or the File when there is no upload function), in order. */
|
|
236
|
+
get value() { return items.filter((x) => x.status === 'done').map((x) => x.result); },
|
|
237
|
+
get busy() { return items.some((x) => x.status === 'queued' || x.status === 'uploading'); },
|
|
238
|
+
/** Resolves with value once nothing is waiting or uploading (failed ones are left out). */
|
|
239
|
+
settled() { return api.busy ? new Promise((r) => waiters.push(r)) : Promise.resolve(api.value); },
|
|
240
|
+
/** Add files (a FileList or array). from: { x, y } on screen, where they fly in from. */
|
|
241
|
+
add(files, from = null) {
|
|
242
|
+
const ok = [];
|
|
243
|
+
for (const f of [...(files || [])]) {
|
|
244
|
+
if (!(f instanceof Blob)) continue;
|
|
245
|
+
const name = f.name || 'photo';
|
|
246
|
+
if (!accepts(f, o.accept)) { tell(W.wrongType(name)); o.onReject?.(f, 'type', api); continue; }
|
|
247
|
+
if (o.maxSize && f.size > o.maxSize * MB) { tell(W.tooBig(name, o.maxSize)); o.onReject?.(f, 'size', api); continue; }
|
|
248
|
+
if (ok.length >= room()) { tell(W.tooMany(o.max)); o.onReject?.(f, 'count', api); continue; }
|
|
249
|
+
ok.push(fresh(f));
|
|
250
|
+
}
|
|
251
|
+
if (!ok.length) return [];
|
|
252
|
+
insert(ok, from);
|
|
253
|
+
say(W.added(ok.length));
|
|
254
|
+
changed();
|
|
255
|
+
ok.forEach(async (x) => {
|
|
256
|
+
if (o.resize) {
|
|
257
|
+
const f = await shrink(x.file, o.resize === true ? {} : o.resize).catch(() => x.file);
|
|
258
|
+
if (!byId(x.id)) return;
|
|
259
|
+
x.file = f; x.size = f.size; x.type = f.type; if (!o.upload) x.result = f;
|
|
260
|
+
x.ready = true;
|
|
261
|
+
}
|
|
262
|
+
pump();
|
|
263
|
+
});
|
|
264
|
+
if (!o.resize) pump();
|
|
265
|
+
return ok.map(pub);
|
|
266
|
+
},
|
|
267
|
+
remove(id) {
|
|
268
|
+
const x = byId(id); if (!x) return api;
|
|
269
|
+
const i = items.indexOf(x), wasFull = root.classList.contains('is-full');
|
|
270
|
+
items.splice(i, 1); drop(x);
|
|
271
|
+
const li = x.el, next = tiles()[tiles().indexOf(li) + 1] || tiles()[tiles().indexOf(li) - 1] || pick;
|
|
272
|
+
if (li?.contains(document.activeElement)) next?.focus({ preventScroll: true });
|
|
273
|
+
say(W.removed(x.name));
|
|
274
|
+
const gone = () => { flip(() => { li?.remove(); shape(); }); if (wasFull && addLi && !RM()) g.fromTo(addLi, { opacity: 0, scale: 0.8 }, { opacity: 1, scale: 1, duration: 0.35, ease: 'back.out(1.6)', clearProps: 'transform,opacity' }); };
|
|
275
|
+
if (li && !RM()) { li.classList.add('is-gone'); g.to(li, { scale: 0.5, opacity: 0, duration: 0.22, ease: 'power2.in', onComplete: gone }); }
|
|
276
|
+
else gone();
|
|
277
|
+
changed(); pump();
|
|
278
|
+
return api;
|
|
279
|
+
},
|
|
280
|
+
/** Put a photo at a new place (0 = first, the cover). */
|
|
281
|
+
move(id, index) {
|
|
282
|
+
const x = byId(id); if (!x) return api;
|
|
283
|
+
const from = items.indexOf(x); index = Math.max(0, Math.min(items.length - 1, index));
|
|
284
|
+
if (from === index) return api;
|
|
285
|
+
const cover0 = items[0];
|
|
286
|
+
items.splice(from, 1); items.splice(index, 0, x);
|
|
287
|
+
flip(() => grid.insertBefore(x.el, items[index + 1]?.el || addLi || null));
|
|
288
|
+
if (o.cover && items[0] !== cover0 && !RM()) M.pop(items[0].el.querySelector('.pu__badge'));
|
|
289
|
+
say(W.moved(x.name, index + 1, items.length)); changed();
|
|
290
|
+
return api;
|
|
291
|
+
},
|
|
292
|
+
retry(id) {
|
|
293
|
+
const x = byId(id); if (!x || x.status !== 'error') return api;
|
|
294
|
+
x.status = 'queued'; x.progress = 0; x.ready = true; paint(x); shape(); pump();
|
|
295
|
+
return api;
|
|
296
|
+
},
|
|
297
|
+
clear() { items.forEach(drop); items = []; tiles().forEach((t) => t.remove()); shape(); changed(); settle(); return api; },
|
|
298
|
+
/** Open the file picker. */
|
|
299
|
+
open() { if (!o.readOnly) input.click(); return api; },
|
|
300
|
+
/** Show photos that are already uploaded: [{ url, name?, …anything }] (kept as each one's result). */
|
|
301
|
+
setValue(list = []) {
|
|
302
|
+
items.forEach(drop); tiles().forEach((t) => t.remove()); items = [];
|
|
303
|
+
const xs = list.map((v) => { const url = typeof v === 'string' ? v : v.url; return { id: uid(), name: (typeof v === 'object' && v.name) || decodeURIComponent((url || '').split('/').pop().split('?')[0]) || 'photo', size: 0, type: '', file: null, src: url, own: false, status: 'done', progress: 1, result: v, error: null, ready: true }; });
|
|
304
|
+
xs.forEach((x) => { build(x); grid.insertBefore(x.el, addLi || null); });
|
|
305
|
+
items = xs; shape();
|
|
306
|
+
return api;
|
|
307
|
+
},
|
|
308
|
+
destroy() { clearTimeout(msgT); ac.abort(); items.forEach(drop); el.innerHTML = ''; },
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
/* ---------- events ---------- */
|
|
312
|
+
const ac = new AbortController(), on = { signal: ac.signal };
|
|
313
|
+
pick?.addEventListener('click', () => api.open(), on);
|
|
314
|
+
input.addEventListener('change', () => { api.add(input.files); input.value = ''; }, on);
|
|
315
|
+
|
|
316
|
+
// drag files in from the desktop
|
|
317
|
+
let depth = 0;
|
|
318
|
+
const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes('Files');
|
|
319
|
+
root.addEventListener('dragenter', (e) => { if (o.readOnly || !hasFiles(e)) return; e.preventDefault(); depth++; root.classList.add('is-over'); }, on);
|
|
320
|
+
root.addEventListener('dragover', (e) => { if (o.readOnly || !hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = root.classList.contains('is-full') ? 'none' : 'copy'; }, on);
|
|
321
|
+
root.addEventListener('dragleave', () => { if (--depth <= 0) { depth = 0; root.classList.remove('is-over'); } }, on);
|
|
322
|
+
root.addEventListener('drop', (e) => {
|
|
323
|
+
if (o.readOnly || !hasFiles(e)) return;
|
|
324
|
+
e.preventDefault(); depth = 0; root.classList.remove('is-over');
|
|
325
|
+
api.add(e.dataTransfer.files, { x: e.clientX, y: e.clientY });
|
|
326
|
+
}, on);
|
|
327
|
+
// paste a screenshot or copied image while the box has focus
|
|
328
|
+
root.addEventListener('paste', (e) => {
|
|
329
|
+
if (o.readOnly) return;
|
|
330
|
+
const fs = [...(e.clipboardData?.files || [])]; if (!fs.length) return;
|
|
331
|
+
e.preventDefault(); api.add(fs);
|
|
332
|
+
}, on);
|
|
333
|
+
|
|
334
|
+
root.addEventListener('click', (e) => {
|
|
335
|
+
const t = e.target.closest('.pu__tile'); if (!t) return;
|
|
336
|
+
if (e.target.closest('.pu__x')) api.remove(t.dataset.id);
|
|
337
|
+
else if (e.target.closest('.pu__retry')) api.retry(t.dataset.id);
|
|
338
|
+
}, on);
|
|
339
|
+
|
|
340
|
+
root.addEventListener('keydown', (e) => {
|
|
341
|
+
const t = e.target.closest?.('.pu__tile'); if (!t || e.target !== t || o.readOnly) return;
|
|
342
|
+
const i = items.indexOf(byId(t.dataset.id)), list = tiles();
|
|
343
|
+
if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); api.remove(t.dataset.id); return; }
|
|
344
|
+
const dir = { ArrowLeft: -1, ArrowUp: -1, ArrowRight: 1, ArrowDown: 1 }[e.key]; if (!dir && e.key !== 'Home' && e.key !== 'End') return;
|
|
345
|
+
e.preventDefault();
|
|
346
|
+
const to = e.key === 'Home' ? 0 : e.key === 'End' ? items.length - 1 : i + dir;
|
|
347
|
+
if ((e.altKey || e.ctrlKey || e.metaKey) && o.sortable) { api.move(t.dataset.id, to); t.focus({ preventScroll: true }); }
|
|
348
|
+
else list[Math.max(0, Math.min(list.length - 1, to))]?.focus();
|
|
349
|
+
}, on);
|
|
350
|
+
|
|
351
|
+
/* ---------- drag to reorder ---------- */
|
|
352
|
+
let d = null;
|
|
353
|
+
const lift = () => {
|
|
354
|
+
d.on = true; d.el.classList.add('is-lift'); root.classList.add('is-sorting');
|
|
355
|
+
if (d.touch) navigator.vibrate?.(8);
|
|
356
|
+
if (!RM()) g.to(d.el, { scale: 1.07, rotation: d.tilt, duration: 0.2, ease: 'power2.out' });
|
|
357
|
+
};
|
|
358
|
+
const follow = (cx, cy) => {
|
|
359
|
+
const gr = grid.getBoundingClientRect();
|
|
360
|
+
const px = cx - gr.left, py = cy - gr.top;
|
|
361
|
+
// the tile under the pointer, by layout position (ignores tiles that are still sliding)
|
|
362
|
+
const over = tiles().find((t) => t !== d.el && px >= t.offsetLeft && px <= t.offsetLeft + t.offsetWidth && py >= t.offsetTop && py <= t.offsetTop + t.offsetHeight);
|
|
363
|
+
if (over) {
|
|
364
|
+
const from = items.indexOf(byId(d.el.dataset.id)), to = items.indexOf(byId(over.dataset.id));
|
|
365
|
+
const x = items[from]; items.splice(from, 1); items.splice(to, 0, x);
|
|
366
|
+
flip(() => grid.insertBefore(d.el, items[to + 1]?.el || addLi || null), d.el);
|
|
367
|
+
}
|
|
368
|
+
g.set(d.el, { x: px - d.gx - d.el.offsetLeft, y: py - d.gy - d.el.offsetTop });
|
|
369
|
+
};
|
|
370
|
+
const endDrag = (cancelled) => {
|
|
371
|
+
const x = d; d = null;
|
|
372
|
+
clearTimeout(x.timer);
|
|
373
|
+
removeEventListener('pointermove', onMove); removeEventListener('pointerup', onUp); removeEventListener('pointercancel', onCancel);
|
|
374
|
+
if (!x.on) return;
|
|
375
|
+
x.el.classList.remove('is-lift'); root.classList.remove('is-sorting');
|
|
376
|
+
if (cancelled) {
|
|
377
|
+
const now = items.indexOf(byId(x.el.dataset.id));
|
|
378
|
+
if (now !== x.from) { const it = items.splice(now, 1)[0]; items.splice(x.from, 0, it); flip(() => grid.insertBefore(x.el, items[x.from + 1]?.el || addLi || null), x.el); }
|
|
379
|
+
}
|
|
380
|
+
if (RM()) g.set(x.el, { clearProps: 'transform' });
|
|
381
|
+
else g.to(x.el, { x: 0, y: 0, scale: 1, rotation: 0, duration: 0.45, ease: 'back.out(1.6)', clearProps: 'transform' });
|
|
382
|
+
const at = items.indexOf(byId(x.el.dataset.id));
|
|
383
|
+
if (!cancelled && at !== x.from) {
|
|
384
|
+
if (o.cover && (at === 0 || x.from === 0) && !RM()) M.pop(items[0].el.querySelector('.pu__badge'));
|
|
385
|
+
say(W.moved(byId(x.el.dataset.id).name, at + 1, items.length)); changed();
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
const onMove = (e) => {
|
|
389
|
+
if (!d || e.pointerId !== d.pid) return;
|
|
390
|
+
const dist = Math.hypot(e.clientX - d.sx, e.clientY - d.sy);
|
|
391
|
+
if (!d.on) {
|
|
392
|
+
if (d.touch) { if (dist > 8) endDrag(true); return; } // a swipe before the long-press: let the page scroll
|
|
393
|
+
if (dist < 5) return;
|
|
394
|
+
lift();
|
|
395
|
+
}
|
|
396
|
+
e.preventDefault();
|
|
397
|
+
follow(e.clientX, e.clientY);
|
|
398
|
+
};
|
|
399
|
+
const onUp = (e) => { if (d && e.pointerId === d.pid) endDrag(false); };
|
|
400
|
+
const onCancel = (e) => { if (d && e.pointerId === d.pid) endDrag(true); };
|
|
401
|
+
grid.addEventListener('pointerdown', (e) => {
|
|
402
|
+
const t = e.target.closest('.pu__tile');
|
|
403
|
+
if (!t || !o.sortable || o.readOnly || e.button > 0 || d || e.target.closest('button') || items.length < 2) return;
|
|
404
|
+
const r = t.getBoundingClientRect();
|
|
405
|
+
d = { el: t, pid: e.pointerId, sx: e.clientX, sy: e.clientY, gx: e.clientX - r.left, gy: e.clientY - r.top, on: false, touch: e.pointerType === 'touch', from: items.indexOf(byId(t.dataset.id)), tilt: (Math.random() < 0.5 ? -1 : 1) * 2 };
|
|
406
|
+
if (d.touch) d.timer = setTimeout(() => { if (d && !d.on) lift(); }, 320);
|
|
407
|
+
addEventListener('pointermove', onMove, { passive: false }); addEventListener('pointerup', onUp); addEventListener('pointercancel', onCancel);
|
|
408
|
+
}, on);
|
|
409
|
+
// while a finger holds a tile, the page must not scroll
|
|
410
|
+
grid.addEventListener('touchmove', (e) => { if (d?.on) e.preventDefault(); }, { passive: false, signal: ac.signal });
|
|
411
|
+
grid.addEventListener('contextmenu', (e) => { if (e.target.closest('.pu__tile')) e.preventDefault(); }, on);
|
|
412
|
+
ac.signal.addEventListener('abort', () => { if (d) endDrag(true); });
|
|
413
|
+
|
|
414
|
+
if (o.value?.length) api.setValue(o.value); else shape();
|
|
415
|
+
return api;
|
|
416
|
+
};
|