@finstack-com-public/design 0.10.3 → 0.11.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.
@@ -0,0 +1,256 @@
1
+ // The slider and the range slider (F2 draft §4, T134): one or two `role="slider"` thumbs on a track,
2
+ // moved by the keys (APG Slider and Multi-Thumb Slider) and by the pointer (pointer capture). A
3
+ // range's thumbs depend on each other: neither crosses the other. Values are numbers; every word
4
+ // (the value text, a range thumb's name) is passed in.
5
+ const THUMB = '.fs-slider__thumb';
6
+ const DRAGGING = 'fs-is-dragging';
7
+ /** The digits after the point, so a snapped 0.1 + 0.2 reads 0.3. */
8
+ const decimals = (n) => {
9
+ const s = String(n);
10
+ const e = s.indexOf('e-');
11
+ if (e >= 0)
12
+ return Number(s.slice(e + 2));
13
+ const dot = s.indexOf('.');
14
+ return dot < 0 ? 0 : s.length - dot - 1;
15
+ };
16
+ /** A range's `__value` text: both ends' words. */
17
+ export const rangeValueText = (low, high) => `${low} – ${high}`;
18
+ export function createSlider(root, options) {
19
+ let opts = { ...options };
20
+ const isRange = Array.isArray(options.value);
21
+ const thumbs = [...root.querySelectorAll(THUMB)];
22
+ if (thumbs.length !== (isRange ? 2 : 1)) {
23
+ throw new Error(`createSlider: a ${isRange ? 'range needs two' : 'slider needs one'} ${THUMB}`);
24
+ }
25
+ const track = root.querySelector('.fs-slider__track') ?? root;
26
+ const step = () => (opts.step && opts.step > 0 ? opts.step : 1);
27
+ const pageStep = () => (opts.pageStep && opts.pageStep > 0 ? opts.pageStep : step() * 10);
28
+ const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
29
+ const snap = (v) => {
30
+ const s = step();
31
+ const snapped = opts.min + Math.round((v - opts.min) / s) * s;
32
+ return Number(snapped.toFixed(Math.max(decimals(s), decimals(opts.min))));
33
+ };
34
+ /** Snapped and clamped into the whole range, lower first. */
35
+ const normalise = (v) => {
36
+ const raw = isRange ? [...v] : [v];
37
+ const out = raw.map((x) => clamp(snap(Number.isFinite(x) ? x : opts.min), opts.min, opts.max));
38
+ return out.length === 2 && out[0] > out[1] ? [out[1], out[0]] : out;
39
+ };
40
+ let values = normalise(opts.value);
41
+ /** Where thumb `i` may go: the whole range, or up to the other thumb. */
42
+ const bounds = (i) => !isRange ? [opts.min, opts.max] : i === 0 ? [opts.min, values[1]] : [values[0], opts.max];
43
+ const percent = (v) => (opts.max === opts.min ? 0 : ((v - opts.min) / (opts.max - opts.min)) * 100);
44
+ const isRtl = () => getComputedStyle(root).direction === 'rtl';
45
+ const isDisabled = (thumb) => thumb.getAttribute('aria-disabled') === 'true';
46
+ const detail = () => ({ value: isRange ? [values[0], values[1]] : values[0] });
47
+ const emit = (type) => root.dispatchEvent(new CustomEvent(type, { bubbles: true, detail: detail() }));
48
+ function render() {
49
+ const text = (v) => opts.valueText(v);
50
+ thumbs.forEach((thumb, i) => {
51
+ const v = values[i];
52
+ const [lo, hi] = bounds(i);
53
+ if (!thumb.hasAttribute('role'))
54
+ thumb.setAttribute('role', 'slider');
55
+ if (!thumb.hasAttribute('tabindex'))
56
+ thumb.tabIndex = 0;
57
+ thumb.setAttribute('aria-valuemin', String(lo));
58
+ thumb.setAttribute('aria-valuemax', String(hi));
59
+ thumb.setAttribute('aria-valuenow', String(v));
60
+ thumb.setAttribute('aria-valuetext', text(v));
61
+ if (isRange && opts.labels)
62
+ thumb.setAttribute('aria-label', i === 0 ? opts.labels.start : opts.labels.end);
63
+ thumb.style.setProperty('--fs-slider-at', `${percent(v)}%`);
64
+ });
65
+ root.style.setProperty('--fs-slider-low', `${isRange ? percent(values[0]) : 0}%`);
66
+ root.style.setProperty('--fs-slider-high', `${percent(values[values.length - 1])}%`);
67
+ const out = root.querySelector('.fs-slider__value');
68
+ if (out)
69
+ out.textContent = isRange ? rangeValueText(text(values[0]), text(values[1])) : text(values[0]);
70
+ const inputs = root.querySelectorAll(':scope > input[type="hidden"]');
71
+ inputs.forEach((input, i) => {
72
+ if (i < values.length)
73
+ input.value = String(values[i]);
74
+ });
75
+ }
76
+ /** Moves thumb `i` to `to` (snapped unless `exact`), inside its bounds. Whether it moved. */
77
+ function moveTo(i, to, exact = false) {
78
+ const [lo, hi] = bounds(i);
79
+ const next = clamp(exact ? to : snap(to), lo, hi);
80
+ if (next === values[i])
81
+ return false;
82
+ values[i] = next;
83
+ render();
84
+ emit('fs-input');
85
+ return true;
86
+ }
87
+ function onKeydown(e) {
88
+ if (e.altKey || e.ctrlKey || e.metaKey)
89
+ return;
90
+ const i = thumbs.indexOf(e.target);
91
+ if (i < 0 || isDisabled(thumbs[i]))
92
+ return;
93
+ const v = values[i];
94
+ const [lo, hi] = bounds(i);
95
+ const flip = isRtl() ? -1 : 1;
96
+ let to;
97
+ let exact = false;
98
+ switch (e.key) {
99
+ case 'ArrowRight':
100
+ to = v + step() * flip;
101
+ break;
102
+ case 'ArrowLeft':
103
+ to = v - step() * flip;
104
+ break;
105
+ case 'ArrowUp':
106
+ to = v + step();
107
+ break;
108
+ case 'ArrowDown':
109
+ to = v - step();
110
+ break;
111
+ case 'PageUp':
112
+ to = v + pageStep();
113
+ break;
114
+ case 'PageDown':
115
+ to = v - pageStep();
116
+ break;
117
+ case 'Home':
118
+ to = lo;
119
+ exact = true;
120
+ break;
121
+ case 'End':
122
+ to = hi;
123
+ exact = true;
124
+ break;
125
+ default:
126
+ return;
127
+ }
128
+ e.preventDefault();
129
+ if (moveTo(i, to, exact))
130
+ emit('fs-change');
131
+ }
132
+ // Pointer: a press on the track moves the nearer thumb there and starts a drag; a press on a
133
+ // thumb grabs it where it was pressed (no jump). Pointer capture keeps the moves coming.
134
+ let drag = null;
135
+ const valueAt = (clientX) => {
136
+ const rect = track.getBoundingClientRect();
137
+ if (rect.width <= 0)
138
+ return null;
139
+ let frac = clamp((clientX - rect.left) / rect.width, 0, 1);
140
+ if (isRtl())
141
+ frac = 1 - frac;
142
+ return opts.min + frac * (opts.max - opts.min);
143
+ };
144
+ /** The thumb a press at `at` moves, or `null` while two stacked thumbs wait for a direction. */
145
+ function nearest(at) {
146
+ if (!isRange)
147
+ return 0;
148
+ const [a, b] = values;
149
+ if (a === b)
150
+ return at > a ? 1 : at < a ? 0 : null;
151
+ const da = Math.abs(at - a);
152
+ const db = Math.abs(at - b);
153
+ return db < da ? 1 : 0;
154
+ }
155
+ function onPointerDown(e) {
156
+ if (drag || e.button !== 0 || e.target.closest?.('.fs-slider__value'))
157
+ return;
158
+ const at = valueAt(e.clientX);
159
+ if (at === null)
160
+ return;
161
+ const hit = thumbs.findIndex((t) => t === e.target || t.contains(e.target));
162
+ const stacked = isRange && values[0] === values[1];
163
+ let i = hit >= 0 && !stacked ? hit : nearest(at);
164
+ const pending = i === null || (hit >= 0 && stacked);
165
+ if (i === null)
166
+ i = 0;
167
+ if (isDisabled(thumbs[i]))
168
+ return;
169
+ e.preventDefault();
170
+ let offset = 0;
171
+ if (hit >= 0) {
172
+ const r = thumbs[hit].getBoundingClientRect();
173
+ offset = e.clientX - (r.left + r.width / 2);
174
+ }
175
+ drag = { i, pointerId: e.pointerId, offset, start: [...values], pending };
176
+ thumbs[i].focus({ preventScroll: true });
177
+ try {
178
+ root.setPointerCapture?.(e.pointerId);
179
+ }
180
+ catch {
181
+ // A synthetic or ended pointer can't be captured: the drag still follows root's events.
182
+ }
183
+ thumbs[i].classList.add(DRAGGING);
184
+ if (hit < 0 && !pending)
185
+ moveTo(i, at);
186
+ }
187
+ function onPointerMove(e) {
188
+ if (!drag || e.pointerId !== drag.pointerId)
189
+ return;
190
+ const at = valueAt(e.clientX - drag.offset);
191
+ if (at === null)
192
+ return;
193
+ if (drag.pending) {
194
+ const v = values[0];
195
+ if (snap(at) === v)
196
+ return;
197
+ const i = at > v ? 1 : 0;
198
+ thumbs[drag.i].classList.remove(DRAGGING);
199
+ drag.i = i;
200
+ drag.pending = false;
201
+ thumbs[i].classList.add(DRAGGING);
202
+ thumbs[i].focus({ preventScroll: true });
203
+ }
204
+ moveTo(drag.i, at);
205
+ }
206
+ function endDrag(silent = false) {
207
+ if (!drag)
208
+ return;
209
+ const { i, pointerId, start } = drag;
210
+ drag = null;
211
+ thumbs[i].classList.remove(DRAGGING);
212
+ try {
213
+ if (root.hasPointerCapture?.(pointerId))
214
+ root.releasePointerCapture(pointerId);
215
+ }
216
+ catch {
217
+ // Already released.
218
+ }
219
+ if (!silent && values.some((v, n) => v !== start[n]))
220
+ emit('fs-change');
221
+ }
222
+ function onPointerEnd(e) {
223
+ if (drag && e.pointerId === drag.pointerId)
224
+ endDrag();
225
+ }
226
+ root.addEventListener('keydown', onKeydown);
227
+ root.addEventListener('pointerdown', onPointerDown);
228
+ root.addEventListener('pointermove', onPointerMove);
229
+ root.addEventListener('pointerup', onPointerEnd);
230
+ root.addEventListener('pointercancel', onPointerEnd);
231
+ root.addEventListener('lostpointercapture', onPointerEnd);
232
+ render();
233
+ return {
234
+ get value() {
235
+ return (isRange ? [values[0], values[1]] : values[0]);
236
+ },
237
+ setValue(value) {
238
+ values = normalise(value);
239
+ render();
240
+ },
241
+ update(next = {}) {
242
+ opts = { ...opts, ...next };
243
+ values = normalise((isRange ? values : values[0]));
244
+ render();
245
+ },
246
+ destroy() {
247
+ endDrag(true);
248
+ root.removeEventListener('keydown', onKeydown);
249
+ root.removeEventListener('pointerdown', onPointerDown);
250
+ root.removeEventListener('pointermove', onPointerMove);
251
+ root.removeEventListener('pointerup', onPointerEnd);
252
+ root.removeEventListener('pointercancel', onPointerEnd);
253
+ root.removeEventListener('lostpointercapture', onPointerEnd);
254
+ },
255
+ };
256
+ }