@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
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/* Range slider with two thumbs: pick a low and a high value on one track (a price filter, opening
|
|
2
|
+
hours). Drag a thumb, press the track to send the nearest thumb there, or drag the filled middle to
|
|
3
|
+
move both at once. The thumbs never cross and keep `minGap` apart; when they sit on top of each
|
|
4
|
+
other, the way you drag decides which one moves.
|
|
5
|
+
How it moves: a grabbed thumb grows with a spring and a bubble with the value pops up above it;
|
|
6
|
+
pressing the track or calling set() glides the thumbs over; bars of an optional histogram behind
|
|
7
|
+
the track light up as they come inside the range and fade as they leave it, and grow up from the
|
|
8
|
+
track when it first shows. With reduced motion everything jumps straight to its place. */
|
|
9
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
10
|
+
import { esc } from '../index.js';
|
|
11
|
+
|
|
12
|
+
const { g, RM, $$ } = M;
|
|
13
|
+
const WORDS = { min: 'Minimum', max: 'Maximum', to: 'to', range: (a, b) => `${a} – ${b}` };
|
|
14
|
+
let seq = 0;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* const rs = rangeSlider(el, {
|
|
18
|
+
* min: 0, max: 100, step: 1,
|
|
19
|
+
* value: [20, 80], // [low, high]; default: the whole range
|
|
20
|
+
* minGap: 0, // the least the two may be apart
|
|
21
|
+
* format: (v) => string, // bubble, aria-valuetext, marks, inputs (default: grouped digits)
|
|
22
|
+
* parse: (text) => number, // reads the number inputs (default: the digits in the text)
|
|
23
|
+
* marks: [0, 50, 100] | 25, // ticks + labels under the track (a number: every n)
|
|
24
|
+
* histogram: [3, 8, 12, …], // bars behind the track, spread evenly from min to max;
|
|
25
|
+
* // a bar whose middle is inside the range lights up
|
|
26
|
+
* inputs: false, // two number boxes under the track (commit on blur / Enter)
|
|
27
|
+
* name: 'price', // two hidden inputs: price_min and price_max
|
|
28
|
+
* label: 'Price', // a heading with the range written out next to it
|
|
29
|
+
* disabled: false,
|
|
30
|
+
* words: { min, max, to, range },
|
|
31
|
+
* onInput(value, rs), // every change while dragging
|
|
32
|
+
* onChange(value, rs), // when a drag ends, a key is pressed, a box is committed
|
|
33
|
+
* })
|
|
34
|
+
* rs.value → [low, high] · rs.set([low, high], { silent }) · rs.destroy()
|
|
35
|
+
*/
|
|
36
|
+
export const rangeSlider = (el, opts = {}) => {
|
|
37
|
+
el = $$(el)[0];
|
|
38
|
+
if (!el) return null;
|
|
39
|
+
const o = { min: 0, max: 100, step: 1, value: null, minGap: 0, format: null, parse: null, marks: null, histogram: null, inputs: false, name: '', label: '', disabled: false, onInput: null, onChange: null, ...opts };
|
|
40
|
+
const W = { ...WORDS, ...o.words };
|
|
41
|
+
const id = `rs${++seq}`;
|
|
42
|
+
const min = +o.min, max = Math.max(+o.max, min + 1e-9), span = max - min, step = Math.abs(+o.step) || 1;
|
|
43
|
+
const gap = Math.max(0, +o.minGap || 0);
|
|
44
|
+
const dec = (String(step).split('.')[1] || '').length;
|
|
45
|
+
const nf = new Intl.NumberFormat(undefined, { minimumFractionDigits: dec, maximumFractionDigits: dec });
|
|
46
|
+
const fmt = (v) => (o.format ? String(o.format(v)) : nf.format(v));
|
|
47
|
+
const parse = (t) => (o.parse ? +o.parse(t) : parseFloat(String(t).replace(/[^\d.-]/g, '')));
|
|
48
|
+
const snap = (v) => +(min + Math.round((v - min) / step) * step).toFixed(dec);
|
|
49
|
+
const clamp = (v, a = min, b = max) => Math.min(b, Math.max(a, v));
|
|
50
|
+
const pct = (v) => ((v - min) / span) * 100;
|
|
51
|
+
|
|
52
|
+
/* ---------- the first value ---------- */
|
|
53
|
+
const start = Array.isArray(o.value) ? o.value : [min, max];
|
|
54
|
+
let lo = clamp(snap(+start[0])), hi = clamp(snap(+start[1]));
|
|
55
|
+
if (!Number.isFinite(lo)) lo = min;
|
|
56
|
+
if (!Number.isFinite(hi)) hi = max;
|
|
57
|
+
if (lo > hi) [lo, hi] = [hi, lo];
|
|
58
|
+
if (hi - lo < gap) { hi = Math.min(max, lo + gap); lo = Math.max(min, hi - gap); }
|
|
59
|
+
let val = [lo, hi];
|
|
60
|
+
|
|
61
|
+
/* ---------- markup ---------- */
|
|
62
|
+
const hist = Array.isArray(o.histogram) && o.histogram.length ? o.histogram.map((n) => Math.max(0, +n || 0)) : null;
|
|
63
|
+
const top = hist ? Math.max(...hist) || 1 : 1;
|
|
64
|
+
const marks = (typeof o.marks === 'number' && o.marks > 0
|
|
65
|
+
? Array.from({ length: Math.floor(span / o.marks + 1e-9) + 1 }, (_, i) => min + i * o.marks)
|
|
66
|
+
: Array.isArray(o.marks) ? o.marks.map(Number) : []).filter((v) => Number.isFinite(v) && v >= min && v <= max);
|
|
67
|
+
const thumb = (i) => `<div class="rs__thumb" data-i="${i}" role="slider" tabindex="${o.disabled ? -1 : 0}" aria-label="${esc(i ? W.max : W.min)}" aria-orientation="horizontal"${o.disabled ? ' aria-disabled="true"' : ''}><span class="rs__knob"></span><span class="rs__bubble" aria-hidden="true"></span></div>`;
|
|
68
|
+
const box = (i) => `<label class="rs__in"><small>${esc(i ? W.max : W.min)}</small><input class="input input--sm rs__num" data-i="${i}" type="text" inputmode="decimal" autocomplete="off"${o.disabled ? ' disabled' : ''}></label>`;
|
|
69
|
+
el.innerHTML = `<div class="rs${hist ? ' has-hist' : ''}${marks.length ? ' has-marks' : ''}${o.disabled ? ' is-disabled' : ''}${RM() ? ' is-still' : ''}" role="group"${o.label ? ` aria-labelledby="${id}-l"` : ''}>`
|
|
70
|
+
+ (o.label ? `<div class="rs__head"><span class="rs__label" id="${id}-l">${esc(o.label)}</span><output class="rs__out" aria-hidden="true"></output></div>` : '')
|
|
71
|
+
+ '<div class="rs__body">'
|
|
72
|
+
+ (hist ? `<div class="rs__hist" aria-hidden="true">${hist.map((n) => `<i class="rs__bar" style="height:${Math.max(4, (n / top) * 100)}%"></i>`).join('')}</div>` : '')
|
|
73
|
+
+ `<div class="rs__rail"><div class="rs__track"><div class="rs__fill"></div></div>${thumb(0)}${thumb(1)}</div>`
|
|
74
|
+
+ (marks.length ? `<div class="rs__marks" aria-hidden="true">${marks.map((v) => `<button type="button" class="rs__mark${v === min ? ' is-start' : v === max ? ' is-end' : ''}" tabindex="-1" data-v="${v}" style="left:${pct(v)}%"${o.disabled ? ' disabled' : ''}><i></i><small>${esc(fmt(v))}</small></button>`).join('')}</div>` : '')
|
|
75
|
+
+ '</div>'
|
|
76
|
+
+ (o.inputs ? `<div class="rs__inputs">${box(0)}<span class="rs__to">${esc(W.to)}</span>${box(1)}</div>` : '')
|
|
77
|
+
+ (o.name ? `<input type="hidden" name="${esc(o.name)}_min"><input type="hidden" name="${esc(o.name)}_max">` : '')
|
|
78
|
+
+ '</div>';
|
|
79
|
+
const root = el.firstElementChild, rail = root.querySelector('.rs__rail');
|
|
80
|
+
const thumbs = [...root.querySelectorAll('.rs__thumb')], knobs = thumbs.map((t) => t.querySelector('.rs__knob')), bubbles = thumbs.map((t) => t.querySelector('.rs__bubble'));
|
|
81
|
+
const nums = [...root.querySelectorAll('.rs__num')], bars = [...root.querySelectorAll('.rs__bar')], markEls = [...root.querySelectorAll('.rs__mark')];
|
|
82
|
+
const hidden = [...root.querySelectorAll('input[type="hidden"]')], out = root.querySelector('.rs__out');
|
|
83
|
+
|
|
84
|
+
/* ---------- drawing ---------- */
|
|
85
|
+
const pos = { a: pct(lo), b: pct(hi) }; // what is on screen (tweened), in %
|
|
86
|
+
const place = () => {
|
|
87
|
+
const w = rail.clientWidth, near = ((pos.b - pos.a) / 100) * w < (bubbles[0].offsetWidth + bubbles[1].offsetWidth) / 2 + 6;
|
|
88
|
+
root.style.setProperty('--a', `${pos.a}%`); root.style.setProperty('--b', `${pos.b}%`);
|
|
89
|
+
root.classList.toggle('is-near', near);
|
|
90
|
+
};
|
|
91
|
+
const glide = (animate) => {
|
|
92
|
+
g.killTweensOf(pos);
|
|
93
|
+
const a = pct(val[0]), b = pct(val[1]);
|
|
94
|
+
if (!animate || RM()) { pos.a = a; pos.b = b; place(); return; }
|
|
95
|
+
g.to(pos, { a, b, duration: 0.34, ease: 'power3.out', onUpdate: place });
|
|
96
|
+
};
|
|
97
|
+
const paint = (animate = false) => {
|
|
98
|
+
const [a, b] = val;
|
|
99
|
+
thumbs.forEach((t, i) => {
|
|
100
|
+
const v = val[i];
|
|
101
|
+
t.setAttribute('aria-valuemin', String(i ? Math.min(max, a + gap) : min));
|
|
102
|
+
t.setAttribute('aria-valuemax', String(i ? max : Math.max(min, b - gap)));
|
|
103
|
+
t.setAttribute('aria-valuenow', String(v));
|
|
104
|
+
t.setAttribute('aria-valuetext', fmt(v));
|
|
105
|
+
bubbles[i].textContent = fmt(v);
|
|
106
|
+
});
|
|
107
|
+
if (out) out.textContent = W.range(fmt(a), fmt(b));
|
|
108
|
+
nums.forEach((n, i) => { if (document.activeElement !== n) n.value = fmt(val[i]); });
|
|
109
|
+
if (hidden.length) { hidden[0].value = String(a); hidden[1].value = String(b); }
|
|
110
|
+
const w = span / (bars.length || 1);
|
|
111
|
+
bars.forEach((x, k) => { const mid = min + (k + 0.5) * w; x.classList.toggle('is-in', mid >= a && mid <= b); });
|
|
112
|
+
markEls.forEach((m) => { const v = +m.dataset.v; m.classList.toggle('is-in', v >= a && v <= b); });
|
|
113
|
+
glide(animate);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/* ---------- changing the value ---------- */
|
|
117
|
+
const same = (x, y) => x[0] === y[0] && x[1] === y[1];
|
|
118
|
+
/** Where thumb i may go: inside the track and minGap away from the other one. */
|
|
119
|
+
const fit = (i, v) => (i ? clamp(snap(v), Math.min(max, val[0] + gap), max) : clamp(snap(v), min, Math.max(min, val[1] - gap)));
|
|
120
|
+
/** Set a new pair; returns true when it changed. input: call onInput. */
|
|
121
|
+
const put = (next, { animate = false, silent = false } = {}) => {
|
|
122
|
+
if (same(next, val)) return false;
|
|
123
|
+
val = next; paint(animate);
|
|
124
|
+
if (!silent) o.onInput?.([...val], api);
|
|
125
|
+
return true;
|
|
126
|
+
};
|
|
127
|
+
const changed = () => o.onChange?.([...val], api);
|
|
128
|
+
const moveThumb = (i, v, how) => { const next = [...val]; next[i] = fit(i, v); return put(next, how); };
|
|
129
|
+
const valueAt = (x) => { const r = rail.getBoundingClientRect(); return min + clamp((x - r.left) / (r.width || 1), 0, 1) * span; };
|
|
130
|
+
const nearest = (v) => (v <= val[0] ? 0 : v >= val[1] ? 1 : v - val[0] <= val[1] - v ? 0 : 1);
|
|
131
|
+
const front = (i) => thumbs.forEach((t, k) => t.classList.toggle('is-top', k === i));
|
|
132
|
+
|
|
133
|
+
/* ---------- grab motion ---------- */
|
|
134
|
+
const grab = (i, on) => {
|
|
135
|
+
thumbs[i].classList.toggle('is-drag', on);
|
|
136
|
+
if (RM()) return;
|
|
137
|
+
g.to(knobs[i], on ? { scale: 1.32, duration: 0.55, ease: 'elastic.out(1, 0.45)', overwrite: true } : { scale: 1, duration: 0.35, ease: 'back.out(2.2)', overwrite: true, clearProps: 'transform' });
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/* ---------- pointer ---------- */
|
|
141
|
+
const ac = new AbortController();
|
|
142
|
+
const on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
|
|
143
|
+
let drag = null; // { mode: 'thumb' | 'middle' | 'pick', i, x0, v0, from, id }
|
|
144
|
+
const begin = (i) => { drag.mode = 'thumb'; drag.i = i; front(i); grab(i, true); thumbs[i].focus({ preventScroll: true }); };
|
|
145
|
+
on(rail, 'pointerdown', (e) => {
|
|
146
|
+
if (o.disabled || e.button > 0 || drag) return;
|
|
147
|
+
e.preventDefault();
|
|
148
|
+
const v = valueAt(e.clientX), t = e.target.closest('.rs__thumb');
|
|
149
|
+
drag = { mode: '', i: -1, x0: e.clientX, v0: v, from: [...val], id: e.pointerId };
|
|
150
|
+
try { rail.setPointerCapture(e.pointerId); } catch { /* fine */ }
|
|
151
|
+
if (t) {
|
|
152
|
+
const w = rail.clientWidth, overlap = ((pos.b - pos.a) / 100) * w < knobs[0].offsetWidth;
|
|
153
|
+
if (overlap) { drag.mode = 'pick'; thumbs[+t.dataset.i].focus({ preventScroll: true }); thumbs.forEach((x, k) => grab(k, true)); return; } // the drag direction decides
|
|
154
|
+
begin(+t.dataset.i);
|
|
155
|
+
} else if (v > val[0] && v < val[1]) {
|
|
156
|
+
drag.mode = 'middle'; // drag both, or a click moves the nearest
|
|
157
|
+
} else {
|
|
158
|
+
const i = nearest(v);
|
|
159
|
+
begin(i); moveThumb(i, v, { animate: true });
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
on(rail, 'pointermove', (e) => {
|
|
163
|
+
if (!drag || e.pointerId !== drag.id) return;
|
|
164
|
+
const dx = e.clientX - drag.x0;
|
|
165
|
+
if (drag.mode === 'pick') {
|
|
166
|
+
if (Math.abs(dx) < 2) return;
|
|
167
|
+
const i = dx < 0 ? 0 : 1;
|
|
168
|
+
thumbs.forEach((x, k) => { if (k !== i) grab(k, false); });
|
|
169
|
+
drag.mode = 'thumb'; drag.i = i; front(i); thumbs[i].focus({ preventScroll: true });
|
|
170
|
+
}
|
|
171
|
+
if (drag.mode === 'middle') {
|
|
172
|
+
if (Math.abs(dx) < 3 && !drag.moved) return;
|
|
173
|
+
if (!drag.moved) { drag.moved = true; root.classList.add('is-grab'); grab(0, true); grab(1, true); }
|
|
174
|
+
const width = drag.from[1] - drag.from[0];
|
|
175
|
+
const a = clamp(snap(drag.from[0] + valueAt(e.clientX) - drag.v0), min, max - width);
|
|
176
|
+
put([a, +(a + width).toFixed(dec)]);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (drag.mode === 'thumb') moveThumb(drag.i, valueAt(e.clientX));
|
|
180
|
+
});
|
|
181
|
+
const end = (e) => {
|
|
182
|
+
if (!drag || (e.pointerId != null && e.pointerId !== drag.id)) return;
|
|
183
|
+
const d = drag; drag = null;
|
|
184
|
+
root.classList.remove('is-grab');
|
|
185
|
+
if (d.mode === 'middle' && !d.moved) { // a click inside the range: the nearest thumb glides there
|
|
186
|
+
const i = Math.abs(d.v0 - val[0]) <= Math.abs(d.v0 - val[1]) ? 0 : 1;
|
|
187
|
+
front(i); thumbs[i].focus({ preventScroll: true }); moveThumb(i, d.v0, { animate: true });
|
|
188
|
+
}
|
|
189
|
+
thumbs.forEach((x, k) => { if (x.classList.contains('is-drag')) grab(k, false); });
|
|
190
|
+
if (!same(d.from, val)) changed();
|
|
191
|
+
};
|
|
192
|
+
on(rail, 'pointerup', end);
|
|
193
|
+
on(rail, 'pointercancel', end);
|
|
194
|
+
on(rail, 'lostpointercapture', end);
|
|
195
|
+
|
|
196
|
+
/* ---------- keyboard ---------- */
|
|
197
|
+
thumbs.forEach((t, i) => {
|
|
198
|
+
on(t, 'keydown', (e) => {
|
|
199
|
+
if (o.disabled) return;
|
|
200
|
+
const k = e.key, big = step * 10;
|
|
201
|
+
let v = null;
|
|
202
|
+
if (k === 'ArrowRight' || k === 'ArrowUp') v = val[i] + step;
|
|
203
|
+
else if (k === 'ArrowLeft' || k === 'ArrowDown') v = val[i] - step;
|
|
204
|
+
else if (k === 'PageUp') v = val[i] + big;
|
|
205
|
+
else if (k === 'PageDown') v = val[i] - big;
|
|
206
|
+
else if (k === 'Home') v = min;
|
|
207
|
+
else if (k === 'End') v = max;
|
|
208
|
+
if (v === null) return;
|
|
209
|
+
e.preventDefault(); front(i);
|
|
210
|
+
if (moveThumb(i, v, { animate: true })) changed();
|
|
211
|
+
});
|
|
212
|
+
on(t, 'focus', () => front(i));
|
|
213
|
+
});
|
|
214
|
+
markEls.forEach((m) => on(m, 'click', () => {
|
|
215
|
+
if (o.disabled) return;
|
|
216
|
+
const v = +m.dataset.v, i = v <= val[0] ? 0 : v >= val[1] ? 1 : nearest(v);
|
|
217
|
+
front(i); if (moveThumb(i, v, { animate: true })) changed();
|
|
218
|
+
}));
|
|
219
|
+
|
|
220
|
+
/* ---------- number boxes ---------- */
|
|
221
|
+
nums.forEach((n, i) => {
|
|
222
|
+
/** Read the box; raw: leave the plain number in it (still typing) rather than the formatted one. */
|
|
223
|
+
const commit = (raw) => {
|
|
224
|
+
const v = parse(n.value);
|
|
225
|
+
if (!Number.isFinite(v)) { n.value = raw ? String(val[i]) : fmt(val[i]); M.shake(n.closest('.rs__in')); return; }
|
|
226
|
+
if (moveThumb(i, v, { animate: true })) changed();
|
|
227
|
+
n.value = raw ? String(val[i]) : fmt(val[i]);
|
|
228
|
+
if (snap(clamp(v)) !== val[i]) M.flash(n); // it was pulled inside the limits
|
|
229
|
+
};
|
|
230
|
+
on(n, 'focus', () => { n.value = String(val[i]); n.select(); });
|
|
231
|
+
on(n, 'blur', () => commit(false));
|
|
232
|
+
on(n, 'keydown', (e) => {
|
|
233
|
+
if (e.key === 'Enter') { e.preventDefault(); commit(true); n.select(); }
|
|
234
|
+
else if (e.key === 'Escape') { e.preventDefault(); n.value = String(val[i]); n.select(); }
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
let ro = null;
|
|
239
|
+
if (typeof ResizeObserver !== 'undefined') { ro = new ResizeObserver(() => place()); ro.observe(rail); }
|
|
240
|
+
|
|
241
|
+
const api = {
|
|
242
|
+
el: root, opts: o,
|
|
243
|
+
get value() { return [...val]; },
|
|
244
|
+
/** Go to [low, high] (snapped, kept in the limits and minGap apart); the thumbs glide there. */
|
|
245
|
+
set(next = [], { silent = false } = {}) {
|
|
246
|
+
let [a, b] = [+next[0], +next[1]];
|
|
247
|
+
if (!Number.isFinite(a)) a = val[0];
|
|
248
|
+
if (!Number.isFinite(b)) b = val[1];
|
|
249
|
+
a = clamp(snap(a)); b = clamp(snap(b));
|
|
250
|
+
if (a > b) [a, b] = [b, a];
|
|
251
|
+
if (b - a < gap) { b = Math.min(max, a + gap); a = Math.max(min, b - gap); }
|
|
252
|
+
if (put([a, b], { animate: true, silent }) && !silent) changed();
|
|
253
|
+
return api;
|
|
254
|
+
},
|
|
255
|
+
destroy() {
|
|
256
|
+
ac.abort(); ro?.disconnect();
|
|
257
|
+
g.killTweensOf([pos, ...knobs, ...bars]);
|
|
258
|
+
el.innerHTML = '';
|
|
259
|
+
},
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
paint(false);
|
|
263
|
+
front(1);
|
|
264
|
+
if (bars.length && !RM()) g.from(bars, { scaleY: 0, transformOrigin: '50% 100%', duration: 0.6, ease: 'power3.out', stagger: { each: 0.018, from: 'start' }, clearProps: 'transform' });
|
|
265
|
+
return api;
|
|
266
|
+
};
|
package/src/rating.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/* Rating: stars (or hearts) to pick a score, or to show one. Moving over them fills a preview;
|
|
2
|
+
picking pops the filled stars one after another and throws a few sparks from the last one.
|
|
3
|
+
Drag along them on a phone. Half steps if you like, and click the same score again to clear.
|
|
4
|
+
Read-only shows any number, so 4.3 fills the fifth star by a third. */
|
|
5
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
6
|
+
import { icon } from '@gecko-ui-kit/icons';
|
|
7
|
+
import { esc } from '../index.js';
|
|
8
|
+
|
|
9
|
+
const { g, RM, $$ } = M;
|
|
10
|
+
const WORDS = { label: 'Rating', of: (v, max) => `${v} out of ${max}`, none: 'No rating', cleared: 'Rating cleared' };
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* const r = rating(el, {
|
|
14
|
+
* value: 0, max: 5,
|
|
15
|
+
* half: false, // pick in halves (3.5)
|
|
16
|
+
* readOnly: false, // show a score; any number fills partly (4.3)
|
|
17
|
+
* clearable: true, // picking the same score again clears it
|
|
18
|
+
* icon: 'star' | 'heart' | any icon name,
|
|
19
|
+
* size: '' | 'sm' | 'lg',
|
|
20
|
+
* labels: ['Bad', 'Poor', 'Okay', 'Good', 'Great'], // a word beside the stars
|
|
21
|
+
* showValue: false, // the number beside the stars
|
|
22
|
+
* name: 'score', // a hidden input, so a plain <form> sends it
|
|
23
|
+
* disabled: false,
|
|
24
|
+
* words: { label, of, none, cleared },
|
|
25
|
+
* onChange(value, r)
|
|
26
|
+
* })
|
|
27
|
+
* r.value · r.set(n) · r.setReadOnly(bool) · r.destroy()
|
|
28
|
+
*/
|
|
29
|
+
export const rating = (el, opts = {}) => {
|
|
30
|
+
el = $$(el)[0];
|
|
31
|
+
if (!el) return null;
|
|
32
|
+
const o = { value: 0, max: 5, half: false, readOnly: false, clearable: true, icon: 'star', size: '', labels: null, showValue: false, name: '', disabled: false, onChange: null, ...opts };
|
|
33
|
+
const W = { ...WORDS, ...o.words };
|
|
34
|
+
const ac = new AbortController(), on = (t, ev, fn, x) => t.addEventListener(ev, fn, { signal: ac.signal, ...x });
|
|
35
|
+
const max = Math.max(1, Math.round(+o.max || 5)), step = () => (o.half ? 0.5 : 1);
|
|
36
|
+
const snap = (v) => Math.min(max, Math.max(0, Math.round(v / step()) * step()));
|
|
37
|
+
let value = o.readOnly ? Math.min(max, Math.max(0, +o.value || 0)) : snap(+o.value || 0), shown = -1, ro = !!o.readOnly;
|
|
38
|
+
|
|
39
|
+
const star = `<span class="rt__s">${icon(o.icon)}<span class="rt__f">${icon(o.icon)}</span></span>`;
|
|
40
|
+
el.innerHTML = `<div class="rt rt--${esc(o.icon)}${o.size ? ` rt--${esc(o.size)}` : ''}${o.disabled ? ' is-disabled' : ''}">`
|
|
41
|
+
+ `<span class="rt__stars">${star.repeat(max)}</span>`
|
|
42
|
+
+ `${o.showValue ? '<b class="rt__num"></b>' : ''}${o.labels ? '<span class="rt__word"><span></span></span>' : ''}`
|
|
43
|
+
+ `${o.name ? `<input type="hidden" name="${esc(o.name)}">` : ''}<span class="rt__sr" role="status"></span></div>`;
|
|
44
|
+
const root = el.firstElementChild, row = root.querySelector('.rt__stars'), stars = [...row.children];
|
|
45
|
+
const num = root.querySelector('.rt__num'), word = root.querySelector('.rt__word > span'), hidden = root.querySelector('input[type="hidden"]');
|
|
46
|
+
const say = (t) => { root.querySelector('.rt__sr').textContent = t; };
|
|
47
|
+
const fmt = (v) => (Number.isInteger(v) ? String(v) : v.toFixed(1).replace(/\.0$/, ''));
|
|
48
|
+
const label = (v) => (o.labels && v > 0 ? o.labels[Math.min(o.labels.length, Math.max(1, ro ? Math.round(v) : Math.ceil(v))) - 1] ?? '' : ''); // read-only 4.3 reads as 4
|
|
49
|
+
|
|
50
|
+
/* ---------- drawing ---------- */
|
|
51
|
+
const fills = (v) => stars.map((_, i) => Math.min(1, Math.max(0, v - i)));
|
|
52
|
+
const draw = (v, animate = true, dur = 0.18) => {
|
|
53
|
+
const f = fills(v);
|
|
54
|
+
stars.forEach((s, i) => {
|
|
55
|
+
g.killTweensOf(s, '--f');
|
|
56
|
+
if (!animate || RM()) g.set(s, { '--f': f[i] });
|
|
57
|
+
else g.to(s, { '--f': f[i], duration: dur, ease: 'power2.out' });
|
|
58
|
+
});
|
|
59
|
+
if (num) num.textContent = v > 0 ? fmt(v) : '–';
|
|
60
|
+
if (word) {
|
|
61
|
+
const t = label(v);
|
|
62
|
+
if (word.textContent !== t) {
|
|
63
|
+
const up = v > shown;
|
|
64
|
+
word.textContent = t;
|
|
65
|
+
if (animate && !RM() && t) g.fromTo(word, { y: up ? 6 : -6, opacity: 0 }, { y: 0, opacity: 1, duration: 0.25, ease: 'power2.out', clearProps: 'transform,opacity' });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
root.classList.toggle('is-empty', v <= 0);
|
|
69
|
+
shown = v;
|
|
70
|
+
};
|
|
71
|
+
const aria = () => {
|
|
72
|
+
if (ro) {
|
|
73
|
+
row.setAttribute('role', 'img'); row.removeAttribute('tabindex');
|
|
74
|
+
['aria-valuenow', 'aria-valuemin', 'aria-valuemax', 'aria-valuetext', 'aria-disabled'].forEach((a) => row.removeAttribute(a));
|
|
75
|
+
row.setAttribute('aria-label', `${W.label}: ${value > 0 ? W.of(fmt(value), max) : W.none}`);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
row.setAttribute('role', 'slider'); row.tabIndex = o.disabled ? -1 : 0;
|
|
79
|
+
row.setAttribute('aria-label', W.label);
|
|
80
|
+
row.setAttribute('aria-valuemin', '0'); row.setAttribute('aria-valuemax', String(max)); row.setAttribute('aria-valuenow', String(value));
|
|
81
|
+
row.setAttribute('aria-valuetext', value > 0 ? `${W.of(fmt(value), max)}${label(value) ? ` (${label(value)})` : ''}` : W.none);
|
|
82
|
+
if (o.disabled) row.setAttribute('aria-disabled', 'true'); else row.removeAttribute('aria-disabled');
|
|
83
|
+
};
|
|
84
|
+
const sync = () => { aria(); root.classList.toggle('is-ro', ro); if (hidden) hidden.value = value > 0 ? String(value) : ''; };
|
|
85
|
+
|
|
86
|
+
/** Picked: the filled stars pop one after another, the last throws a few sparks. */
|
|
87
|
+
const celebrate = (v, from) => {
|
|
88
|
+
if (RM()) return;
|
|
89
|
+
const n = Math.ceil(v);
|
|
90
|
+
if (v < from || v <= 0) {
|
|
91
|
+
stars.slice(n).reverse().forEach((s, k) => g.fromTo(s.querySelector('svg'), { scale: 0.86 }, { scale: 1, duration: 0.35, delay: k * 0.03, ease: 'back.out(3)', clearProps: 'transform' }));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
stars.slice(0, n).forEach((s, k) => g.fromTo(s, { scale: 1 }, { keyframes: { scale: [1, k === n - 1 ? 1.32 : 1.16, 1] }, duration: 0.42, delay: k * 0.045, ease: 'power2.out', clearProps: 'transform' }));
|
|
95
|
+
const last = stars[n - 1], burst = document.createElement('span');
|
|
96
|
+
burst.className = 'rt__burst';
|
|
97
|
+
burst.innerHTML = '<i></i>'.repeat(6);
|
|
98
|
+
last.append(burst);
|
|
99
|
+
const d = (n - 1) * 0.045 + 0.08;
|
|
100
|
+
[...burst.children].forEach((p, k) => {
|
|
101
|
+
const a = (k / 6) * Math.PI * 2 - Math.PI / 2, r = 16 + (k % 2) * 6;
|
|
102
|
+
g.fromTo(p, { x: 0, y: 0, scale: 1, opacity: 1 }, { x: Math.cos(a) * r, y: Math.sin(a) * r, scale: 0.2, opacity: 0, duration: 0.55, delay: d, ease: 'power2.out' });
|
|
103
|
+
});
|
|
104
|
+
g.delayedCall(d + 0.6, () => burst.remove());
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const commit = (v, { tell = true, animate = true, toggle = false } = {}) => {
|
|
108
|
+
v = ro ? Math.min(max, Math.max(0, +v || 0)) : snap(v);
|
|
109
|
+
const from = value;
|
|
110
|
+
if (!ro && o.clearable && toggle && v === value && v > 0) v = 0;
|
|
111
|
+
if (v === value) { draw(value, animate); return false; }
|
|
112
|
+
value = v; draw(value, animate, 0.22); sync();
|
|
113
|
+
if (animate) celebrate(value, from);
|
|
114
|
+
if (tell) { say(value > 0 ? W.of(fmt(value), max) : W.cleared); o.onChange?.(value, api); }
|
|
115
|
+
return true;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/* ---------- pointer: hover preview, click or drag to pick ---------- */
|
|
119
|
+
const at = (x) => {
|
|
120
|
+
const r = row.getBoundingClientRect(), w = r.width / max;
|
|
121
|
+
const raw = Math.min(max, Math.max(0, (x - r.left) / w));
|
|
122
|
+
return o.half ? Math.max(0.5, Math.ceil(raw * 2) / 2) : Math.max(1, Math.ceil(raw));
|
|
123
|
+
};
|
|
124
|
+
const live = () => !ro && !o.disabled;
|
|
125
|
+
let drag = null;
|
|
126
|
+
on(row, 'pointermove', (e) => {
|
|
127
|
+
if (!live()) return;
|
|
128
|
+
if (drag && e.pointerId !== drag) return;
|
|
129
|
+
const v = at(e.clientX); if (v !== shown) draw(v);
|
|
130
|
+
root.classList.add('is-hover');
|
|
131
|
+
});
|
|
132
|
+
on(row, 'pointerleave', () => { if (!live() || drag) return; root.classList.remove('is-hover'); draw(value); });
|
|
133
|
+
on(row, 'pointerdown', (e) => {
|
|
134
|
+
if (!live() || e.button > 0) return;
|
|
135
|
+
if (e.pointerType !== 'mouse') { drag = e.pointerId; try { row.setPointerCapture(e.pointerId); } catch {} draw(at(e.clientX)); }
|
|
136
|
+
});
|
|
137
|
+
on(row, 'pointerup', (e) => {
|
|
138
|
+
if (!live()) return;
|
|
139
|
+
const touch = drag !== null; drag = null;
|
|
140
|
+
if (touch) { try { row.releasePointerCapture(e.pointerId); } catch {} root.classList.remove('is-hover'); }
|
|
141
|
+
commit(at(e.clientX), { toggle: true });
|
|
142
|
+
if (!touch) draw(value === 0 ? 0 : value);
|
|
143
|
+
});
|
|
144
|
+
on(row, 'pointercancel', () => { drag = null; root.classList.remove('is-hover'); draw(value); });
|
|
145
|
+
on(row, 'keydown', (e) => {
|
|
146
|
+
if (!live()) return;
|
|
147
|
+
const k = e.key, s = step();
|
|
148
|
+
let v = null;
|
|
149
|
+
if (k === 'ArrowRight' || k === 'ArrowUp') v = Math.min(max, value + s);
|
|
150
|
+
else if (k === 'ArrowLeft' || k === 'ArrowDown') v = Math.max(0, value - s);
|
|
151
|
+
else if (k === 'Home') v = 0;
|
|
152
|
+
else if (k === 'End') v = max;
|
|
153
|
+
else if (k === 'Delete' || k === 'Backspace' || k === '0') v = 0;
|
|
154
|
+
else if (/^[1-9]$/.test(k) && +k <= max) v = +k;
|
|
155
|
+
if (v == null) return;
|
|
156
|
+
e.preventDefault();
|
|
157
|
+
if (v !== value) { const from = value; value = v; draw(value, true, 0.2); sync(); celebrate(value, from); o.onChange?.(value, api); }
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
draw(value, false); sync();
|
|
161
|
+
if (o.disabled) row.setAttribute('aria-disabled', 'true');
|
|
162
|
+
|
|
163
|
+
const api = {
|
|
164
|
+
root,
|
|
165
|
+
get value() { return value; },
|
|
166
|
+
set: (v, { silent = false } = {}) => commit(+v || 0, { tell: !silent && !ro, animate: true }),
|
|
167
|
+
setReadOnly(b) { ro = !!b; root.classList.remove('is-hover'); draw(value, false); sync(); },
|
|
168
|
+
destroy() { ac.abort(); g.killTweensOf(root.querySelectorAll('*')); stars.forEach((s) => g.killTweensOf(s)); el.innerHTML = ''; },
|
|
169
|
+
};
|
|
170
|
+
return api;
|
|
171
|
+
};
|
package/src/signature.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/* Signature pad: sign with a finger, a pen or the mouse. The line gets thinner when you move fast
|
|
2
|
+
and thicker when you slow down (or press harder with a pen), like ink. The "Sign here" hint fades
|
|
3
|
+
out with the first stroke. Undo lifts the last stroke off, Clear dissolves the whole signature,
|
|
4
|
+
and replay() draws it again stroke by stroke at the speed it was signed. Export it as a PNG
|
|
5
|
+
(trimmed, any background) or an SVG, or save the strokes as JSON and load them back. */
|
|
6
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
7
|
+
import { icon } from '@gecko-ui-kit/icons';
|
|
8
|
+
import { esc } from '../index.js';
|
|
9
|
+
|
|
10
|
+
const { g, RM, $$ } = M;
|
|
11
|
+
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
|
12
|
+
const WORDS = { label: 'Signature', hint: 'Sign here', undo: 'Undo last stroke', clear: 'Clear signature', signed: 'Signed', empty: 'Not signed yet', cleared: 'Signature cleared' };
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* const sig = signaturePad(el, {
|
|
16
|
+
* color: 'currentColor' (follows the text colour, so it works in dark mode) | '#1f3a93',
|
|
17
|
+
* width: [1.2, 3.6], // thinnest and thickest line in px
|
|
18
|
+
* pressure: true, // fast = thin, slow or pressed hard = thick (false: one even width)
|
|
19
|
+
* guide: true, // the line and × to sign on
|
|
20
|
+
* tools: true, // undo and clear buttons in the corner
|
|
21
|
+
* readOnly: false, // show a signature that can't be changed
|
|
22
|
+
* words: { label, hint, undo, clear, … },
|
|
23
|
+
* onChange(isEmpty, sig), onEnd(sig) // after every change / after each stroke
|
|
24
|
+
* })
|
|
25
|
+
* sig.isEmpty · sig.undo() · sig.clear() · sig.replay() · sig.toJSON() · sig.fromJSON(data, { animate })
|
|
26
|
+
* sig.toImage({ type: 'image/png', background: '#fff', color: '#14161c', trim: true, scale: 2 }) → data URL
|
|
27
|
+
* sig.toSVG({ color }) → '<svg …>' · sig.destroy()
|
|
28
|
+
* Shape: --sig-ratio (3 / 1) on the pad or a parent.
|
|
29
|
+
*/
|
|
30
|
+
export const signaturePad = (el, opts = {}) => {
|
|
31
|
+
el = $$(el)[0];
|
|
32
|
+
if (!el) return null;
|
|
33
|
+
const W = { ...WORDS, ...opts.words };
|
|
34
|
+
const o = { color: 'currentColor', width: [1.2, 3.6], pressure: true, guide: true, tools: true, readOnly: false, ...opts };
|
|
35
|
+
const [wMin, wMax] = o.width;
|
|
36
|
+
|
|
37
|
+
el.innerHTML = `<div class="sig${o.readOnly ? ' is-readonly' : ''}">`
|
|
38
|
+
+ `<canvas class="sig__pad" role="img" aria-label="${esc(W.label)}: ${esc(W.empty)}"></canvas><canvas class="sig__fx" aria-hidden="true"></canvas>`
|
|
39
|
+
+ (o.guide ? `<div class="sig__guide" aria-hidden="true"><span class="sig__x">×</span><i></i><span class="sig__hint">${esc(W.hint)}</span></div>` : '')
|
|
40
|
+
+ (o.tools && !o.readOnly ? `<div class="sig__tools"><button type="button" class="sig__tool" data-t="undo" aria-label="${esc(W.undo)}" title="${esc(W.undo)}" disabled>${icon('refresh')}</button><button type="button" class="sig__tool" data-t="clear" aria-label="${esc(W.clear)}" title="${esc(W.clear)}" disabled>${icon('close')}</button></div>` : '')
|
|
41
|
+
+ '<span class="sig__sr" role="status"></span></div>';
|
|
42
|
+
const root = el.firstElementChild, pad = root.querySelector('.sig__pad'), fx = root.querySelector('.sig__fx');
|
|
43
|
+
const ctx = pad.getContext('2d'), fctx = fx.getContext('2d');
|
|
44
|
+
|
|
45
|
+
/** Strokes are kept as points in a 1000-wide space, so the signature scales with the pad. */
|
|
46
|
+
let strokes = [], cur = null, box = { w: 1, h: 1 }, dpr = 1, replaying = null;
|
|
47
|
+
const k = () => box.w / 1000;
|
|
48
|
+
const ink = () => (o.color === 'currentColor' ? getComputedStyle(root).color : o.color);
|
|
49
|
+
|
|
50
|
+
const size = () => {
|
|
51
|
+
const r = pad.getBoundingClientRect(); if (!r.width) return;
|
|
52
|
+
dpr = Math.min(3, window.devicePixelRatio || 1); box = { w: r.width, h: r.height };
|
|
53
|
+
[pad, fx].forEach((c) => { c.width = Math.round(r.width * dpr); c.height = Math.round(r.height * dpr); c.getContext('2d').setTransform(dpr, 0, 0, dpr, 0, 0); });
|
|
54
|
+
redraw();
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** Draw one stroke (or its first n points) onto a canvas context, in CSS px. */
|
|
58
|
+
const paint = (c, s, scale, color, n = s.pts.length) => {
|
|
59
|
+
const p = s.pts, m = Math.min(n, p.length); if (!m) return;
|
|
60
|
+
c.fillStyle = c.strokeStyle = color; c.lineCap = 'round'; c.lineJoin = 'round';
|
|
61
|
+
if (m === 1) { c.beginPath(); c.arc(p[0].x * scale, p[0].y * scale, (p[0].w * scale) * 0.75, 0, Math.PI * 2); c.fill(); return; } // a dot (a tap), a little bolder than the line
|
|
62
|
+
const mid = (a, b) => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
|
|
63
|
+
for (let i = 1; i < m; i++) { // smooth curves through the midpoints, each with its own width
|
|
64
|
+
const a = p[i - 1], b = p[i], m0 = i > 1 ? mid(p[i - 2], a) : a, m1 = mid(a, b);
|
|
65
|
+
c.beginPath(); c.lineWidth = ((a.w + b.w) / 2) * scale;
|
|
66
|
+
c.moveTo(m0.x * scale, m0.y * scale); c.quadraticCurveTo(a.x * scale, a.y * scale, m1.x * scale, m1.y * scale); c.stroke();
|
|
67
|
+
}
|
|
68
|
+
if (m === p.length) { // the last half-step to the end of the stroke
|
|
69
|
+
const a = p[m - 2], b = p[m - 1], m1 = mid(a, b);
|
|
70
|
+
c.beginPath(); c.lineWidth = b.w * scale; c.moveTo(m1.x * scale, m1.y * scale); c.lineTo(b.x * scale, b.y * scale); c.stroke();
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const redraw = () => { ctx.clearRect(0, 0, box.w, box.h); const color = ink(); strokes.forEach((s) => paint(ctx, s, k(), color)); };
|
|
74
|
+
|
|
75
|
+
const say = (t) => { const s = root.querySelector('.sig__sr'); if (s) s.textContent = t; };
|
|
76
|
+
const changed = () => {
|
|
77
|
+
const empty = !strokes.length;
|
|
78
|
+
root.classList.toggle('is-signed', !empty);
|
|
79
|
+
pad.setAttribute('aria-label', `${W.label}: ${empty ? W.empty : W.signed}`);
|
|
80
|
+
root.querySelectorAll('.sig__tool').forEach((b) => { b.disabled = empty; });
|
|
81
|
+
o.onChange?.(empty, api);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/* ---------- drawing ---------- */
|
|
85
|
+
const at = (e) => { const r = pad.getBoundingClientRect(); return { x: (e.clientX - r.left) / k(), y: (e.clientY - r.top) / k() }; };
|
|
86
|
+
const widthFor = (e, last, pt, t) => {
|
|
87
|
+
if (!o.pressure) return (wMin + wMax) / 2;
|
|
88
|
+
if (e.pointerType === 'pen' && e.pressure > 0) return wMin + (wMax - wMin) * e.pressure;
|
|
89
|
+
if (!last) return (wMin + wMax) / 2;
|
|
90
|
+
const v = Math.hypot(pt.x - last.x, pt.y - last.y) * k() / Math.max(1, t - last.t); // CSS px per ms
|
|
91
|
+
const target = clamp(wMax - v * (wMax - wMin) * 0.9, wMin, wMax);
|
|
92
|
+
const was = last.w * k(); // stored widths are in the 1000-wide space
|
|
93
|
+
return was + (target - was) * 0.35; // ease towards it, no sudden jumps
|
|
94
|
+
};
|
|
95
|
+
const add = (e) => {
|
|
96
|
+
const pt = at(e), last = cur.pts[cur.pts.length - 1], t = e.timeStamp || performance.now();
|
|
97
|
+
if (last && Math.hypot(pt.x - last.x, pt.y - last.y) * k() < 1.2) return;
|
|
98
|
+
const w = widthFor(e, last, pt, t) / k(); // stored in the 1000-wide space
|
|
99
|
+
cur.pts.push({ x: pt.x, y: pt.y, t, w });
|
|
100
|
+
const n = cur.pts.length;
|
|
101
|
+
if (n >= 2) paint(ctx, { pts: cur.pts.slice(Math.max(0, n - 3)) }, k(), ink(), n >= 3 ? 3 : 2); // just the newest piece
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
let pid = null;
|
|
105
|
+
const ac = new AbortController(), on = { signal: ac.signal };
|
|
106
|
+
pad.addEventListener('pointerdown', (e) => {
|
|
107
|
+
if (o.readOnly || replaying || e.button > 0) return;
|
|
108
|
+
e.preventDefault(); pid = e.pointerId; try { pad.setPointerCapture(pid); } catch { /* fine */ }
|
|
109
|
+
cur = { pts: [] }; strokes.push(cur); add(e);
|
|
110
|
+
if (strokes.length === 1) root.classList.add('is-signed');
|
|
111
|
+
}, on);
|
|
112
|
+
pad.addEventListener('pointermove', (e) => {
|
|
113
|
+
if (e.pointerId !== pid || !cur) return;
|
|
114
|
+
const all = e.getCoalescedEvents?.(); // the in-between points the screen sampled (can be empty)
|
|
115
|
+
(all?.length ? all : [e]).forEach(add);
|
|
116
|
+
}, on);
|
|
117
|
+
const finish = (e) => {
|
|
118
|
+
if (e.pointerId !== pid || !cur) return;
|
|
119
|
+
pid = null;
|
|
120
|
+
redraw(); // finishes the stroke's tail (and draws a dot for a tap)
|
|
121
|
+
cur = null; changed(); say(W.signed); o.onEnd?.(api);
|
|
122
|
+
};
|
|
123
|
+
pad.addEventListener('pointerup', finish, on);
|
|
124
|
+
pad.addEventListener('pointercancel', finish, on);
|
|
125
|
+
root.addEventListener('click', (e) => { const t = e.target.closest('.sig__tool'); if (t) (t.dataset.t === 'undo' ? api.undo() : api.clear()); }, on);
|
|
126
|
+
|
|
127
|
+
const ro = new ResizeObserver(() => size());
|
|
128
|
+
ro.observe(pad);
|
|
129
|
+
// the ink follows the text colour: draw again when the theme changes
|
|
130
|
+
const mo = o.color === 'currentColor' ? new MutationObserver(() => requestAnimationFrame(redraw)) : null;
|
|
131
|
+
mo?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class'] });
|
|
132
|
+
|
|
133
|
+
/** Fade something drawn on the effects layer away (used by undo and clear). */
|
|
134
|
+
const lift = (draw, { y = -6, duration = 0.45 } = {}) => {
|
|
135
|
+
fctx.clearRect(0, 0, box.w, box.h); draw(fctx);
|
|
136
|
+
g.killTweensOf(fx);
|
|
137
|
+
g.fromTo(fx, { opacity: 1, y: 0, scaleY: 1 }, { opacity: 0, y, scaleY: 0.97, duration, ease: 'power2.in', transformOrigin: '50% 60%', onComplete: () => { fctx.clearRect(0, 0, box.w, box.h); g.set(fx, { clearProps: 'all' }); } });
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const api = {
|
|
141
|
+
el: root, opts: o,
|
|
142
|
+
get isEmpty() { return !strokes.length; },
|
|
143
|
+
/** Take the last stroke off; it lifts away. */
|
|
144
|
+
undo() {
|
|
145
|
+
if (!strokes.length || replaying) return api;
|
|
146
|
+
const s = strokes.pop(); redraw(); changed(); say(strokes.length ? W.signed : W.empty);
|
|
147
|
+
if (!RM()) lift((c) => paint(c, s, k(), ink()), { y: -4, duration: 0.35 });
|
|
148
|
+
return api;
|
|
149
|
+
},
|
|
150
|
+
/** Clear everything; the signature dissolves upwards. */
|
|
151
|
+
clear() {
|
|
152
|
+
replaying?.kill(); replaying = null;
|
|
153
|
+
if (!strokes.length) return api;
|
|
154
|
+
const old = strokes; strokes = []; redraw(); changed(); say(W.cleared);
|
|
155
|
+
if (!RM()) lift((c) => old.forEach((s) => paint(c, s, k(), ink())), { y: -10, duration: 0.5 });
|
|
156
|
+
return api;
|
|
157
|
+
},
|
|
158
|
+
/** Draw the signature again, stroke by stroke, at the speed it was signed (at most ~2.5 s). */
|
|
159
|
+
replay() {
|
|
160
|
+
if (!strokes.length) return Promise.resolve(api);
|
|
161
|
+
replaying?.kill();
|
|
162
|
+
if (RM()) { redraw(); return Promise.resolve(api); }
|
|
163
|
+
const all = strokes.map((s) => ({ s, d: Math.max(0.12, (s.pts[s.pts.length - 1].t - s.pts[0].t) / 1000) }));
|
|
164
|
+
const total = all.reduce((a, x) => a + x.d + 0.12, 0), speed = Math.max(1, total / 2.5);
|
|
165
|
+
ctx.clearRect(0, 0, box.w, box.h);
|
|
166
|
+
return new Promise((res) => {
|
|
167
|
+
const tl = g.timeline({ onComplete: () => { replaying = null; redraw(); res(api); } });
|
|
168
|
+
const color = ink();
|
|
169
|
+
all.forEach(({ s, d }) => {
|
|
170
|
+
const p = { n: 1 };
|
|
171
|
+
tl.to(p, { n: s.pts.length, duration: d / speed, ease: 'none', onUpdate: () => { redraw0(); paint(ctx, s, k(), color, Math.round(p.n)); } }, `+=${0.12 / speed}`);
|
|
172
|
+
const done = strokes.indexOf(s);
|
|
173
|
+
// strokes before this one stay drawn
|
|
174
|
+
function redraw0() { ctx.clearRect(0, 0, box.w, box.h); strokes.slice(0, done).forEach((x) => paint(ctx, x, k(), color)); }
|
|
175
|
+
});
|
|
176
|
+
replaying = tl;
|
|
177
|
+
});
|
|
178
|
+
},
|
|
179
|
+
/** The strokes as plain data (points in a 1000-wide space), to save and load back with fromJSON(). */
|
|
180
|
+
toJSON() { return { v: 1, ratio: box.h / box.w, strokes: strokes.map((s) => s.pts.map((p) => [Math.round(p.x * 10) / 10, Math.round(p.y * 10) / 10, Math.round(p.w * 100) / 100, Math.round(p.t)])) }; },
|
|
181
|
+
fromJSON(data, { animate = false } = {}) {
|
|
182
|
+
strokes = (data?.strokes || []).map((s) => ({ pts: s.map(([x, y, w, t]) => ({ x, y, w, t })) }));
|
|
183
|
+
redraw(); changed();
|
|
184
|
+
if (animate) return api.replay();
|
|
185
|
+
return Promise.resolve(api);
|
|
186
|
+
},
|
|
187
|
+
/** A picture of the signature. trim cuts it to the ink (plus a margin); background '' keeps it transparent. */
|
|
188
|
+
toImage({ type = 'image/png', background = '', color = '#14161c', trim = true, scale = 2, margin = 12 } = {}) {
|
|
189
|
+
const c = document.createElement('canvas');
|
|
190
|
+
let x0 = 0, y0 = 0, w = box.w, h = box.h;
|
|
191
|
+
if (trim && strokes.length) {
|
|
192
|
+
const pts = strokes.flatMap((s) => s.pts), m = margin / k();
|
|
193
|
+
x0 = Math.min(...pts.map((p) => p.x - p.w)) - m; y0 = Math.min(...pts.map((p) => p.y - p.w)) - m;
|
|
194
|
+
w = (Math.max(...pts.map((p) => p.x + p.w)) + m - x0) * k(); h = (Math.max(...pts.map((p) => p.y + p.w)) + m - y0) * k();
|
|
195
|
+
}
|
|
196
|
+
c.width = Math.max(1, Math.round(w * scale)); c.height = Math.max(1, Math.round(h * scale));
|
|
197
|
+
const cc = c.getContext('2d'); cc.setTransform(scale, 0, 0, scale, 0, 0);
|
|
198
|
+
if (background) { cc.fillStyle = background; cc.fillRect(0, 0, w, h); }
|
|
199
|
+
cc.translate(-x0 * k(), -y0 * k());
|
|
200
|
+
strokes.forEach((s) => paint(cc, s, k(), color));
|
|
201
|
+
return c.toDataURL(type);
|
|
202
|
+
},
|
|
203
|
+
/** The signature as an SVG string (each stroke one smooth path). */
|
|
204
|
+
toSVG({ color = '#14161c' } = {}) {
|
|
205
|
+
const path = (p) => { if (p.length < 2) return `M${p[0].x} ${p[0].y}h0.01`; let d = `M${p[0].x} ${p[0].y}`; for (let i = 1; i < p.length - 1; i++) d += `Q${p[i].x} ${p[i].y} ${((p[i].x + p[i + 1].x) / 2).toFixed(1)} ${((p[i].y + p[i + 1].y) / 2).toFixed(1)}`; return `${d}L${p[p.length - 1].x} ${p[p.length - 1].y}`; };
|
|
206
|
+
const H = Math.round(1000 * box.h / box.w);
|
|
207
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 ${H}" fill="none" stroke="${esc(color)}" stroke-linecap="round" stroke-linejoin="round">${strokes.map((s) => `<path d="${path(s.pts)}" stroke-width="${(s.pts.reduce((a, p) => a + p.w, 0) / s.pts.length).toFixed(2)}"/>`).join('')}</svg>`;
|
|
208
|
+
},
|
|
209
|
+
destroy() { ac.abort(); ro.disconnect(); mo?.disconnect(); replaying?.kill(); el.innerHTML = ''; },
|
|
210
|
+
};
|
|
211
|
+
size();
|
|
212
|
+
return api;
|
|
213
|
+
};
|