@gecko-ui-kit/components 0.0.0-stage → 0.21.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 +904 -2
- package/index.js +225 -0
- package/package.json +42 -4
- package/src/accordion.js +208 -0
- package/src/activity.js +218 -0
- package/src/alert.js +205 -0
- package/src/authform.js +285 -0
- package/src/beforeafter.js +141 -0
- package/src/bell.js +137 -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/like.js +208 -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/pay.js +162 -0
- package/src/pricing.js +189 -0
- package/src/radiocards.js +101 -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/speeddial.js +128 -0
- package/src/spinner.js +38 -0
- package/src/stepper.js +211 -0
- package/src/subscribe.js +173 -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/typing.js +93 -0
- package/src/upload.js +416 -0
- package/src/virtuallist.js +373 -0
- package/src/wizard.js +392 -0
- package/style.css +2092 -0
package/src/swipe.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/* Swipe actions: slide a list row sideways to show the buttons behind it (archive, delete, pin…).
|
|
2
|
+
The buttons fan out from under each other as the row moves and each icon grows as it is
|
|
3
|
+
uncovered. Let go past half way and the row stays open; a quick flick opens or shuts it.
|
|
4
|
+
Pull further (a "long swipe") and the edge button stretches over the whole row, its icon
|
|
5
|
+
riding with your finger; let go there and it runs straight away. An action can remove the row
|
|
6
|
+
(it slides off and the gap closes), and ctx.undo() brings it back. Rows scroll up and down as
|
|
7
|
+
usual: only a sideways move picks one up. Arrow keys open a focused row, Escape shuts it. */
|
|
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 TONES = new Set(['good', 'bad', 'warn', 'accent', 'neutral']);
|
|
14
|
+
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
|
15
|
+
const svg = (ic) => (!ic ? '' : String(ic).trim().startsWith('<') ? ic : icon(ic));
|
|
16
|
+
|
|
17
|
+
const actBtn = (a) => `<button type="button" class="swp__act swp__act--${TONES.has(a.tone) ? a.tone : 'neutral'}" data-act="${esc(a.id)}"${a.remove ? ' data-remove' : ''} tabindex="-1"><span class="swp__in">${svg(a.icon)}<span class="swp__lb">${esc(a.label ?? a.id)}</span></span></button>`;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* swipeItem({ body, start, end, id, look: 'both'|'icons'|'labels', label }) → HTML for one row.
|
|
21
|
+
* body: the row's own HTML (what people see before they swipe).
|
|
22
|
+
* start: actions shown when the row is pulled right; end: when it is pulled left.
|
|
23
|
+
* Each: { id, label, icon: 'trash' | '<svg…>', tone: 'good'|'bad'|'warn'|'accent'|'neutral', remove: false }.
|
|
24
|
+
* List them from the screen edge inward: the first one sits at the edge and is the one a long swipe runs.
|
|
25
|
+
* look: 'icons' keeps labels for screen readers only, 'labels' hides the icons.
|
|
26
|
+
* label: an accessible name for the row (otherwise its text is read).
|
|
27
|
+
*/
|
|
28
|
+
export const swipeItem = ({ body = '', start = [], end = [], id = '', look = 'both', label = '' } = {}) =>
|
|
29
|
+
`<div class="swp${look === 'icons' || look === 'labels' ? ` swp--${look}` : ''}"${id !== '' ? ` data-id="${esc(id)}"` : ''}>`
|
|
30
|
+
+ `<div class="swp__main" tabindex="0"${label ? ` aria-label="${esc(label)}"` : ''} aria-keyshortcuts="ArrowLeft ArrowRight">${body}</div>`
|
|
31
|
+
+ `<div class="swp__acts swp__acts--start">${start.map(actBtn).join('')}</div>`
|
|
32
|
+
+ `<div class="swp__acts swp__acts--end">${[...end].reverse().map(actBtn).join('')}</div></div>`;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* const sw = swipeActions(list, {
|
|
36
|
+
* full: true, // a long swipe runs the edge action
|
|
37
|
+
* fullAt: 0.55, // how far (share of the row's width) a long swipe must go
|
|
38
|
+
* single: true, // opening one row shuts the others
|
|
39
|
+
* haptic: true, // a tiny buzz on phones when a long swipe is ready
|
|
40
|
+
* onAction(id, ctx, sw) // ctx: { row, id (the row's data-id), action, undo() }. Return false to keep the row.
|
|
41
|
+
* onOpen(row, side), onClose(row)
|
|
42
|
+
* })
|
|
43
|
+
* list: any box holding .swp rows from swipeItem() (rows added later work too).
|
|
44
|
+
* sw.open(row, 'start'|'end') · sw.close(row?) · sw.peek(row?, side) (a nudge that hints at the gesture)
|
|
45
|
+
* sw.openRow · sw.destroy(). A row can be an element, its data-id or a selector.
|
|
46
|
+
* Button width: --swp-w (default 76px) on the list or any parent.
|
|
47
|
+
*/
|
|
48
|
+
export const swipeActions = (list, opts = {}) => {
|
|
49
|
+
list = $$(list)[0];
|
|
50
|
+
if (!list) return null;
|
|
51
|
+
if (list.__swp) { Object.assign(list.__swp.opts, opts); return list.__swp; }
|
|
52
|
+
const o = { full: true, fullAt: 0.55, single: true, haptic: true, onAction: null, onOpen: null, onClose: null, ...opts };
|
|
53
|
+
|
|
54
|
+
const rowOf = (r) => {
|
|
55
|
+
if (!r) return null;
|
|
56
|
+
if (r instanceof Element) return r.closest('.swp');
|
|
57
|
+
return list.querySelector(`.swp[data-id="${CSS.escape(String(r))}"]`) || list.querySelector(r);
|
|
58
|
+
};
|
|
59
|
+
const actsOf = (row, side) => { const b = [...row.querySelectorAll(`:scope > .swp__acts--${side} > .swp__act`)]; return side === 'end' ? b.reverse() : b; };
|
|
60
|
+
const bw = (row) => parseFloat(getComputedStyle(row).getPropertyValue('--swp-w')) || 76;
|
|
61
|
+
|
|
62
|
+
/** Each row's state lives on the element: x (how far it is pulled), grow (0–1, the long-swipe stretch). */
|
|
63
|
+
const stOf = (row) => {
|
|
64
|
+
if (!row.__swpSt) row.__swpSt = { row, main: row.querySelector(':scope > .swp__main'), x: 0, grow: 0, armed: false, open: null, tw: null, gw: null };
|
|
65
|
+
const st = row.__swpSt;
|
|
66
|
+
st.aw = bw(row); st.acts = { start: actsOf(row, 'start'), end: actsOf(row, 'end') };
|
|
67
|
+
return st;
|
|
68
|
+
};
|
|
69
|
+
const sideOf = (x) => (x > 0 ? 'start' : x < 0 ? 'end' : null);
|
|
70
|
+
const widthOf = (st, side) => (side ? st.acts[side].length * st.aw : 0);
|
|
71
|
+
|
|
72
|
+
/** Draw a row pulled x px (right = positive): the content moves, the buttons fan out behind it. */
|
|
73
|
+
const paint = (st, x) => {
|
|
74
|
+
st.x = x;
|
|
75
|
+
const side = sideOf(x);
|
|
76
|
+
st.main.style.transform = x ? `translate3d(${x}px,0,0)` : '';
|
|
77
|
+
st.row.classList.toggle('is-start', side === 'start'); st.row.classList.toggle('is-end', side === 'end');
|
|
78
|
+
if (!side) return;
|
|
79
|
+
const acts = st.acts[side], n = acts.length, X = Math.abs(x), dir = side === 'start' ? 1 : -1, aw = st.aw;
|
|
80
|
+
acts.forEach((b, i) => {
|
|
81
|
+
const pos = (X * i) / n;
|
|
82
|
+
let w = Math.max(aw, X / n);
|
|
83
|
+
if (i === 0) w += (X - w) * st.grow; // a long swipe: the edge button covers it all
|
|
84
|
+
const p = clamp((X - pos) / Math.min(w, aw), 0, 1); // how much of this button shows
|
|
85
|
+
const fade = i === 0 ? 1 : 1 - st.grow;
|
|
86
|
+
b.style.transform = `translate3d(${dir * pos}px,0,0)`; b.style.width = `${w}px`;
|
|
87
|
+
b.style.zIndex = i === 0 && st.grow > 0 ? n + 1 : i + 1;
|
|
88
|
+
const shift = (w - aw) * (i === 0 ? 0.5 + 0.5 * st.grow : 0.5); // centred; rides to the content edge on a long swipe
|
|
89
|
+
const inner = b.firstChild;
|
|
90
|
+
inner.style.transform = `translate3d(${dir * shift}px,0,0) scale(${0.55 + 0.45 * p})`;
|
|
91
|
+
inner.style.opacity = String(p * fade);
|
|
92
|
+
});
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const tabbable = (st, side) => ['start', 'end'].forEach((s) => st.acts[s].forEach((b) => { b.tabIndex = s === side ? 0 : -1; }));
|
|
96
|
+
|
|
97
|
+
/** Glide a row to x (0 = shut). */
|
|
98
|
+
const settle = (st, x, { ease = 'power3.out', duration = 0.42, done } = {}) => {
|
|
99
|
+
st.tw?.kill();
|
|
100
|
+
const wasOpen = st.open, side = sideOf(x);
|
|
101
|
+
st.open = side; tabbable(st, side);
|
|
102
|
+
st.row.classList.toggle('is-open', !!side);
|
|
103
|
+
if (side) { st.row.classList.toggle('is-start', side === 'start'); st.row.classList.toggle('is-end', side === 'end'); } // buttons can take focus straight away
|
|
104
|
+
if (side && side !== wasOpen) o.onOpen?.(st.row, side, api);
|
|
105
|
+
if (!side && wasOpen) o.onClose?.(st.row, api);
|
|
106
|
+
if (RM()) { paint(st, x); done?.(); return null; }
|
|
107
|
+
const p = { x: st.x };
|
|
108
|
+
st.tw = g.to(p, { x, duration, ease, onUpdate: () => paint(st, p.x), onComplete: () => { st.tw = null; done?.(); } });
|
|
109
|
+
return st.tw;
|
|
110
|
+
};
|
|
111
|
+
const setGrow = (st, v) => {
|
|
112
|
+
st.gw?.kill();
|
|
113
|
+
if (RM()) { st.grow = v; paint(st, st.x); return; }
|
|
114
|
+
const p = { v: st.grow };
|
|
115
|
+
st.gw = g.to(p, { v, duration: v ? 0.26 : 0.2, ease: v ? 'back.out(1.6)' : 'power2.out', onUpdate: () => { st.grow = p.v; paint(st, st.x); } });
|
|
116
|
+
};
|
|
117
|
+
const arm = (st, on, touch) => {
|
|
118
|
+
if (st.armed === on) return;
|
|
119
|
+
st.armed = on; setGrow(st, on ? 1 : 0);
|
|
120
|
+
const edge = st.acts[sideOf(st.x)]?.[0];
|
|
121
|
+
edge?.classList.toggle('is-armed', on);
|
|
122
|
+
if (on && touch && o.haptic) navigator.vibrate?.(8);
|
|
123
|
+
if (on && edge && !RM()) g.fromTo(edge.querySelector('svg'), { scale: 1 }, { keyframes: { scale: [1, 1.3, 1] }, duration: 0.32, ease: 'power2.out', clearProps: 'transform' });
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const close = (st, opt) => { if (st.armed) arm(st, false); return settle(st, 0, opt); };
|
|
127
|
+
const closeOthers = (keep) => list.querySelectorAll('.swp.is-open').forEach((r) => { if (r !== keep) close(stOf(r)); });
|
|
128
|
+
|
|
129
|
+
/** Run an action button of a row. */
|
|
130
|
+
const run = (st, btn) => {
|
|
131
|
+
const row = st.row, side = st.acts.start.includes(btn) ? 'start' : 'end', dir = side === 'start' ? 1 : -1;
|
|
132
|
+
const remove = btn.hasAttribute('data-remove');
|
|
133
|
+
const parent = row.parentNode; let next = row.nextSibling, h = 0;
|
|
134
|
+
const ctx = {
|
|
135
|
+
row, id: row.dataset.id, action: btn.dataset.act,
|
|
136
|
+
/** Put a removed row back where it was. */
|
|
137
|
+
undo: () => {
|
|
138
|
+
if (!remove || row.isConnected) return false;
|
|
139
|
+
parent.insertBefore(row, next && next.parentNode === parent ? next : null);
|
|
140
|
+
const s = stOf(row); s.grow = 1; s.armed = false; btn.classList.remove('is-armed');
|
|
141
|
+
if (RM()) { s.grow = 0; paint(s, 0); row.style.height = ''; return true; }
|
|
142
|
+
paint(s, dir * row.offsetWidth);
|
|
143
|
+
const p = { x: s.x, grow: 1 };
|
|
144
|
+
g.timeline()
|
|
145
|
+
.fromTo(row, { height: 0 }, { height: h, duration: 0.3, ease: 'power2.out', clearProps: 'height' })
|
|
146
|
+
.to(p, { x: 0, grow: 0, duration: 0.5, ease: 'back.out(1.2)', onUpdate: () => { s.grow = p.grow; paint(s, p.x); } }, 0.12);
|
|
147
|
+
return true;
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
if (o.onAction?.(ctx.action, ctx, api) === false || !remove) { close(st); return; }
|
|
151
|
+
// slide it off, then close the gap
|
|
152
|
+
next = row.nextSibling; h = row.offsetHeight; st.open = null; row.classList.remove('is-open');
|
|
153
|
+
const gone = () => { row.remove(); row.style.height = ''; };
|
|
154
|
+
if (RM()) { gone(); return; }
|
|
155
|
+
const out = dir * row.offsetWidth;
|
|
156
|
+
if (st.grow < 1) setGrow(st, 1);
|
|
157
|
+
const p = { x: st.x };
|
|
158
|
+
st.tw?.kill();
|
|
159
|
+
st.tw = g.timeline()
|
|
160
|
+
.to(p, { x: out, duration: Math.abs(out - st.x) > 40 ? 0.24 : 0.01, ease: 'power2.in', onUpdate: () => paint(st, p.x) })
|
|
161
|
+
.to(row, { height: 0, duration: 0.3, ease: 'power2.inOut', onComplete: gone }, '+=0.04');
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
/* ---------- dragging ---------- */
|
|
165
|
+
let drag = null, eat = false;
|
|
166
|
+
/** Finger travel → how far the row moves: a side with no buttons barely gives, past the buttons it gets stiff. */
|
|
167
|
+
const shape = (st, raw) => {
|
|
168
|
+
const side = sideOf(raw); if (!side) return 0;
|
|
169
|
+
const n = st.acts[side].length, X = Math.abs(raw), R = st.row.offsetWidth;
|
|
170
|
+
if (!n) return Math.sign(raw) * Math.min(24, X * 0.18);
|
|
171
|
+
const W = n * st.aw;
|
|
172
|
+
const y = o.full ? X : X <= W ? X : W + (X - W) * 0.3;
|
|
173
|
+
return Math.sign(raw) * Math.min(y, R);
|
|
174
|
+
};
|
|
175
|
+
const armAt = (st, side) => Math.max(widthOf(st, side) + st.aw * 0.6, st.row.offsetWidth * o.fullAt);
|
|
176
|
+
|
|
177
|
+
const ac = new AbortController(), on = { signal: ac.signal };
|
|
178
|
+
list.addEventListener('pointerdown', (e) => {
|
|
179
|
+
if (e.button > 0) return;
|
|
180
|
+
const main = e.target.closest('.swp__main'); if (!main || !list.contains(main)) return;
|
|
181
|
+
const row = main.parentElement, st = stOf(row);
|
|
182
|
+
if (o.single) closeOthers(row);
|
|
183
|
+
drag = { st, x0: e.clientX, y0: e.clientY, base: st.x, pid: e.pointerId, live: false, touch: e.pointerType !== 'mouse', hist: [] };
|
|
184
|
+
}, on);
|
|
185
|
+
addEventListener('pointermove', (e) => {
|
|
186
|
+
const d = drag; if (!d || e.pointerId !== d.pid) return;
|
|
187
|
+
const dx = e.clientX - d.x0, dy = e.clientY - d.y0;
|
|
188
|
+
if (!d.live) {
|
|
189
|
+
if (Math.abs(dy) > 8 && Math.abs(dy) > Math.abs(dx)) { drag = null; return; } // scrolling the list
|
|
190
|
+
if (Math.abs(dx) < 6) return;
|
|
191
|
+
d.live = true; eat = true;
|
|
192
|
+
d.st.tw?.kill(); d.st.row.classList.add('is-swiping');
|
|
193
|
+
try { d.st.main.setPointerCapture(d.pid); } catch { /* fine */ }
|
|
194
|
+
}
|
|
195
|
+
const st = d.st, x = shape(st, d.base + dx), side = sideOf(x);
|
|
196
|
+
if (side !== sideOf(st.x) && st.armed) arm(st, false);
|
|
197
|
+
paint(st, x);
|
|
198
|
+
const canFull = o.full && side && st.acts[side].length;
|
|
199
|
+
arm(st, !!(canFull && Math.abs(x) >= armAt(st, side)), d.touch);
|
|
200
|
+
d.hist.push([e.timeStamp, e.clientX]); if (d.hist.length > 5) d.hist.shift();
|
|
201
|
+
}, on);
|
|
202
|
+
const release = (cancel) => (e) => {
|
|
203
|
+
const d = drag; if (!d || e.pointerId !== d.pid) return;
|
|
204
|
+
drag = null;
|
|
205
|
+
if (!d.live) return;
|
|
206
|
+
const st = d.st; st.row.classList.remove('is-swiping');
|
|
207
|
+
setTimeout(() => { eat = false; }, 0);
|
|
208
|
+
const side = sideOf(st.x);
|
|
209
|
+
if (!side) { close(st); return; }
|
|
210
|
+
if (st.armed && !cancel) { run(st, st.acts[side][0]); return; }
|
|
211
|
+
const [t0, x0] = d.hist[0] || [0, 0], [t1, x1] = d.hist[d.hist.length - 1] || [0, 0];
|
|
212
|
+
const v = t1 > t0 ? (x1 - x0) / (t1 - t0) : 0; // px per ms, + = rightward
|
|
213
|
+
const W = widthOf(st, side), X = Math.abs(st.x);
|
|
214
|
+
const keep = W > 0 && (Math.abs(v) > 0.45 && !cancel ? Math.sign(v) === Math.sign(st.x) : X > W / 2);
|
|
215
|
+
if (st.armed) arm(st, false);
|
|
216
|
+
if (keep) { if (o.single) closeOthers(st.row); settle(st, Math.sign(st.x) * W, { ease: 'back.out(1.3)', duration: 0.45 }); }
|
|
217
|
+
else close(st);
|
|
218
|
+
};
|
|
219
|
+
addEventListener('pointerup', release(false), on);
|
|
220
|
+
addEventListener('pointercancel', release(true), on);
|
|
221
|
+
|
|
222
|
+
list.addEventListener('click', (e) => {
|
|
223
|
+
const main = e.target.closest('.swp__main');
|
|
224
|
+
if (main && (eat || main.parentElement.classList.contains('is-open'))) {
|
|
225
|
+
// the click that ends a swipe, or a tap on an open row (which shuts it), does nothing else
|
|
226
|
+
e.preventDefault(); e.stopPropagation();
|
|
227
|
+
if (!eat) close(stOf(main.parentElement));
|
|
228
|
+
eat = false; return;
|
|
229
|
+
}
|
|
230
|
+
const btn = e.target.closest('.swp__act');
|
|
231
|
+
if (btn && list.contains(btn)) run(stOf(btn.closest('.swp')), btn);
|
|
232
|
+
}, { capture: true, signal: ac.signal });
|
|
233
|
+
|
|
234
|
+
list.addEventListener('keydown', (e) => {
|
|
235
|
+
const row = e.target.closest('.swp'); if (!row || !list.contains(row)) return;
|
|
236
|
+
const st = stOf(row), onMain = e.target.classList.contains('swp__main');
|
|
237
|
+
if (e.key === 'Escape' && st.open) { e.preventDefault(); close(st); st.main.focus(); return; }
|
|
238
|
+
if (!onMain || (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight')) return;
|
|
239
|
+
const side = e.key === 'ArrowLeft' ? 'end' : 'start'; // pulling left shows the end buttons
|
|
240
|
+
e.preventDefault();
|
|
241
|
+
if (st.open && st.open !== side) { close(st); return; }
|
|
242
|
+
if (!st.acts[side].length) return;
|
|
243
|
+
api.open(row, side);
|
|
244
|
+
st.acts[side][st.acts[side].length - 1].focus({ preventScroll: true }); // the one nearest the content
|
|
245
|
+
}, on);
|
|
246
|
+
list.addEventListener('focusout', (e) => {
|
|
247
|
+
const row = e.target.closest?.('.swp'); if (!row || row.contains(e.relatedTarget)) return;
|
|
248
|
+
if (row.classList.contains('is-open')) close(stOf(row));
|
|
249
|
+
}, on);
|
|
250
|
+
document.addEventListener('pointerdown', (e) => { if (!list.contains(e.target)) closeOthers(null); }, on);
|
|
251
|
+
|
|
252
|
+
const api = {
|
|
253
|
+
el: list, opts: o,
|
|
254
|
+
get openRow() { return list.querySelector('.swp.is-open'); },
|
|
255
|
+
/** Open a row on one side ('end' = pulled left, the usual one). */
|
|
256
|
+
open(r, side = 'end') {
|
|
257
|
+
const row = rowOf(r); if (!row) return api;
|
|
258
|
+
const st = stOf(row); if (!st.acts[side].length) return api;
|
|
259
|
+
if (o.single) closeOthers(row);
|
|
260
|
+
settle(st, (side === 'start' ? 1 : -1) * widthOf(st, side), { ease: 'back.out(1.3)', duration: 0.45 });
|
|
261
|
+
return api;
|
|
262
|
+
},
|
|
263
|
+
/** Shut one row, or every open row. */
|
|
264
|
+
close(r) { if (r) { const row = rowOf(r); if (row) close(stOf(row)); } else closeOthers(null); return api; },
|
|
265
|
+
/** A short nudge that shows the row can be swiped (good the first time someone sees the list). */
|
|
266
|
+
peek(r, side = 'end') {
|
|
267
|
+
const row = rowOf(r) || list.querySelector('.swp'); if (!row || RM()) return api;
|
|
268
|
+
const st = stOf(row); if (!st.acts[side].length || st.open) return api;
|
|
269
|
+
const p = { x: 0 }, to = (side === 'start' ? 1 : -1) * Math.min(widthOf(st, side), st.aw * 0.9);
|
|
270
|
+
st.tw?.kill();
|
|
271
|
+
st.tw = g.timeline({ onComplete: () => { st.tw = null; } })
|
|
272
|
+
.to(p, { x: to, duration: 0.35, ease: 'power2.out', onUpdate: () => paint(st, p.x) })
|
|
273
|
+
.to(p, { x: 0, duration: 0.55, ease: 'back.out(1.8)', onUpdate: () => paint(st, p.x) }, '+=0.25');
|
|
274
|
+
return api;
|
|
275
|
+
},
|
|
276
|
+
destroy() { ac.abort(); list.querySelectorAll('.swp').forEach((r) => { r.__swpSt?.tw?.kill(); delete r.__swpSt; }); delete list.__swp; },
|
|
277
|
+
};
|
|
278
|
+
list.__swp = api;
|
|
279
|
+
return api;
|
|
280
|
+
};
|
package/src/tagsinput.js
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
/* Tags input: type words (emails, topics, skills) and each one becomes a tag in the field. A comma or
|
|
2
|
+
Enter makes a tag; pasting "a, b, c" makes three. Backspace in an empty field first marks the last
|
|
3
|
+
tag, a second Backspace removes it; ← → walk along the tags. An optional list of suggestions under
|
|
4
|
+
the field narrows as you type (↑ ↓ Enter to pick).
|
|
5
|
+
How it moves: a new tag pops out of the caret (or out of the suggestion you picked) into its place
|
|
6
|
+
while the text box slides over; a removed tag shrinks away and the others slide up to close the gap.
|
|
7
|
+
Adding one that is already there makes that tag shake and glow; text that fails `validate` shakes
|
|
8
|
+
the field and shows why; at `max` the counter pulses. With reduced motion the tags just appear and
|
|
9
|
+
go, and the messages still show. */
|
|
10
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
11
|
+
import { icon } from '@gecko-ui-kit/icons';
|
|
12
|
+
import { esc } from '../index.js';
|
|
13
|
+
|
|
14
|
+
const { g, RM, $$ } = M;
|
|
15
|
+
const WORDS = {
|
|
16
|
+
label: 'Tags',
|
|
17
|
+
placeholder: 'Add a tag…',
|
|
18
|
+
hint: 'Press Enter or a comma to add. Backspace removes the last one.',
|
|
19
|
+
remove: (t) => `Remove ${t}`,
|
|
20
|
+
added: (t) => `${t} added`,
|
|
21
|
+
removed: (t) => `${t} removed`,
|
|
22
|
+
duplicate: (t) => `${t} is already added`,
|
|
23
|
+
invalid: (t) => `“${t}” can’t be added`,
|
|
24
|
+
max: (n) => `You can add up to ${n}`,
|
|
25
|
+
count: (n, max) => `${n} of ${max}`,
|
|
26
|
+
suggestions: 'Suggestions',
|
|
27
|
+
};
|
|
28
|
+
const KEYS = { Enter: 1, Tab: 1 }; // separators that are keys, not characters
|
|
29
|
+
let seq = 0;
|
|
30
|
+
let ctx = null; // a canvas to measure text (where the caret is)
|
|
31
|
+
|
|
32
|
+
/** Lower case without accents, for comparing and matching. */
|
|
33
|
+
const fold = (s) => String(s ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
|
|
34
|
+
const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\-]/g, '\\$&');
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* const ti = tagsInput(el, {
|
|
38
|
+
* value: ['design'],
|
|
39
|
+
* placeholder: 'Add a tag…',
|
|
40
|
+
* suggestions: ['design', 'mobile', …], // a short list under the field, narrowed as you type
|
|
41
|
+
* max: 0, // most tags (0 = no limit); a counter shows n/max
|
|
42
|
+
* unique: true, // no repeats (ignores upper/lower case and accents)
|
|
43
|
+
* separators: [',', 'Enter'], // characters or the keys 'Enter' / 'Tab'
|
|
44
|
+
* validate: (text) => true | 'message', // false shows words.invalid
|
|
45
|
+
* transform: (text) => text, // e.g. (t) => t.toLowerCase(); runs before the checks
|
|
46
|
+
* name: 'tags', // a hidden input with the tags joined by commas
|
|
47
|
+
* disabled: false,
|
|
48
|
+
* words: { label, placeholder, hint, remove, added, removed, duplicate, invalid, max, count, suggestions },
|
|
49
|
+
* onChange(tags, ti),
|
|
50
|
+
* })
|
|
51
|
+
* ti.value · ti.add(text) → true/false · ti.remove(text | index) · ti.clear() · ti.focus() · ti.destroy()
|
|
52
|
+
*/
|
|
53
|
+
export const tagsInput = (el, opts = {}) => {
|
|
54
|
+
el = $$(el)[0];
|
|
55
|
+
if (!el) return null;
|
|
56
|
+
const o = { value: [], placeholder: null, suggestions: [], max: 0, unique: true, separators: [',', 'Enter'], validate: null, transform: null, name: '', disabled: false, onChange: null, ...opts };
|
|
57
|
+
const W = { ...WORDS, ...o.words };
|
|
58
|
+
if (o.placeholder != null) W.placeholder = o.placeholder;
|
|
59
|
+
const id = `ti${++seq}`;
|
|
60
|
+
const seps = (o.separators || []).map(String);
|
|
61
|
+
const chars = seps.filter((s) => !KEYS[s]);
|
|
62
|
+
const split = new RegExp(`[${[...chars, '\n', '\r'].map(reEsc).join('')}]`);
|
|
63
|
+
const J = '\n'; // joins pieces before they are split again
|
|
64
|
+
const glue = [' ', '; ', ' / '].find((x) => !chars.includes(x.trim() || x)) || ' '; // puts refused pieces back in the box
|
|
65
|
+
const sugg = (o.suggestions || []).map(String);
|
|
66
|
+
let tags = [], armed = -1, active = -1, rows = [], open = false;
|
|
67
|
+
const timers = new Set();
|
|
68
|
+
const later = (fn, ms) => { const t = setTimeout(() => { timers.delete(t); fn(); }, ms); timers.add(t); };
|
|
69
|
+
|
|
70
|
+
el.innerHTML = `<div class="ti${o.disabled ? ' is-disabled' : ''}">`
|
|
71
|
+
+ `<div class="ti__box"><div class="ti__field"><div class="ti__tags" role="list" aria-label="${esc(W.label)}"></div>`
|
|
72
|
+
+ `<input class="ti__input" type="text" aria-label="${esc(W.label)}" aria-describedby="${id}-h ${id}-m" autocomplete="off" autocapitalize="off" spellcheck="false"`
|
|
73
|
+
+ (sugg.length ? ` role="combobox" aria-autocomplete="list" aria-expanded="false" aria-controls="${id}-s"` : '')
|
|
74
|
+
+ `${o.disabled ? ' disabled' : ''}>`
|
|
75
|
+
+ `${o.max ? '<span class="ti__count" aria-hidden="true"></span>' : ''}</div>`
|
|
76
|
+
+ (sugg.length ? `<div class="ti__sug" id="${id}-s" role="listbox" aria-label="${esc(W.suggestions)}" hidden></div>` : '') + '</div>'
|
|
77
|
+
+ `<p class="ti__msg" id="${id}-m" aria-live="polite"></p>`
|
|
78
|
+
+ `<span class="ti__sr" id="${id}-h">${esc(W.hint)}</span><span class="ti__sr" role="status"></span>`
|
|
79
|
+
+ (o.name ? `<input type="hidden" name="${esc(o.name)}">` : '')
|
|
80
|
+
+ '</div>';
|
|
81
|
+
const root = el.firstElementChild, field = root.querySelector('.ti__field'), list = root.querySelector('.ti__tags');
|
|
82
|
+
const input = root.querySelector('.ti__input'), count = root.querySelector('.ti__count'), msg = root.querySelector('.ti__msg');
|
|
83
|
+
const sug = root.querySelector('.ti__sug'), hidden = root.querySelector('input[type="hidden"]');
|
|
84
|
+
const say = (t) => { root.querySelector('[role="status"]').textContent = t; };
|
|
85
|
+
const tagEls = () => [...list.querySelectorAll('.ti__tag:not(.is-gone)')];
|
|
86
|
+
const full = () => !!o.max && tags.length >= o.max;
|
|
87
|
+
const indexOf = (t) => { const f = fold(t); return tags.findIndex((x) => fold(x) === f); };
|
|
88
|
+
|
|
89
|
+
/* ---------- pieces ---------- */
|
|
90
|
+
const tagHTML = (t) => `<span class="ti__tag" role="listitem" tabindex="-1"><span class="ti__text">${esc(t)}</span>`
|
|
91
|
+
+ `<button type="button" class="ti__x" tabindex="-1" aria-label="${esc(W.remove(t))}"${o.disabled ? ' disabled' : ''}>${icon('close')}</button></span>`;
|
|
92
|
+
const make = (t) => { const x = document.createElement('template'); x.innerHTML = tagHTML(t); return x.content.firstElementChild; };
|
|
93
|
+
|
|
94
|
+
/** Change the tags in the field, then slide every tag (and the text box) from where it was. */
|
|
95
|
+
const flip = (mutate, skip) => {
|
|
96
|
+
const els = [...tagEls(), input];
|
|
97
|
+
const before = new Map(els.map((x) => [x, x.getBoundingClientRect()]));
|
|
98
|
+
mutate();
|
|
99
|
+
if (RM()) return;
|
|
100
|
+
before.forEach((r, x) => {
|
|
101
|
+
if (x === skip || !x.isConnected) return;
|
|
102
|
+
const n = x.getBoundingClientRect(), dx = r.left - n.left, dy = r.top - n.top;
|
|
103
|
+
if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) g.fromTo(x, { x: dx, y: dy }, { x: 0, y: 0, duration: 0.32, ease: 'power3.out', overwrite: 'auto', clearProps: 'transform' });
|
|
104
|
+
});
|
|
105
|
+
};
|
|
106
|
+
/** Where the caret is on screen (the end of the typed text). */
|
|
107
|
+
const caretAt = (text) => {
|
|
108
|
+
const r = input.getBoundingClientRect(), s = getComputedStyle(input);
|
|
109
|
+
ctx ||= document.createElement('canvas').getContext('2d');
|
|
110
|
+
let w = 0;
|
|
111
|
+
if (ctx) { ctx.font = `${s.fontWeight} ${s.fontSize} ${s.fontFamily}`; w = ctx.measureText(text).width; }
|
|
112
|
+
return { x: r.left + (parseFloat(s.paddingLeft) || 0) + Math.min(w, r.width), y: r.top + r.height / 2 };
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const sync = () => {
|
|
116
|
+
root.classList.toggle('has-value', tags.length > 0);
|
|
117
|
+
root.classList.toggle('is-full', full());
|
|
118
|
+
input.placeholder = full() ? '' : tags.length ? '' : W.placeholder;
|
|
119
|
+
if (count) count.textContent = `${tags.length}/${o.max}`;
|
|
120
|
+
if (hidden) hidden.value = tags.join(',');
|
|
121
|
+
};
|
|
122
|
+
const emit = () => { sync(); o.onChange?.([...tags], api); };
|
|
123
|
+
const note = (text, bad = false) => { msg.textContent = text || ''; root.classList.toggle('is-bad', !!text && bad); root.classList.toggle('has-msg', !!text); };
|
|
124
|
+
const disarm = () => { if (armed < 0) return; tagEls()[armed]?.classList.remove('is-armed'); armed = -1; };
|
|
125
|
+
|
|
126
|
+
/* ---------- feedback ---------- */
|
|
127
|
+
const pulse = () => {
|
|
128
|
+
note(W.max(o.max)); // the message line is aria-live
|
|
129
|
+
if (!count) return;
|
|
130
|
+
count.classList.remove('is-pulse'); void count.offsetWidth; count.classList.add('is-pulse');
|
|
131
|
+
later(() => count.classList.remove('is-pulse'), 700);
|
|
132
|
+
if (!RM()) g.fromTo(count, { scale: 1.45 }, { scale: 1, duration: 0.6, ease: 'elastic.out(1, 0.4)', overwrite: true, clearProps: 'transform' });
|
|
133
|
+
};
|
|
134
|
+
const dup = (i, t) => {
|
|
135
|
+
const x = tagEls()[i]; note(W.duplicate(t));
|
|
136
|
+
if (!x) return;
|
|
137
|
+
x.classList.remove('is-dup'); void x.offsetWidth; x.classList.add('is-dup');
|
|
138
|
+
later(() => x.classList.remove('is-dup'), 900);
|
|
139
|
+
if (!RM()) g.fromTo(x, { x: 0 }, { keyframes: { x: [0, -5, 5, -3, 2, 0] }, duration: 0.42, ease: 'power2.out', clearProps: 'transform' });
|
|
140
|
+
};
|
|
141
|
+
const bad = (t, why) => {
|
|
142
|
+
const text = typeof why === 'string' && why ? why : W.invalid(t);
|
|
143
|
+
note(text, true);
|
|
144
|
+
M.shake(field);
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
/* ---------- adding and removing ---------- */
|
|
148
|
+
/** Try one text. from: a point or element the new tag pops out of. Returns true when added. */
|
|
149
|
+
const add = (raw, { from = null, quiet = false } = {}) => {
|
|
150
|
+
let t = String(raw ?? '').trim();
|
|
151
|
+
if (o.transform) t = String(o.transform(t) ?? '').trim();
|
|
152
|
+
if (!t) return false;
|
|
153
|
+
if (o.unique) { const i = indexOf(t); if (i >= 0) { dup(i, t); return false; } }
|
|
154
|
+
if (full()) { pulse(); return false; }
|
|
155
|
+
if (o.validate) { const ok = o.validate(t); if (ok !== true) { bad(t, ok); return false; } }
|
|
156
|
+
disarm(); tags.push(t);
|
|
157
|
+
const tag = make(t);
|
|
158
|
+
const at = from instanceof Element ? from.getBoundingClientRect() : from;
|
|
159
|
+
flip(() => list.appendChild(tag), tag);
|
|
160
|
+
if (!RM()) {
|
|
161
|
+
const r = tag.getBoundingClientRect();
|
|
162
|
+
const fx = at ? (at.x ?? at.left) + (at.width || 0) / 2 : r.left + r.width / 2;
|
|
163
|
+
const fy = at ? (at.y ?? at.top) + (at.height || 0) / 2 : r.top + r.height / 2;
|
|
164
|
+
g.fromTo(tag, { x: fx - (r.left + r.width / 2), y: fy - (r.top + r.height / 2), scale: 0.35, opacity: 0 },
|
|
165
|
+
{ x: 0, y: 0, scale: 1, opacity: 1, duration: 0.42, ease: 'back.out(1.9)', clearProps: 'transform,opacity' });
|
|
166
|
+
}
|
|
167
|
+
if (!quiet) { say(W.added(t)); note(''); }
|
|
168
|
+
if (full() && count && !RM()) g.fromTo(count, { scale: 1.3 }, { scale: 1, duration: 0.5, ease: 'back.out(3)', clearProps: 'transform' }); // just filled up
|
|
169
|
+
return true;
|
|
170
|
+
};
|
|
171
|
+
/** Add every piece of a text; the ones that could not be added go back into the box. */
|
|
172
|
+
const addMany = (text, from) => {
|
|
173
|
+
const g0 = glue.trim(); // a lone glue mark (" / ") left from an earlier refusal is not a piece
|
|
174
|
+
const edge = g0 ? new RegExp(`^(?:${reEsc(g0)})+|(?:${reEsc(g0)})+$`, 'g') : null;
|
|
175
|
+
const parts = String(text).split(split).map((x) => (edge ? x.trim().replace(edge, '') : x).trim()).filter(Boolean);
|
|
176
|
+
const left = [], done = [];
|
|
177
|
+
parts.forEach((p) => { if (add(p, { from, quiet: parts.length > 1 })) done.push(p); else left.push(p); });
|
|
178
|
+
if (parts.length > 1 && done.length) { say(W.added(done.join(', '))); if (!left.length) note(''); }
|
|
179
|
+
if (done.length) emit();
|
|
180
|
+
return left;
|
|
181
|
+
};
|
|
182
|
+
const remove = (i, { focus = false } = {}) => {
|
|
183
|
+
if (i < 0 || i >= tags.length) return false;
|
|
184
|
+
const els = tagEls(), x = els[i], [t] = tags.splice(i, 1);
|
|
185
|
+
if (armed === i) armed = -1; else if (armed > i) armed--;
|
|
186
|
+
if (focus) (els[i - 1] || els[i + 1] || input).focus({ preventScroll: true });
|
|
187
|
+
if (x) {
|
|
188
|
+
x.classList.add('is-gone');
|
|
189
|
+
if (RM()) x.remove();
|
|
190
|
+
else g.to(x, { scale: 0.4, opacity: 0, duration: 0.18, ease: 'power2.in', overwrite: true, onComplete: () => flip(() => x.remove()) });
|
|
191
|
+
}
|
|
192
|
+
say(W.removed(t)); note('');
|
|
193
|
+
emit(); if (open) render();
|
|
194
|
+
return true;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
/* ---------- suggestions ---------- */
|
|
198
|
+
const mark = (s, q) => {
|
|
199
|
+
const i = q ? fold(s).indexOf(fold(q)) : -1;
|
|
200
|
+
return i < 0 || fold(s).length !== s.length ? esc(s) : `${esc(s.slice(0, i))}<mark>${esc(s.slice(i, i + q.length))}</mark>${esc(s.slice(i + q.length))}`;
|
|
201
|
+
};
|
|
202
|
+
const render = () => {
|
|
203
|
+
if (!sug) return;
|
|
204
|
+
const q = input.value.trim(), f = fold(q);
|
|
205
|
+
const pool = sugg.filter((s) => !(o.unique && indexOf(o.transform ? String(o.transform(s)) : s) >= 0));
|
|
206
|
+
const starts = pool.filter((s) => f && fold(s).startsWith(f)), has = pool.filter((s) => f && !fold(s).startsWith(f) && fold(s).includes(f));
|
|
207
|
+
rows = (f ? [...starts, ...has] : pool).slice(0, 6);
|
|
208
|
+
sug.innerHTML = rows.map((s, i) => `<div class="ti__opt" role="option" id="${id}-o${i}" data-i="${i}" aria-selected="false">${icon('plus')}<span>${mark(s, q)}</span></div>`).join('');
|
|
209
|
+
if (active >= rows.length) active = rows.length - 1;
|
|
210
|
+
highlight();
|
|
211
|
+
if (!rows.length) close();
|
|
212
|
+
};
|
|
213
|
+
const highlight = () => {
|
|
214
|
+
sug.querySelectorAll('.ti__opt').forEach((r, i) => { r.classList.toggle('is-active', i === active); r.setAttribute('aria-selected', String(i === active)); });
|
|
215
|
+
const row = active >= 0 ? sug.querySelector(`[data-i="${active}"]`) : null;
|
|
216
|
+
if (row) { input.setAttribute('aria-activedescendant', row.id); row.scrollIntoView?.({ block: 'nearest' }); }
|
|
217
|
+
else input.removeAttribute('aria-activedescendant');
|
|
218
|
+
};
|
|
219
|
+
const show = (all = false) => {
|
|
220
|
+
if (!sug || o.disabled || (!all && !input.value.trim())) { close(); return; }
|
|
221
|
+
active = -1; render();
|
|
222
|
+
if (!rows.length || open) return;
|
|
223
|
+
open = true; sug.hidden = false; input.setAttribute('aria-expanded', 'true');
|
|
224
|
+
if (!RM()) g.fromTo(sug, { opacity: 0, y: -4 }, { opacity: 1, y: 0, duration: 0.18, ease: 'power2.out', overwrite: true, clearProps: 'transform,opacity' });
|
|
225
|
+
};
|
|
226
|
+
function close() {
|
|
227
|
+
if (!sug || !open) return;
|
|
228
|
+
open = false; active = -1; input.setAttribute('aria-expanded', 'false'); input.removeAttribute('aria-activedescendant');
|
|
229
|
+
g.killTweensOf(sug); sug.hidden = true;
|
|
230
|
+
}
|
|
231
|
+
const pick = (i) => {
|
|
232
|
+
const s = rows[i]; if (s == null) return;
|
|
233
|
+
const row = sug.querySelector(`[data-i="${i}"] span`);
|
|
234
|
+
if (add(s, { from: row })) { input.value = ''; emit(); }
|
|
235
|
+
close();
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
/* ---------- events ---------- */
|
|
239
|
+
const ac = new AbortController();
|
|
240
|
+
const on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
|
|
241
|
+
const commit = (from) => {
|
|
242
|
+
const text = input.value;
|
|
243
|
+
if (!text.trim()) return false;
|
|
244
|
+
const left = addMany(text, from ?? caretAt(text));
|
|
245
|
+
input.value = left.join(glue);
|
|
246
|
+
close();
|
|
247
|
+
return true;
|
|
248
|
+
};
|
|
249
|
+
on(field, 'pointerdown', (e) => {
|
|
250
|
+
if (o.disabled) return;
|
|
251
|
+
const x = e.target.closest('.ti__x');
|
|
252
|
+
if (x) { e.preventDefault(); remove(tagEls().indexOf(x.closest('.ti__tag'))); input.focus({ preventScroll: true }); return; }
|
|
253
|
+
if (e.target.closest('.ti__tag') || e.target === input) return;
|
|
254
|
+
e.preventDefault(); input.focus();
|
|
255
|
+
});
|
|
256
|
+
on(field, 'click', (e) => { // the × from the keyboard or a screen reader (no pointerdown)
|
|
257
|
+
const x = e.target.closest('.ti__x');
|
|
258
|
+
if (!x || o.disabled || e.detail) return;
|
|
259
|
+
remove(tagEls().indexOf(x.closest('.ti__tag')), { focus: true });
|
|
260
|
+
});
|
|
261
|
+
on(input, 'input', () => {
|
|
262
|
+
disarm();
|
|
263
|
+
if (msg.textContent) note('');
|
|
264
|
+
if (chars.length && split.test(input.value)) { // a separator was typed (or dropped in)
|
|
265
|
+
const parts = input.value.split(split), rest = parts.pop();
|
|
266
|
+
const left = addMany(parts.join(J), caretAt(input.value));
|
|
267
|
+
input.value = [...left, rest.trim()].filter(Boolean).join(glue);
|
|
268
|
+
}
|
|
269
|
+
show();
|
|
270
|
+
});
|
|
271
|
+
on(input, 'paste', (e) => {
|
|
272
|
+
const text = e.clipboardData?.getData('text') ?? '';
|
|
273
|
+
if (!/[\n\r\t]/.test(text) && !(chars.length && split.test(text))) return; // one plain word: let it in
|
|
274
|
+
e.preventDefault();
|
|
275
|
+
const left = addMany(`${input.value}${J}${text.replace(/\t/g, J)}`, caretAt(input.value));
|
|
276
|
+
input.value = left.join(glue);
|
|
277
|
+
close();
|
|
278
|
+
});
|
|
279
|
+
on(input, 'keydown', (e) => {
|
|
280
|
+
if (e.key !== 'Backspace') disarm();
|
|
281
|
+
if (e.isComposing) return;
|
|
282
|
+
switch (e.key) {
|
|
283
|
+
case 'ArrowDown': if (sug) { e.preventDefault(); if (!open) show(true); if (rows.length) { active = (active + 1) % rows.length; highlight(); } } break;
|
|
284
|
+
case 'ArrowUp': if (open) { e.preventDefault(); active = active <= 0 ? rows.length - 1 : active - 1; highlight(); } break;
|
|
285
|
+
case 'Escape':
|
|
286
|
+
if (open) { e.preventDefault(); e.stopPropagation(); close(); }
|
|
287
|
+
else if (msg.textContent) note('');
|
|
288
|
+
break;
|
|
289
|
+
case 'Enter':
|
|
290
|
+
if (open && active >= 0) { e.preventDefault(); pick(active); }
|
|
291
|
+
else if (seps.includes('Enter') && input.value.trim()) { e.preventDefault(); commit(); }
|
|
292
|
+
break;
|
|
293
|
+
case 'Tab':
|
|
294
|
+
if (seps.includes('Tab') && input.value.trim() && !e.shiftKey) { e.preventDefault(); if (open && active >= 0) pick(active); else commit(); }
|
|
295
|
+
else close();
|
|
296
|
+
break;
|
|
297
|
+
case 'Backspace': {
|
|
298
|
+
if (input.value || !tags.length) break;
|
|
299
|
+
const last = tags.length - 1;
|
|
300
|
+
if (armed === last) { e.preventDefault(); remove(last); }
|
|
301
|
+
else { e.preventDefault(); armed = last; const x = tagEls()[last]; x?.classList.add('is-armed'); }
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
case 'ArrowLeft':
|
|
305
|
+
if (input.selectionStart === 0 && input.selectionEnd === 0 && tags.length) { e.preventDefault(); close(); tagEls().at(-1)?.focus(); }
|
|
306
|
+
break;
|
|
307
|
+
default:
|
|
308
|
+
if (chars.includes(e.key) && !input.value.trim()) e.preventDefault(); // a comma on its own adds nothing
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
on(list, 'keydown', (e) => {
|
|
312
|
+
const x = e.target.closest?.('.ti__tag'); if (!x || o.disabled) return;
|
|
313
|
+
const all = tagEls(), i = all.indexOf(x);
|
|
314
|
+
if (e.key === 'ArrowLeft') { e.preventDefault(); (all[i - 1] || x).focus(); }
|
|
315
|
+
else if (e.key === 'ArrowRight') { e.preventDefault(); (all[i + 1] || input).focus(); }
|
|
316
|
+
else if (e.key === 'Home') { e.preventDefault(); all[0]?.focus(); }
|
|
317
|
+
else if (e.key === 'End') { e.preventDefault(); input.focus(); }
|
|
318
|
+
else if (e.key === 'Backspace' || e.key === 'Delete') { e.preventDefault(); remove(i, { focus: true }); }
|
|
319
|
+
else if (e.key === 'Escape') { e.preventDefault(); input.focus(); }
|
|
320
|
+
else if (e.key.length === 1 && !e.ctrlKey && !e.metaKey) input.focus(); // typing goes to the box
|
|
321
|
+
});
|
|
322
|
+
on(input, 'focus', () => { if (input.value.trim()) show(); });
|
|
323
|
+
if (sug) {
|
|
324
|
+
on(sug, 'pointerdown', (e) => e.preventDefault()); // keep the focus in the box
|
|
325
|
+
on(sug, 'click', (e) => { const r = e.target.closest('.ti__opt'); if (r) pick(+r.dataset.i); });
|
|
326
|
+
on(sug, 'pointermove', (e) => { const r = e.target.closest('.ti__opt'); if (r && +r.dataset.i !== active) { active = +r.dataset.i; highlight(); } });
|
|
327
|
+
}
|
|
328
|
+
on(root, 'focusout', (e) => {
|
|
329
|
+
if (root.contains(e.relatedTarget)) return;
|
|
330
|
+
disarm(); close();
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
const api = {
|
|
334
|
+
el: root, opts: o,
|
|
335
|
+
get value() { return [...tags]; },
|
|
336
|
+
/** Add a tag (it goes through transform, unique, max and validate). Returns true when added. */
|
|
337
|
+
add(text) { const ok = add(text); if (ok) emit(); return ok; },
|
|
338
|
+
/** Remove a tag by its text or its index. */
|
|
339
|
+
remove(x) { return remove(typeof x === 'number' ? x : indexOf(String(x))); },
|
|
340
|
+
clear() {
|
|
341
|
+
if (!tags.length) return api;
|
|
342
|
+
const els = tagEls();
|
|
343
|
+
tags = []; armed = -1;
|
|
344
|
+
els.forEach((x, k) => {
|
|
345
|
+
x.classList.add('is-gone');
|
|
346
|
+
if (RM()) x.remove();
|
|
347
|
+
else g.to(x, { scale: 0.4, opacity: 0, duration: 0.18, delay: (els.length - 1 - k) * 0.03, ease: 'power2.in', onComplete: () => x.remove() });
|
|
348
|
+
});
|
|
349
|
+
note(''); say(W.removed(els.map((x) => x.textContent).join(', ')));
|
|
350
|
+
emit(); if (open) render();
|
|
351
|
+
return api;
|
|
352
|
+
},
|
|
353
|
+
focus() { input.focus(); return api; },
|
|
354
|
+
destroy() {
|
|
355
|
+
ac.abort(); timers.forEach(clearTimeout); timers.clear();
|
|
356
|
+
g.killTweensOf([field, count, sug, input, ...list.children].filter(Boolean));
|
|
357
|
+
el.innerHTML = '';
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
// the first tags, without animation and without onChange
|
|
362
|
+
(o.value || []).forEach((t) => {
|
|
363
|
+
let x = String(t).trim(); if (o.transform) x = String(o.transform(x) ?? '').trim();
|
|
364
|
+
if (!x || (o.unique && indexOf(x) >= 0) || full()) return;
|
|
365
|
+
tags.push(x); list.appendChild(make(x));
|
|
366
|
+
});
|
|
367
|
+
sync();
|
|
368
|
+
return api;
|
|
369
|
+
};
|