@gecko-ui-kit/components 0.0.0-stage → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +712 -2
- package/index.js +198 -0
- package/package.json +42 -4
- package/src/accordion.js +208 -0
- package/src/alert.js +205 -0
- package/src/authform.js +285 -0
- package/src/breadcrumbs.js +204 -0
- package/src/calendar.js +523 -0
- package/src/carousel.js +266 -0
- package/src/combobox.js +421 -0
- package/src/daterange.js +311 -0
- package/src/donut.js +346 -0
- package/src/filedrop.js +378 -0
- package/src/gauge.js +169 -0
- package/src/grid.js +298 -0
- package/src/heatmap.js +332 -0
- package/src/kanban.js +319 -0
- package/src/leaderboard.js +201 -0
- package/src/linechart.js +550 -0
- package/src/multiselect.js +324 -0
- package/src/notifications.js +393 -0
- package/src/otp.js +112 -0
- package/src/pagination.js +242 -0
- package/src/password.js +245 -0
- package/src/rangeslider.js +266 -0
- package/src/rating.js +171 -0
- package/src/signature.js +213 -0
- package/src/skeleton.js +254 -0
- package/src/spinner.js +38 -0
- package/src/stepper.js +211 -0
- package/src/swipe.js +280 -0
- package/src/tagsinput.js +369 -0
- package/src/timeline.js +340 -0
- package/src/timepicker.js +290 -0
- package/src/tree.js +490 -0
- package/src/upload.js +416 -0
- package/src/virtuallist.js +373 -0
- package/src/wizard.js +392 -0
- package/style.css +1761 -0
package/src/skeleton.js
ADDED
|
@@ -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
|
+
};
|
package/src/spinner.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/* Spinner (orbit loader): a comet sweeps round a faint ring. Its tail fades from nothing to the
|
|
2
|
+
full tone colour and a small glowing head leads it, so it reads as one object circling rather
|
|
3
|
+
than a ring that rotates. Tail and head turn together in one CSS rotation (it keeps going while
|
|
4
|
+
the page is busy with scripts, and needs no JavaScript once it is on the page). Size it with
|
|
5
|
+
font-size: the ring is 1em across. With reduced motion (the OS setting, or reduceMotion(true)
|
|
6
|
+
before you build it) the comet stops turning and the ring breathes slowly instead. */
|
|
7
|
+
import * as M from '@gecko-ui-kit/motion';
|
|
8
|
+
import { esc } from '../index.js';
|
|
9
|
+
|
|
10
|
+
const { RM } = M;
|
|
11
|
+
const WORDS = { loading: 'Loading…' };
|
|
12
|
+
const TONES = ['accent', 'ink', 'muted', 'good', 'warn', 'bad', 'current'];
|
|
13
|
+
const len = (v) => (typeof v === 'number' ? `${v}px` : String(v).replace(/[^\w.%()+\-*/ ]/g, ''));
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* spinner({
|
|
17
|
+
* size: 28, // px, or any CSS length ('1.2em' to match the text around it)
|
|
18
|
+
* tone: 'accent' | 'ink' | 'muted' | 'good' | 'warn' | 'bad' | 'current', // current = the text colour
|
|
19
|
+
* speed: 1, // seconds per lap
|
|
20
|
+
* track: true, // the faint full ring behind the comet
|
|
21
|
+
* label: '', // text shown next to it ('' = a hidden "Loading…" for screen readers only)
|
|
22
|
+
* stack: false, // the label under the ring instead of beside it
|
|
23
|
+
* words: { loading: 'Loading…' },
|
|
24
|
+
* decorative: false, // true: hidden from screen readers (no role, no text), e.g. inside a button whose text already says "Saving…"
|
|
25
|
+
* cls: '', // extra classes
|
|
26
|
+
* }) → HTML string: <span class="orb" role="status">…</span>
|
|
27
|
+
* Remove the element (or replace it with the content) when loading is done.
|
|
28
|
+
*/
|
|
29
|
+
export const spinner = (opts = {}) => {
|
|
30
|
+
const o = { size: '', tone: 'accent', speed: 1, track: true, label: '', stack: false, words: null, decorative: false, cls: '', ...opts };
|
|
31
|
+
const W = { ...WORDS, ...o.words };
|
|
32
|
+
const tone = TONES.includes(o.tone) ? o.tone : 'accent';
|
|
33
|
+
const style = [o.size !== '' && o.size !== null && o.size !== undefined ? `font-size:${len(o.size)}` : '', +o.speed && +o.speed !== 1 ? `--orb-speed:${+o.speed}s` : ''].filter(Boolean).join(';');
|
|
34
|
+
const cls = ['orb', `orb--${tone}`, o.track === false ? 'orb--bare' : '', o.stack && o.label ? 'orb--stack' : '', RM() ? 'orb--still' : '', o.cls].filter(Boolean).join(' ');
|
|
35
|
+
const text = o.label ? `<span class="orb__label">${esc(o.label)}</span>` : o.decorative ? '' : `<span class="orb__sr">${esc(W.loading)}</span>`;
|
|
36
|
+
const role = o.decorative ? ' aria-hidden="true"' : ' role="status"';
|
|
37
|
+
return `<span class="${esc(cls)}"${role}${style ? ` style="${style}"` : ''}><span class="orb__dial" aria-hidden="true"><span class="orb__spin"></span></span>${text}</span>`;
|
|
38
|
+
};
|
package/src/stepper.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/* Number stepper: − and + round a number whose digits roll like an odometer — up when it goes up,
|
|
2
|
+
down when it goes down, and only the digits that change. Hold a button and it keeps counting,
|
|
3
|
+
faster and faster. At the limit the number gives a small elastic nudge instead of moving.
|
|
4
|
+
Click (or start typing on) the number to type a value straight in. */
|
|
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: 'Amount', less: 'Decrease', more: 'Increase', min: (n) => `The least is ${n}`, max: (n) => `The most is ${n}` };
|
|
11
|
+
const STRIP = Array.from({ length: 20 }, (_, i) => `<i>${i % 10}</i>`).join('');
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* const st = stepper(el, {
|
|
15
|
+
* value: 1, min: 0, max: 99, step: 1, // step 0.5 shows one decimal, 0.25 two
|
|
16
|
+
* unit: 'days' | (n) => (n === 1 ? 'day' : 'days'), // after the number
|
|
17
|
+
* prefix: '฿', // before the number
|
|
18
|
+
* format: (n) => string, // default: grouped digits for the locale (1,250)
|
|
19
|
+
* locale: undefined,
|
|
20
|
+
* size: '' | 'sm' | 'lg',
|
|
21
|
+
* name: 'days', // a hidden input, so a plain <form> sends the value
|
|
22
|
+
* disabled: false,
|
|
23
|
+
* words: { label, less, more, min, max },
|
|
24
|
+
* onChange(value, st)
|
|
25
|
+
* })
|
|
26
|
+
* st.value · st.set(n) · st.stepBy(±1) · st.setRange({ min, max }) · st.destroy()
|
|
27
|
+
*/
|
|
28
|
+
export const stepper = (el, opts = {}) => {
|
|
29
|
+
el = $$(el)[0];
|
|
30
|
+
if (!el) return null;
|
|
31
|
+
const o = { value: 0, min: -Infinity, max: Infinity, step: 1, unit: '', prefix: '', format: null, locale: undefined, size: '', name: '', disabled: false, onChange: null, ...opts };
|
|
32
|
+
const W = { ...WORDS, ...o.words };
|
|
33
|
+
const dec = () => (String(o.step).split('.')[1] || '').length;
|
|
34
|
+
const nf = () => new Intl.NumberFormat(o.locale, { minimumFractionDigits: dec(), maximumFractionDigits: dec() });
|
|
35
|
+
const fmt = (n) => (o.format ? String(o.format(n)) : nf().format(n));
|
|
36
|
+
const unitOf = (n) => (typeof o.unit === 'function' ? o.unit(n) : o.unit) || '';
|
|
37
|
+
const snap = (n) => { const base = Number.isFinite(o.min) ? o.min : 0; const s = +o.step || 1; return +(base + Math.round((n - base) / s) * s).toFixed(dec()); };
|
|
38
|
+
const clamp = (n) => Math.min(o.max, Math.max(o.min, n));
|
|
39
|
+
|
|
40
|
+
el.innerHTML = `<div class="st${o.size ? ` st--${esc(o.size)}` : ''}${o.disabled ? ' is-disabled' : ''}">`
|
|
41
|
+
+ `<button type="button" class="st__btn" data-d="-1" aria-label="${esc(W.less)}"${o.disabled ? ' disabled' : ''}>${icon('minus')}</button>`
|
|
42
|
+
+ `<div class="st__val" role="spinbutton" tabindex="${o.disabled ? -1 : 0}" aria-label="${esc(W.label)}"${o.disabled ? ' aria-disabled="true"' : ''}>`
|
|
43
|
+
+ `<span class="st__face" aria-hidden="true">${o.prefix ? `<span class="st__pre">${esc(o.prefix)}</span>` : ''}<span class="st__odo"></span><span class="st__unit"></span></span>`
|
|
44
|
+
+ `<input class="st__input" type="text" inputmode="${dec() ? 'decimal' : 'numeric'}" tabindex="-1" aria-hidden="true" autocomplete="off"></div>`
|
|
45
|
+
+ `<button type="button" class="st__btn" data-d="1" aria-label="${esc(W.more)}"${o.disabled ? ' disabled' : ''}>${icon('plus')}</button>`
|
|
46
|
+
+ `${o.name ? `<input type="hidden" name="${esc(o.name)}">` : ''}<span class="st__sr" role="status"></span></div>`;
|
|
47
|
+
const root = el.firstElementChild, val = root.querySelector('.st__val'), odo = root.querySelector('.st__odo'), unitEl = root.querySelector('.st__unit');
|
|
48
|
+
const input = root.querySelector('.st__input'), [less, more] = root.querySelectorAll('.st__btn');
|
|
49
|
+
const say = (t) => { root.querySelector('.st__sr').textContent = t; };
|
|
50
|
+
|
|
51
|
+
let value = clamp(snap(+o.value || 0)), shown = '';
|
|
52
|
+
|
|
53
|
+
/* ---------- the odometer ---------- */
|
|
54
|
+
const isDigit = (c) => c >= '0' && c <= '9';
|
|
55
|
+
const cell = (c) => {
|
|
56
|
+
const s = document.createElement('span');
|
|
57
|
+
if (isDigit(c)) { s.className = 'st__d'; s.innerHTML = `<span class="st__strip">${STRIP}</span>`; g.set(s.firstChild, { yPercent: -(+c) * 5 }); }
|
|
58
|
+
else { s.className = 'st__c'; s.textContent = c; }
|
|
59
|
+
s.dataset.c = c;
|
|
60
|
+
return s;
|
|
61
|
+
};
|
|
62
|
+
/** Roll one digit strip to c, the short way round in the direction the number moved. */
|
|
63
|
+
const roll = (span, c, dir, delay) => {
|
|
64
|
+
const strip = span.firstChild, n = +c;
|
|
65
|
+
let p = -g.getProperty(strip, 'yPercent') / 5; // where it shows now (0…20)
|
|
66
|
+
p = ((p % 10) + 10) % 10; g.killTweensOf(strip); g.set(strip, { yPercent: -p * 5 });
|
|
67
|
+
span.dataset.c = c;
|
|
68
|
+
if (RM()) { g.set(strip, { yPercent: -n * 5 }); return; }
|
|
69
|
+
let to = n;
|
|
70
|
+
if (dir > 0) { if (n < p - 0.001) to = n + 10; }
|
|
71
|
+
else if (n > p + 0.001) { g.set(strip, { yPercent: -(p + 10) * 5 }); }
|
|
72
|
+
g.to(strip, { yPercent: -to * 5, duration: 0.45, delay, ease: 'power3.out', onComplete: () => g.set(strip, { yPercent: -n * 5 }) });
|
|
73
|
+
};
|
|
74
|
+
const draw = (text, dir, animate) => {
|
|
75
|
+
const leaving = [...odo.children].filter((x) => x.classList.contains('is-gone')); // still on their way out
|
|
76
|
+
const old = [...odo.children].filter((x) => !x.classList.contains('is-gone'));
|
|
77
|
+
const chars = [...text], seq = [], fresh = [], gone = [];
|
|
78
|
+
const w0 = odo.offsetWidth;
|
|
79
|
+
// line the two up from the right, so units stay units and tens stay tens
|
|
80
|
+
for (let k = 1; k <= Math.max(old.length, chars.length); k++) {
|
|
81
|
+
const span = old[old.length - k], c = chars[chars.length - k];
|
|
82
|
+
if (span && c != null && isDigit(c) && span.classList.contains('st__d')) {
|
|
83
|
+
if (span.dataset.c !== c) roll(span, c, dir, animate ? (k - 1) * 0.03 : 0);
|
|
84
|
+
seq.unshift(span);
|
|
85
|
+
} else if (span && c != null && span.dataset.c === c) seq.unshift(span);
|
|
86
|
+
else {
|
|
87
|
+
if (c != null) { const n = cell(c); fresh.push(n); seq.unshift(n); }
|
|
88
|
+
if (span) { span.classList.add('is-gone'); gone.push(span); seq.unshift(span); }
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
odo.replaceChildren(...leaving, ...seq);
|
|
92
|
+
if (!animate || RM()) { gone.forEach((x) => x.remove()); return; }
|
|
93
|
+
gone.forEach((x) => g.to(x, { yPercent: dir > 0 ? 70 : -70, opacity: 0, width: 0, duration: 0.3, ease: 'power2.in', onComplete: () => x.remove() }));
|
|
94
|
+
fresh.forEach((x) => { const w = x.offsetWidth; g.fromTo(x, { yPercent: dir > 0 ? -70 : 70, opacity: 0, width: 0 }, { yPercent: 0, opacity: 1, width: w, duration: 0.38, ease: 'power3.out', clearProps: 'width,opacity,transform' }); });
|
|
95
|
+
const w1 = odo.offsetWidth;
|
|
96
|
+
if (Math.abs(w1 - w0) > 1 && !fresh.length && !gone.length) g.fromTo(odo, { width: w0 }, { width: w1, duration: 0.3, ease: 'power3.out', clearProps: 'width' });
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const paint = (dir = 1, animate = true) => {
|
|
100
|
+
const text = fmt(value);
|
|
101
|
+
if (text !== shown) { draw(text, dir, animate && !!shown); shown = text; }
|
|
102
|
+
const u = unitOf(value);
|
|
103
|
+
if (unitEl.textContent !== u) {
|
|
104
|
+
unitEl.textContent = u; unitEl.hidden = !u;
|
|
105
|
+
if (animate && !RM() && u) g.fromTo(unitEl, { y: dir > 0 ? -6 : 6, opacity: 0 }, { y: 0, opacity: 1, duration: 0.3, ease: 'power2.out', clearProps: 'transform,opacity' });
|
|
106
|
+
}
|
|
107
|
+
const full = `${o.prefix || ''}${text}${u ? ` ${u}` : ''}`;
|
|
108
|
+
val.setAttribute('aria-valuenow', String(value)); val.setAttribute('aria-valuetext', full);
|
|
109
|
+
if (Number.isFinite(o.min)) val.setAttribute('aria-valuemin', String(o.min)); else val.removeAttribute('aria-valuemin');
|
|
110
|
+
if (Number.isFinite(o.max)) val.setAttribute('aria-valuemax', String(o.max)); else val.removeAttribute('aria-valuemax');
|
|
111
|
+
less.classList.toggle('is-end', value <= o.min); more.classList.toggle('is-end', value >= o.max);
|
|
112
|
+
less.setAttribute('aria-disabled', String(value <= o.min || o.disabled)); more.setAttribute('aria-disabled', String(value >= o.max || o.disabled));
|
|
113
|
+
const h = root.querySelector('input[type="hidden"]'); if (h) h.value = String(value);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/** Pushing past the limit: the number leans that way and springs back. */
|
|
117
|
+
const bump = (dir) => {
|
|
118
|
+
say(dir > 0 ? W.max(fmt(o.max)) : W.min(fmt(o.min)));
|
|
119
|
+
if (RM()) return;
|
|
120
|
+
const face = root.querySelector('.st__face');
|
|
121
|
+
g.fromTo(face, { y: 0 }, { keyframes: { y: [0, -dir * 5, 0] }, duration: 0.42, ease: 'power2.out', overwrite: true, clearProps: 'transform' });
|
|
122
|
+
const b = dir > 0 ? more : less;
|
|
123
|
+
g.fromTo(b, { x: 0 }, { keyframes: { x: [0, dir * 3, -dir * 2, 0] }, duration: 0.3, ease: 'power2.out', clearProps: 'transform' });
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const set = (n, { silent = false, animate = true } = {}) => {
|
|
127
|
+
if (!Number.isFinite(n)) return false;
|
|
128
|
+
const next = clamp(snap(n));
|
|
129
|
+
if (next === value) return false;
|
|
130
|
+
const dir = next > value ? 1 : -1;
|
|
131
|
+
value = next; paint(dir, animate);
|
|
132
|
+
if (!silent) o.onChange?.(value, api);
|
|
133
|
+
return true;
|
|
134
|
+
};
|
|
135
|
+
const stepBy = (dir) => {
|
|
136
|
+
if (o.disabled) return false;
|
|
137
|
+
const moved = set(value + dir * (+o.step || 1));
|
|
138
|
+
if (!moved) bump(dir);
|
|
139
|
+
return moved;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/* ---------- typing a value in ---------- */
|
|
143
|
+
const edit = (seed) => {
|
|
144
|
+
if (o.disabled || root.classList.contains('is-editing')) return;
|
|
145
|
+
root.classList.add('is-editing');
|
|
146
|
+
input.value = seed ?? String(value); input.tabIndex = 0;
|
|
147
|
+
input.focus(); if (seed == null) input.select(); else input.setSelectionRange(input.value.length, input.value.length);
|
|
148
|
+
};
|
|
149
|
+
const endEdit = (keep) => {
|
|
150
|
+
if (!root.classList.contains('is-editing')) return;
|
|
151
|
+
root.classList.remove('is-editing'); input.tabIndex = -1;
|
|
152
|
+
if (keep) {
|
|
153
|
+
const raw = input.value.replace(/[^\d.,-]/g, '').replace(/,(?=\d{3}\b)/g, '').replace(',', '.');
|
|
154
|
+
const n = parseFloat(raw);
|
|
155
|
+
if (Number.isFinite(n)) { const want = snap(n); if (!set(n) && want !== value) bump(want > value ? 1 : -1); }
|
|
156
|
+
}
|
|
157
|
+
val.focus({ preventScroll: true });
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
/* ---------- events ---------- */
|
|
161
|
+
const ac = new AbortController(), on = { signal: ac.signal };
|
|
162
|
+
let timer = null, pressed = false;
|
|
163
|
+
const stopRepeat = () => { clearTimeout(timer); timer = null; };
|
|
164
|
+
[less, more].forEach((b) => {
|
|
165
|
+
const dir = +b.dataset.d;
|
|
166
|
+
b.addEventListener('pointerdown', (e) => {
|
|
167
|
+
if (e.button > 0 || o.disabled) return;
|
|
168
|
+
e.preventDefault(); pressed = true; // keep the focus where it is
|
|
169
|
+
stepBy(dir);
|
|
170
|
+
let gap = 380; // hold: wait, then repeat faster and faster
|
|
171
|
+
const again = () => { if (!stepBy(dir)) { stopRepeat(); return; } gap = Math.max(40, gap * 0.82); timer = setTimeout(again, gap); };
|
|
172
|
+
timer = setTimeout(again, 420);
|
|
173
|
+
try { b.setPointerCapture(e.pointerId); } catch { /* fine */ }
|
|
174
|
+
}, on);
|
|
175
|
+
['pointerup', 'pointercancel', 'lostpointercapture'].forEach((t) => b.addEventListener(t, stopRepeat, on));
|
|
176
|
+
b.addEventListener('click', () => { if (pressed) { pressed = false; return; } stepBy(dir); }, on); // keyboard Enter/Space
|
|
177
|
+
});
|
|
178
|
+
val.addEventListener('keydown', (e) => {
|
|
179
|
+
if (e.target === input || root.classList.contains('is-editing')) return; // keys typed into the box are the box's
|
|
180
|
+
const big = (+o.step || 1) * 10;
|
|
181
|
+
const map = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1 };
|
|
182
|
+
if (map[e.key]) { e.preventDefault(); stepBy(map[e.key]); }
|
|
183
|
+
else if (e.key === 'PageUp' || e.key === 'PageDown') { e.preventDefault(); const d = e.key === 'PageUp' ? 1 : -1; if (!set(value + d * big)) bump(d); }
|
|
184
|
+
else if (e.key === 'Home' && Number.isFinite(o.min)) { e.preventDefault(); if (!set(o.min)) bump(-1); }
|
|
185
|
+
else if (e.key === 'End' && Number.isFinite(o.max)) { e.preventDefault(); if (!set(o.max)) bump(1); }
|
|
186
|
+
else if (e.key === 'Enter') { e.preventDefault(); edit(); }
|
|
187
|
+
else if (/^[\d.,-]$/.test(e.key) && !e.ctrlKey && !e.metaKey) { e.preventDefault(); edit(e.key); }
|
|
188
|
+
}, on);
|
|
189
|
+
val.addEventListener('click', (e) => { if (e.target !== input) edit(); }, on);
|
|
190
|
+
input.addEventListener('keydown', (e) => {
|
|
191
|
+
if (e.key === 'Enter') { e.preventDefault(); endEdit(true); }
|
|
192
|
+
else if (e.key === 'Escape') { e.preventDefault(); endEdit(false); }
|
|
193
|
+
else if (e.key === 'ArrowUp' || e.key === 'ArrowDown') { e.preventDefault(); endEdit(true); stepBy(e.key === 'ArrowUp' ? 1 : -1); }
|
|
194
|
+
}, on);
|
|
195
|
+
input.addEventListener('blur', () => endEdit(true), on);
|
|
196
|
+
ac.signal.addEventListener('abort', stopRepeat);
|
|
197
|
+
|
|
198
|
+
const api = {
|
|
199
|
+
el: root, opts: o,
|
|
200
|
+
get value() { return value; },
|
|
201
|
+
/** Go to a number (clamped and snapped to the step). */
|
|
202
|
+
set(n, { silent = false } = {}) { set(+n, { silent }); return api; },
|
|
203
|
+
/** One step up (1) or down (-1); returns false at the limit (after the nudge). */
|
|
204
|
+
stepBy,
|
|
205
|
+
/** Change the limits; the value is pulled inside them if needed. */
|
|
206
|
+
setRange({ min = o.min, max = o.max } = {}) { o.min = min; o.max = max; if (!set(value)) paint(1, false); return api; },
|
|
207
|
+
destroy() { ac.abort(); g.killTweensOf(root.querySelectorAll('*')); el.innerHTML = ''; },
|
|
208
|
+
};
|
|
209
|
+
paint(1, false);
|
|
210
|
+
return api;
|
|
211
|
+
};
|