@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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +904 -2
  3. package/index.js +225 -0
  4. package/package.json +42 -4
  5. package/src/accordion.js +208 -0
  6. package/src/activity.js +218 -0
  7. package/src/alert.js +205 -0
  8. package/src/authform.js +285 -0
  9. package/src/beforeafter.js +141 -0
  10. package/src/bell.js +137 -0
  11. package/src/breadcrumbs.js +204 -0
  12. package/src/calendar.js +523 -0
  13. package/src/carousel.js +266 -0
  14. package/src/combobox.js +421 -0
  15. package/src/daterange.js +311 -0
  16. package/src/donut.js +346 -0
  17. package/src/filedrop.js +378 -0
  18. package/src/gauge.js +169 -0
  19. package/src/grid.js +298 -0
  20. package/src/heatmap.js +332 -0
  21. package/src/kanban.js +319 -0
  22. package/src/leaderboard.js +201 -0
  23. package/src/like.js +208 -0
  24. package/src/linechart.js +550 -0
  25. package/src/multiselect.js +324 -0
  26. package/src/notifications.js +393 -0
  27. package/src/otp.js +112 -0
  28. package/src/pagination.js +242 -0
  29. package/src/password.js +245 -0
  30. package/src/pay.js +162 -0
  31. package/src/pricing.js +189 -0
  32. package/src/radiocards.js +101 -0
  33. package/src/rangeslider.js +266 -0
  34. package/src/rating.js +171 -0
  35. package/src/signature.js +213 -0
  36. package/src/skeleton.js +254 -0
  37. package/src/speeddial.js +128 -0
  38. package/src/spinner.js +38 -0
  39. package/src/stepper.js +211 -0
  40. package/src/subscribe.js +173 -0
  41. package/src/swipe.js +280 -0
  42. package/src/tagsinput.js +369 -0
  43. package/src/timeline.js +340 -0
  44. package/src/timepicker.js +290 -0
  45. package/src/tree.js +490 -0
  46. package/src/typing.js +93 -0
  47. package/src/upload.js +416 -0
  48. package/src/virtuallist.js +373 -0
  49. package/src/wizard.js +392 -0
  50. package/style.css +2092 -0
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
+ };
@@ -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
+ };
@@ -0,0 +1,254 @@
1
+ /* Skeleton: grey placeholder blocks in the shape of what is loading (a list, cards, text, a table,
2
+ or your own markup), with a soft light that sweeps across all of them together.
3
+ reveal(content) is the signature motion: the placeholders fade row by row while the real rows
4
+ rise into their place with a stagger, and the box grows or shrinks from the skeleton's height to
5
+ the real height, so nothing below it jumps. loading(true) puts the placeholders back over the
6
+ content at the same height. With reduced motion the sweep stops and everything swaps at once. */
7
+ import * as M from '@gecko-ui-kit/motion';
8
+ import { esc } from '../index.js';
9
+
10
+ const { g, RM, $$ } = M;
11
+ const WORDS = { loading: 'Loading…', loaded: 'Loaded' };
12
+ const LOOKS = ['list', 'card', 'text', 'table', 'custom'];
13
+ const REPLACED = /^(IMG|VIDEO|CANVAS|SVG|INPUT|TEXTAREA|SELECT|BUTTON|IFRAME|PICTURE|OBJECT)$/i;
14
+ const W1 = [46, 38, 54, 42, 58, 35, 50]; // first (title) line widths, %
15
+ const W2 = [84, 68, 76, 90, 62, 80, 72]; // other lines
16
+ const int = (v, a, b, d) => { v = Math.round(+v); return Number.isFinite(v) ? Math.min(b, Math.max(a, v)) : d; };
17
+ const bar = (kind, w) => `<span class="sk__b sk__b--${kind}"${w ? ` style="--w:${w}%"` : ''}></span>`;
18
+ /** n lines; the first one is the stronger "title" line. */
19
+ const lines = (n, i) => { let s = ''; for (let k = 0; k < n; k++) s += k === 0 ? bar('line sk__b--strong', W1[(i + k) % 7]) : bar('line', W2[(i * 3 + k) % 7]); return s; };
20
+ /** n lines of running text; the last one is shorter. */
21
+ const para = (n, i) => { let s = ''; for (let k = 0; k < n; k++) s += bar('line', k === n - 1 ? 52 + ((i * 13) % 28) : 92 + (((i + k) * 3) % 8)); return s; };
22
+
23
+ /** The placeholder blocks for one look (inside .sk__ph). */
24
+ const phInner = (look, o = {}) => {
25
+ const rows = int(o.rows ?? 3, 1, 60, 3), n = int(o.lines ?? 2, 1, 12, 2), av = o.avatar !== false, media = o.media ?? look === 'card';
26
+ let s = '';
27
+ if (look === 'card') {
28
+ for (let i = 0; i < rows; i++) {
29
+ s += `<div class="sk__item sk__card">${media ? bar('media') : ''}<span class="sk__lines">${lines(n + 1, i)}</span>`
30
+ + `${av ? `<span class="sk__by">${bar('circle sk__b--sm')}${bar('line', 34 + ((i * 9) % 22))}</span>` : ''}</div>`;
31
+ }
32
+ return `<div class="sk__cards">${s}</div>`;
33
+ }
34
+ if (look === 'table') {
35
+ const cols = int(o.cols ?? 4, 2, 8, 4), tpl = `grid-template-columns:minmax(0,1.7fr) repeat(${cols - 1},minmax(0,1fr))`;
36
+ for (let r = -1; r < rows; r++) {
37
+ let cs = '';
38
+ for (let c = 0; c < cols; c++) {
39
+ cs += r < 0 ? `<span class="sk__cell">${bar('line sk__b--head', c ? 44 : 30)}</span>`
40
+ : `<span class="sk__cell">${c === 0 && av ? bar('circle sk__b--sm') : ''}${bar(c ? 'line' : 'line sk__b--strong', c ? W2[(r + c) % 7] - 18 : W1[r % 7] + 22)}</span>`;
41
+ }
42
+ s += `<div class="sk__item sk__tr${r < 0 ? ' sk__tr--head' : ''}" style="${tpl}">${cs}</div>`;
43
+ }
44
+ return `<div class="sk__table">${s}</div>`;
45
+ }
46
+ if (look === 'text') {
47
+ s += `<div class="sk__item sk__head">${av ? `<span class="sk__by">${bar('circle')}<span class="sk__lines">${bar('line sk__b--strong', 34)}${bar('line', 22)}</span></span>` : ''}`
48
+ + `${media ? bar('media') : ''}${bar('title', 64)}</div>`;
49
+ for (let i = 0; i < rows; i++) s += `<div class="sk__item sk__para">${para(n, i)}</div>`;
50
+ return s;
51
+ }
52
+ for (let i = 0; i < rows; i++) {
53
+ s += `<div class="sk__item sk__row">${media ? bar('thumb') : ''}${av ? bar('circle') : ''}<span class="sk__lines">${lines(n, i)}</span>${bar('pill')}</div>`;
54
+ }
55
+ return s;
56
+ };
57
+ const statusText = (W, label, on) => { const t = on ? W.loading : W.loaded; return t && label ? `${label}: ${t}` : t || ''; };
58
+
59
+ /**
60
+ * skeletonHtml('list' | 'card' | 'text' | 'table', { rows, avatar, media, lines, cols, shimmer, label, words })
61
+ * → the same placeholder markup as a string, for pages that render their own HTML.
62
+ * Swap it for the real content yourself (or call skeleton() on the element to get reveal()).
63
+ */
64
+ export const skeletonHtml = (look = 'list', opts = {}) => {
65
+ look = LOOKS.includes(look) && look !== 'custom' ? look : 'list';
66
+ const W = { ...WORDS, ...opts.words };
67
+ return `<div class="sk sk--${look}${opts.shimmer === false ? ' sk--still' : ''}" aria-busy="true">`
68
+ + `<div class="sk__ph" aria-hidden="true">${phInner(look, opts)}</div>`
69
+ + `<span class="sk__sr" role="status">${esc(statusText(W, opts.label, true))}</span></div>`;
70
+ };
71
+
72
+ /**
73
+ * const sk = skeleton(el, {
74
+ * look: 'list' | 'card' | 'text' | 'table' | 'custom',
75
+ * // custom: every element inside el with data-sk becomes a grey block of its own size
76
+ * // (one bar per line for plain text; data-sk="box" / "circle" to force a shape)
77
+ * rows: 3, // list rows, cards, paragraphs or table rows
78
+ * avatar: true, // a round avatar in each row (and a byline on cards / text)
79
+ * media: false, // a picture block (true by default for look: 'card')
80
+ * lines: 2, // text lines per row / card / paragraph
81
+ * cols: 4, // table columns
82
+ * shimmer: true, // the light that sweeps across the blocks
83
+ * label: 'Team', // added to what screen readers hear: “Team: Loading…”
84
+ * words: { loading, loaded },
85
+ * })
86
+ * sk.reveal(html | Node | (box) => …, { stagger: true }) → Promise placeholders → real content
87
+ * sk.loading(true) → Promise placeholders over the content again, same height (false = reveal())
88
+ * sk.busy · sk.content (the element that holds the real content) · sk.destroy({ keep })
89
+ */
90
+ export const skeleton = (el, opts = {}) => {
91
+ el = $$(el)[0];
92
+ if (!el) return null;
93
+ const o = { look: 'list', rows: 3, avatar: true, media: null, lines: 2, cols: 4, shimmer: true, label: '', words: null, ...opts };
94
+ const look = LOOKS.includes(o.look) ? o.look : 'list', custom = look === 'custom';
95
+ const W = { ...WORDS, ...o.words };
96
+ let busy = false, timer = 0, ro = null, tl = null;
97
+
98
+ const frag = document.createDocumentFragment();
99
+ frag.append(...el.childNodes);
100
+ el.innerHTML = `<div class="sk sk--${look}"><div class="sk__real"></div><div class="sk__ph" aria-hidden="true"></div><span class="sk__sr" role="status"></span></div>`;
101
+ const root = el.firstElementChild, real = root.firstElementChild, ph = real.nextElementSibling, sr = root.lastElementChild;
102
+ real.append(frag);
103
+
104
+ const still = () => root.classList.toggle('sk--still', !o.shimmer || RM());
105
+ const say = (t) => { clearTimeout(timer); sr.textContent = ''; if (t) timer = setTimeout(() => { sr.textContent = t; }, 80); };
106
+ const mark = (on) => { busy = on; el.setAttribute('aria-busy', String(on)); real.inert = on; say(statusText(W, o.label, on)); };
107
+ const put = (c) => {
108
+ if (typeof c === 'function') { real.replaceChildren(); const r = c(real); if (typeof r === 'string') real.innerHTML = r; else if (r?.nodeType) real.append(r); }
109
+ else if (c?.nodeType) real.replaceChildren(c);
110
+ else real.innerHTML = String(c);
111
+ };
112
+ /** What rises in: the rows of the content (looks through one lone wrapper, e.g. a <ul> or a grid). */
113
+ const itemsOf = (box) => {
114
+ let n = box;
115
+ for (let d = 0; d < 4; d++) {
116
+ if (n.tagName === 'TABLE') return [...n.rows];
117
+ const k = [...n.children].filter((c) => c.getClientRects().length);
118
+ if (k.length === 1 && k[0].children.length) { n = k[0]; continue; }
119
+ return k.length ? k : [box];
120
+ }
121
+ return [n];
122
+ };
123
+ const shapes = () => $$('[data-sk]', real).filter((n) => n.getClientRects().length);
124
+
125
+ /* ---------- drawing the placeholders ---------- */
126
+ const render = (minH = 0) => {
127
+ ph.innerHTML = phInner(look, o);
128
+ if (!minH || look === 'card') return;
129
+ // over existing content: add rows until the placeholders fill the height that is kept
130
+ const it = ph.querySelectorAll('.sk__item'), k = it.length;
131
+ if (k < 2) return;
132
+ const a = it[k - 2], b = it[k - 1], per = b.offsetTop - a.offsetTop, bottom = b.offsetTop + b.offsetHeight;
133
+ const extra = per > 0 ? Math.ceil((minH - bottom) / per) : 0;
134
+ if (extra > 0) ph.innerHTML = phInner(look, { ...o, rows: Math.min(60, int(o.rows, 1, 60, 3) + extra) });
135
+ };
136
+ const drawCustom = () => {
137
+ const R = root.getBoundingClientRect(), out = [];
138
+ const add = (x, y, w, h, r) => { if (w >= 1 && h >= 1) out.push(`<span class="sk__b sk__item" style="left:${(x - R.left).toFixed(1)}px;top:${(y - R.top).toFixed(1)}px;width:${w.toFixed(1)}px;height:${h.toFixed(1)}px;border-radius:${r}"></span>`); };
139
+ shapes().forEach((n) => {
140
+ const cs = getComputedStyle(n), kind = n.dataset.sk;
141
+ if (kind !== 'box' && kind !== 'circle' && !n.children.length && n.textContent.trim() && !REPLACED.test(n.tagName)) {
142
+ // plain text: one rounded bar per line, as long as the line
143
+ const rg = document.createRange(), rows = [];
144
+ rg.selectNodeContents(n);
145
+ [...rg.getClientRects()].forEach((r) => {
146
+ if (r.width < 1) return;
147
+ const row = rows.find((x) => Math.abs(x.top - r.top) < r.height / 2);
148
+ if (row) { row.l = Math.min(row.l, r.left); row.r = Math.max(row.r, r.right); } else rows.push({ top: r.top, h: r.height, l: r.left, r: r.right });
149
+ });
150
+ rows.forEach((x) => { const h = Math.max(8, Math.round(x.h * 0.62)); add(x.l, x.top + (x.h - h) / 2, x.r - x.l, h, '6px'); });
151
+ } else {
152
+ const r = n.getBoundingClientRect();
153
+ add(r.left, r.top, r.width, r.height, kind === 'circle' ? '50%' : parseFloat(cs.borderTopLeftRadius) ? cs.borderRadius : '8px');
154
+ }
155
+ });
156
+ ph.innerHTML = out.join('');
157
+ };
158
+
159
+ /* ---------- transitions ---------- */
160
+ /** A new call first finishes the one still running (jumps it to its end). */
161
+ const stop = () => { for (let i = 0; tl && i < 4; i++) { const t = tl; t.progress(1); if (tl === t) tl = null; } };
162
+
163
+ const reveal = (content, { stagger = true } = {}) => new Promise((resolve) => {
164
+ stop();
165
+ const has = content != null;
166
+ const go = () => {
167
+ const h0 = root.offsetHeight, fromPh = !ph.hidden;
168
+ if (has) put(content);
169
+ g.set(real, { clearProps: 'opacity,visibility' });
170
+ if (fromPh) ph.classList.add('is-over');
171
+ root.classList.remove('is-loading');
172
+ real.hidden = false;
173
+ root.style.height = '';
174
+ const h1 = root.offsetHeight;
175
+ if (busy) mark(false);
176
+ const finish = () => {
177
+ tl = null;
178
+ ph.hidden = true; ph.classList.remove('is-over');
179
+ if (custom) ph.innerHTML = '';
180
+ g.set([root, ph], { clearProps: 'height,opacity' });
181
+ root.classList.remove('is-moving');
182
+ resolve();
183
+ };
184
+ if (RM()) { finish(); return; }
185
+ let targets = custom && !has ? shapes() : stagger ? itemsOf(real) : [real];
186
+ if (!targets.length) targets = [real];
187
+ const phItems = stagger ? [...ph.querySelectorAll('.sk__item')] : [ph];
188
+ const each = Math.min(0.07, 0.55 / targets.length), st = (i) => Math.min(i, 12) * each;
189
+ root.classList.add('is-moving');
190
+ tl = g.timeline({ onComplete: finish });
191
+ if (Math.abs(h1 - h0) > 1) tl.fromTo(root, { height: h0 }, { height: h1, duration: 0.55, ease: 'power3.inOut' }, 0);
192
+ if (fromPh && phItems.length) tl.to(phItems, { opacity: 0, duration: 0.3, ease: 'power1.out', stagger: st }, 0);
193
+ tl.fromTo(targets, { opacity: 0, y: 10 }, { opacity: 1, y: 0, duration: 0.5, ease: 'power3.out', stagger: st, clearProps: 'opacity,transform' }, 0.08);
194
+ };
195
+ // swapping content that is already showing: the old content fades out first
196
+ if (!busy && has && ph.hidden && real.childNodes.length && !RM()) tl = g.to(real, { opacity: 0, duration: 0.15, ease: 'power1.in', onComplete: () => { tl = null; go(); } });
197
+ else go();
198
+ });
199
+
200
+ const loading = (on = true) => {
201
+ if (!on) return reveal();
202
+ return new Promise((resolve) => {
203
+ stop();
204
+ if (busy) { resolve(); return; }
205
+ mark(true); still();
206
+ if (custom) {
207
+ drawCustom(); ph.hidden = false;
208
+ const els = shapes();
209
+ const end = () => { tl = null; root.classList.add('is-loading'); g.set(els, { clearProps: 'opacity' }); resolve(); };
210
+ if (RM() || !els.length) { end(); return; }
211
+ tl = g.timeline({ onComplete: end });
212
+ tl.to(els, { opacity: 0, duration: 0.2, ease: 'power1.out' }, 0)
213
+ .fromTo(ph, { opacity: 0 }, { opacity: 1, duration: 0.3, ease: 'power1.out', clearProps: 'opacity' }, 0);
214
+ return;
215
+ }
216
+ const h = root.offsetHeight;
217
+ if (!real.childNodes.length || h < 24) { // nothing to cover: back to the first look
218
+ real.hidden = true; ph.classList.remove('is-over'); ph.hidden = false; render(); resolve(); return;
219
+ }
220
+ root.style.height = `${h}px`; // keep the height while the placeholders show
221
+ ph.classList.add('is-over'); ph.hidden = false; render(h);
222
+ const end = () => { tl = null; g.set(real, { visibility: 'hidden', clearProps: 'opacity' }); resolve(); };
223
+ if (RM()) { end(); return; }
224
+ tl = g.timeline({ onComplete: end });
225
+ tl.to(real, { opacity: 0, duration: 0.22, ease: 'power1.out' }, 0)
226
+ .fromTo(ph, { opacity: 0 }, { opacity: 1, duration: 0.32, ease: 'power1.out', clearProps: 'opacity' }, 0.05);
227
+ });
228
+ };
229
+
230
+ /* ---------- first look ---------- */
231
+ still();
232
+ if (custom) {
233
+ root.classList.add('is-loading'); ph.hidden = false; drawCustom();
234
+ if (typeof ResizeObserver === 'function') { ro = new ResizeObserver(() => { if (busy) drawCustom(); }); ro.observe(root); }
235
+ } else { real.hidden = true; render(); }
236
+ mark(true);
237
+
238
+ const api = {
239
+ root,
240
+ content: real,
241
+ get busy() { return busy; },
242
+ reveal,
243
+ loading,
244
+ /** keep: true leaves the real content in el (without the skeleton wrapper). */
245
+ destroy({ keep = false } = {}) {
246
+ stop(); ro?.disconnect(); clearTimeout(timer);
247
+ g.killTweensOf([root, real, ph, ...real.children, ...ph.querySelectorAll('.sk__item')]);
248
+ el.removeAttribute('aria-busy');
249
+ if (keep) { real.inert = false; g.set(real, { clearProps: 'opacity,visibility' }); const f = document.createDocumentFragment(); f.append(...real.childNodes); el.replaceChildren(f); }
250
+ else el.innerHTML = '';
251
+ },
252
+ };
253
+ return api;
254
+ };