@twistedandy/better-carousel 0.0.0-stage → 1.0.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,83 @@
1
+ /*
2
+ * Loop math: the period, the clones and the place of each slide. This module does not use the DOM.
3
+ *
4
+ * The values and the slides are the same as in geometry.js. In loop mode, each slide is at start + k * period.
5
+ * The library writes k * period as the translate of the slide.
6
+ */
7
+
8
+ /**
9
+ * Get the number of full copies of the slides that the loop needs. With 0, the slides can loop with no clones:
10
+ * no slide is necessary at two places at the same time.
11
+ *
12
+ * @param {number} length The loop period of the original slides.
13
+ * @param {number} view
14
+ * @param {number} max
15
+ * @returns {number}
16
+ */
17
+ export function cloneCount(length, view, max) {
18
+ return length > 0 ? Math.max(0, Math.ceil((view + max) / length) - 1) : 0;
19
+ }
20
+
21
+ /**
22
+ * Get the k of each slide for a motion from one location to another. With from = to, it is the placement at rest.
23
+ * The slide center goes into a window of one period. The window has the same center as the part of the content that shows during the motion.
24
+ *
25
+ * @param {Array<{start: number, end: number}>} slides
26
+ * @param {number} from
27
+ * @param {number} to
28
+ * @param {number} view The size of the visible area.
29
+ * @param {number} length The loop period.
30
+ * @param {number} [offset] The start of the visible area, relative to the viewport start.
31
+ * @returns {number[]}
32
+ */
33
+ export function placement(slides, from, to, view, length, offset = 0) {
34
+ const center = offset + (view - from - to) / 2;
35
+ return slides.map((slide) => Math.round((center - (slide.start + slide.end) / 2) / length) || 0);
36
+ }
37
+
38
+ /**
39
+ * Find if one placement is correct for the full motion. If not, the motion must change the placement during the motion.
40
+ *
41
+ * @param {Array<{start: number, end: number}>} slides
42
+ * @param {number} from
43
+ * @param {number} to
44
+ * @param {number} view
45
+ * @param {number} length
46
+ * @returns {boolean}
47
+ */
48
+ export function pathFits(slides, from, to, view, length) {
49
+ const path = view + Math.abs(to - from);
50
+ return slides.every((slide) => length >= path + slide.end - slide.start);
51
+ }
52
+
53
+ /**
54
+ * Get the steps of each slide for an auto scroll iteration. The container moves by one period, from `from` to `from - length` (forward)
55
+ * or to `from + length` (back). Each slide moves by one period at one time in the iteration.
56
+ *
57
+ * @param {Array<{start: number, end: number}>} slides
58
+ * @param {number} from
59
+ * @param {number} view
60
+ * @param {number} length
61
+ * @param {number} direction 1 for forward, -1 for back.
62
+ * @param {number} [offset] The start of the visible area, relative to the viewport start.
63
+ * @returns {Array<{k: number, offset: number}>} k at the start of the iteration, and the time of the step, from 0 to 1.
64
+ */
65
+ export function steps(slides, from, view, length, direction, offset = 0) {
66
+ return slides.map((slide) => {
67
+ const value = (offset + view / 2 - from - (slide.start + slide.end) / 2) / length,
68
+ k = Math.round(value);
69
+
70
+ return { k, offset: direction > 0 ? k + 0.5 - value : value - k + 0.5 };
71
+ });
72
+ }
73
+
74
+ /**
75
+ * Put a location into the range (-length, 0].
76
+ *
77
+ * @param {number} location
78
+ * @param {number} length
79
+ * @returns {number}
80
+ */
81
+ export function normalize(location, length) {
82
+ return location - Math.ceil(location / length) * length;
83
+ }
@@ -0,0 +1,268 @@
1
+ /*
2
+ * Markup: the wrapper, the slides, the clones, the ARIA attributes, and the helpers that write to the DOM.
3
+ *
4
+ * The helpers that set a value write only when the value changes. restore() removes all that the library added.
5
+ */
6
+
7
+ /**
8
+ * Add or remove a class.
9
+ *
10
+ * @param {Element} element
11
+ * @param {string} name An empty name does nothing.
12
+ * @param {boolean} on
13
+ */
14
+ export function setClass(element, name, on) {
15
+ if (name && element.classList.contains(name) !== !!on) {
16
+ element.classList.toggle(name, !!on);
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Set an attribute, or remove it if the value is false.
22
+ *
23
+ * @param {Element} element
24
+ * @param {string} name
25
+ * @param {string|false} value
26
+ */
27
+ export function setAttribute(element, name, value) {
28
+ if (element.getAttribute(name) !== (value || null)) {
29
+ value ? element.setAttribute(name, value) : element.removeAttribute(name);
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Set an inline style property.
35
+ *
36
+ * @param {HTMLElement} element
37
+ * @param {string} name
38
+ * @param {string} value An empty string removes the property.
39
+ */
40
+ export function setStyle(element, name, value) {
41
+ if (element.style[name] !== value) {
42
+ element.style[name] = value;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Remove an empty style attribute that the library left.
48
+ *
49
+ * @param {Element} element
50
+ */
51
+ export function cleanStyle(element) {
52
+ if (element.getAttribute('style') === '') {
53
+ element.removeAttribute('style');
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Make an element.
59
+ *
60
+ * @param {string} tag
61
+ * @param {string} className
62
+ * @returns {HTMLElement}
63
+ */
64
+ export function create(tag, className) {
65
+ const element = document.createElement(tag);
66
+ if (className) {
67
+ element.className = className;
68
+ }
69
+ return element;
70
+ }
71
+
72
+ /**
73
+ * Find the element of an option, such as "arrows", "dots" or "sync". true gives the root, and false gives null.
74
+ * The library searches for a selector in the root and then in each parent of the root, so that it finds a heading in the section of the carousel.
75
+ *
76
+ * @param {boolean|string|Element} value The option value.
77
+ * @param {HTMLElement} root
78
+ * @returns {Element|null}
79
+ */
80
+ export function optionElement(value, root) {
81
+ if (typeof value === 'string') {
82
+ for (let node = root; node; node = node.parentElement) {
83
+ const found = node.querySelector(value);
84
+ if (found) {
85
+ return found;
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+ return value === true ? root : value || null;
91
+ }
92
+
93
+ // The attributes and the classes that the library added: element => names
94
+ const marked = new WeakMap(),
95
+ added = new WeakMap();
96
+
97
+ /**
98
+ * Set an attribute that the page did not set. restore() removes it.
99
+ *
100
+ * @param {Element} node
101
+ * @param {string} name
102
+ * @param {string} value
103
+ */
104
+ export function own(node, name, value) {
105
+ const list = marked.get(node) || new Set();
106
+ if (list.has(name) || !node.hasAttribute(name)) {
107
+ list.add(name);
108
+ marked.set(node, list);
109
+ if (node.getAttribute(name) !== value) {
110
+ node.setAttribute(name, value);
111
+ }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Add a class that the element does not have. restore() removes it.
117
+ *
118
+ * @param {Element} node
119
+ * @param {string} name An empty name does nothing.
120
+ */
121
+ export function addClass(node, name) {
122
+ if (name && !node.classList.contains(name)) {
123
+ const list = added.get(node) || new Set();
124
+ node.classList.add(name);
125
+ list.add(name);
126
+ added.set(node, list);
127
+ }
128
+ }
129
+
130
+ // The elements that the library made: the wrapper and the clones
131
+ const made = new WeakSet();
132
+
133
+ // A counter for container ids
134
+ let uid = 0;
135
+
136
+ /**
137
+ * Find or make the root, the viewport and the container of a carousel. Then add their classes and the ARIA attributes of the
138
+ * carousel pattern of the WAI-ARIA Authoring Practices. A new setup after reinit() uses the wrapper that the library made before.
139
+ *
140
+ * @param {HTMLElement} element The container of the slides, or its viewport.
141
+ * @param {object} options
142
+ * @param {object} cls The class names.
143
+ * @returns {{root: HTMLElement, viewport: HTMLElement, container: HTMLElement}}
144
+ */
145
+ export function build(element, options, cls) {
146
+ let container = options.container ? element.querySelector(options.container) : element;
147
+
148
+ if (container.classList.contains(cls.viewport)) {
149
+ container = container.firstElementChild;
150
+ }
151
+
152
+ let viewport = container.parentElement,
153
+ root = viewport.parentElement;
154
+
155
+ if (!made.has(viewport) && !viewport.classList.contains(cls.viewport) && options.wrapper) {
156
+ root = create('div');
157
+ viewport = create('div');
158
+ made.add(root).add(viewport);
159
+ container.before(root);
160
+ root.append(viewport);
161
+ viewport.append(container);
162
+ }
163
+
164
+ addClass(root, cls.root);
165
+ addClass(viewport, cls.viewport);
166
+ addClass(container, cls.container);
167
+
168
+ own(root, 'role', 'region');
169
+ own(root, 'aria-roledescription', 'carousel');
170
+ if (!root.hasAttribute('aria-labelledby')) {
171
+ own(root, 'aria-label', options.labels.carousel);
172
+ }
173
+ own(container, 'id', container.id || 'carousel-' + ++uid);
174
+ own(container, 'aria-live', 'polite');
175
+
176
+ return { root, viewport, container };
177
+ }
178
+
179
+ /**
180
+ * Remove the classes and the attributes that own() and addClass() added, an empty class attribute, and the wrapper that build() made.
181
+ *
182
+ * @param {HTMLElement} root
183
+ * @param {HTMLElement} viewport
184
+ * @param {HTMLElement} container
185
+ * @param {HTMLElement[]} slides
186
+ * @param {boolean} keep Keep the wrapper for a new setup.
187
+ */
188
+ export function restore(root, viewport, container, slides, keep) {
189
+ for (const node of [root, viewport, container, ...slides]) {
190
+ marked.get(node)?.forEach((name) => node.removeAttribute(name));
191
+ added.get(node)?.forEach((name) => node.classList.remove(name));
192
+ marked.delete(node);
193
+ added.delete(node);
194
+ if (node.getAttribute('class') === '') {
195
+ node.removeAttribute('class');
196
+ }
197
+ }
198
+
199
+ if (!keep && made.has(root)) {
200
+ root.before(container);
201
+ root.remove();
202
+ }
203
+ }
204
+
205
+ // Slides that are a control keep their own role and name
206
+ const controls = 'a[href],button,input,select,textarea,[tabindex],[role]';
207
+
208
+ // The slides that can get the "group" role. An element with its own role, such as an article or a list item, does not permit "group".
209
+ const generic = 'div,span,section';
210
+
211
+ /**
212
+ * Get the slides of a container. The clones that the library made are not slides.
213
+ *
214
+ * @param {HTMLElement} container
215
+ * @param {string} [selector] The "slides" option.
216
+ * @returns {HTMLElement[]}
217
+ */
218
+ export function readSlides(container, selector) {
219
+ return [...(selector ? container.querySelectorAll(selector) : container.children)].filter((node) => !made.has(node));
220
+ }
221
+
222
+ /**
223
+ * Make the clones: full copies of the slides, which the screen reader and the keyboard do not see.
224
+ *
225
+ * @param {HTMLElement[]} slides
226
+ * @param {number} count The number of copies of all slides.
227
+ * @param {string} className The class of a clone.
228
+ * @returns {HTMLElement[]}
229
+ */
230
+ export function copySlides(slides, count, className) {
231
+ const list = [];
232
+
233
+ for (let copy = 0; copy < count; copy++) {
234
+ for (const node of slides) {
235
+ const clone = node.cloneNode(true);
236
+ for (const item of [clone, ...clone.querySelectorAll('[id]')]) {
237
+ item.removeAttribute('id');
238
+ }
239
+ clone.setAttribute('aria-hidden', 'true');
240
+ clone.inert = true;
241
+ clone.style.translate = '';
242
+ setClass(clone, className, true);
243
+ cleanStyle(clone);
244
+ made.add(clone);
245
+ list.push(clone);
246
+ }
247
+ }
248
+
249
+ return list;
250
+ }
251
+
252
+ /**
253
+ * Give each slide the slide role and a name such as "2 of 8". A slide with its own role, such as an article, keeps it.
254
+ *
255
+ * @param {HTMLElement[]} slides
256
+ * @param {string} text The "slide" label, with %d for the slide number and %n for the number of slides.
257
+ */
258
+ export function labelSlides(slides, text) {
259
+ slides.forEach((node, index) => {
260
+ if (!node.matches(controls) || marked.get(node)?.has('role')) {
261
+ if (node.matches(generic)) {
262
+ own(node, 'role', 'group');
263
+ }
264
+ own(node, 'aria-roledescription', 'slide');
265
+ own(node, 'aria-label', text.replace('%d', index + 1).replace('%n', slides.length));
266
+ }
267
+ });
268
+ }
@@ -0,0 +1,232 @@
1
+ /*
2
+ * Motion: the easing, the duration of a goToSnap() motion, and the motion engine.
3
+ */
4
+
5
+ import { steps } from './loop.js';
6
+
7
+ // The easing of a goToSnap() motion
8
+ export const EASE = [0.25, 1, 0.5, 1];
9
+
10
+ // The easing of a glide after a free drag
11
+ export const GLIDE = [0.2, 0.6, 0.35, 1];
12
+
13
+ /**
14
+ * Make a cubic Bézier easing function, the same as the CSS cubic-bezier().
15
+ *
16
+ * @param {number[]} curve [x1, y1, x2, y2]
17
+ * @returns {(t: number) => number}
18
+ */
19
+ export function bezier([x1, y1, x2, y2]) {
20
+ const axis = (a, b, t) => ((1 + 3 * a - 3 * b) * t + 3 * b - 6 * a) * t * t + 3 * a * t;
21
+
22
+ return (x) => {
23
+ if (x <= 0 || x >= 1) {
24
+ return x <= 0 ? 0 : 1;
25
+ }
26
+
27
+ let t = x;
28
+
29
+ // Newton steps, then bisection if the slope is too small
30
+ for (let i = 0; i < 6; i++) {
31
+ const error = axis(x1, x2, t) - x,
32
+ slope = 3 * (1 + 3 * x1 - 3 * x2) * t * t + 2 * (3 * x2 - 6 * x1) * t + 3 * x1;
33
+ if (Math.abs(error) < 1e-5) {
34
+ return axis(y1, y2, t);
35
+ }
36
+ if (Math.abs(slope) < 1e-6) {
37
+ break;
38
+ }
39
+ t -= error / slope;
40
+ }
41
+
42
+ let low = 0,
43
+ high = 1;
44
+
45
+ t = x;
46
+
47
+ while (high - low > 1e-5) {
48
+ if (axis(x1, x2, t) < x) {
49
+ low = t;
50
+ } else {
51
+ high = t;
52
+ }
53
+ t = (low + high) / 2;
54
+ }
55
+
56
+ return axis(y1, y2, t);
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Get the duration of a goToSnap() motion.
62
+ *
63
+ * @param {number} duration The duration for one snap, in ms.
64
+ * @param {number} count The number of snaps to move.
65
+ * @returns {number}
66
+ */
67
+ export function snapDuration(duration, count) {
68
+ return count > 1 ? Math.min(2 * duration, duration * (1 + Math.log2(count))) : duration;
69
+ }
70
+
71
+ /**
72
+ * Make the motion engine of a carousel. A motion runs as a Web Animations API animation of the container translate, on the compositor.
73
+ * With raf set, it runs as a requestAnimationFrame loop instead, which calls frame() on each frame.
74
+ * A loop motion moves the container and the slides of a loop carousel at a constant speed, on the compositor, until it stops.
75
+ *
76
+ * @param {HTMLElement} element The container.
77
+ * @param {(location: number) => string} css Get the CSS translate value of a location.
78
+ * @param {(location: number) => void} frame Write a location.
79
+ * @param {() => void} done Called when a motion ends. A loop motion does not end.
80
+ * @param {((location: number) => void)|null} [tick] Called on each frame of a motion on the compositor, because such a motion runs no script.
81
+ * @returns {{run: Function, loop: Function, retarget: Function, stop: Function, current: Function, shifts: Function}}
82
+ */
83
+ export function animator(element, css, frame, done, tick) {
84
+ let state = null;
85
+
86
+ const time = () => state.animations ? state.animations[0].currentTime || 0 : performance.now() - state.start,
87
+ current = () => state && state.from + (state.to - state.from) * state.ease(time() / state.duration);
88
+
89
+ // The frame loop: a requestAnimationFrame motion writes the location, and a motion on the compositor calls tick().
90
+ // The next frame starts before the callback, so that a callback that stops the motion also stops the loop.
91
+ function step() {
92
+ if (!state.animations && time() >= state.duration) {
93
+ return finish();
94
+ }
95
+ state.raf = requestAnimationFrame(step);
96
+ (state.animations ? tick : frame)(current());
97
+ }
98
+
99
+ function finish() {
100
+ const to = state.to;
101
+ stop();
102
+ frame(to);
103
+ done();
104
+ }
105
+
106
+ /**
107
+ * Stop the motion.
108
+ *
109
+ * @returns {number|null} The location at the stop, or null if no motion runs.
110
+ */
111
+ function stop() {
112
+ const at = current();
113
+ if (state) {
114
+ state.animations?.forEach((animation) => animation.cancel());
115
+ cancelAnimationFrame(state.raf);
116
+ state = null;
117
+ }
118
+ return at;
119
+ }
120
+
121
+ function animate(at) {
122
+ const animation = element.animate([{ translate: css(state.from) }, { translate: css(state.to) }], { duration: state.duration, easing: 'cubic-bezier(' + state.curve + ')', fill: 'forwards' });
123
+ animation.currentTime = at;
124
+ animation.onfinish = finish;
125
+ state.animations = [animation];
126
+ }
127
+
128
+ /**
129
+ * Start a motion. It stops the motion that runs.
130
+ *
131
+ * @param {object} next The state of the new motion. script: true runs it as a requestAnimationFrame loop.
132
+ * @param {HTMLElement[]} [nodes] The slides of a loop motion.
133
+ */
134
+ function start(next, nodes) {
135
+ stop();
136
+ state = next;
137
+ if (next.list) {
138
+ const timing = { duration: next.duration, iterations: Infinity },
139
+ begin = document.timeline.currentTime,
140
+ { from, to, length, direction } = next;
141
+ next.animations = [
142
+ element.animate([{ translate: css(from) }, { translate: css(to) }], timing),
143
+ ...nodes.map((node, index) => {
144
+ const { k, offset } = next.list[index],
145
+ before = css(k * length),
146
+ after = css((k + direction) * length);
147
+ return node.animate([{ translate: before }, { translate: before, offset }, { translate: after, offset }, { translate: after }], timing);
148
+ })
149
+ ];
150
+ next.animations.forEach((animation) => animation.startTime = begin);
151
+ } else if (next.script) {
152
+ next.start = performance.now();
153
+ } else {
154
+ animate(0);
155
+ }
156
+ if (next.script || tick) {
157
+ next.raf = requestAnimationFrame(step);
158
+ }
159
+ }
160
+
161
+ return {
162
+ /**
163
+ * Start a motion to a location.
164
+ *
165
+ * @param {number} from
166
+ * @param {number} to
167
+ * @param {number} duration ms
168
+ * @param {number[]} curve The cubic Bézier easing.
169
+ * @param {boolean} raf Use a requestAnimationFrame loop.
170
+ */
171
+ run: (from, to, duration, curve, raf) => start({ from, to, duration, curve, script: raf, ease: bezier(curve) }),
172
+
173
+ /**
174
+ * Start a loop motion. The container moves by one period in each iteration, and each slide moves by one period
175
+ * at the time when it leaves the visible area.
176
+ *
177
+ * @param {number} from
178
+ * @param {number} direction 1 for forward, -1 for back.
179
+ * @param {number} duration The time of one iteration, in ms.
180
+ * @param {{slides: Array<{start: number, end: number}>, area: {start: number, size: number}, period: number}} geo
181
+ * @param {HTMLElement[]} nodes All slides, clones included.
182
+ */
183
+ loop: (from, direction, duration, geo, nodes) => start({
184
+ from,
185
+ to: from - direction * geo.period,
186
+ duration,
187
+ direction,
188
+ length: geo.period,
189
+ list: steps(geo.slides, from, geo.area.size, geo.period, direction, geo.area.start),
190
+ // The time in the iteration, from 0 to 1
191
+ ease: (value) => value % 1
192
+ }, nodes),
193
+
194
+ /**
195
+ * Change the end of the motion that runs. The start, the time and the easing stay, so the motion does not jump.
196
+ *
197
+ * @param {number} to
198
+ * @returns {boolean} false if no motion runs, or if a loop motion runs: it has no end.
199
+ */
200
+ retarget(to) {
201
+ if (!state || state.list) {
202
+ return false;
203
+ }
204
+ if (to !== state.to) {
205
+ state.to = to;
206
+ if (state.animations) {
207
+ const at = time();
208
+ state.animations[0].cancel();
209
+ animate(at);
210
+ }
211
+ }
212
+ return true;
213
+ },
214
+
215
+ stop,
216
+ current,
217
+
218
+ /**
219
+ * Get the translate values of the slides during a loop motion.
220
+ *
221
+ * @param {number} sign -1 for a right-to-left carousel.
222
+ * @returns {number[]|null} The values in px, or null if no loop motion runs.
223
+ */
224
+ shifts(sign) {
225
+ if (!state?.list) {
226
+ return null;
227
+ }
228
+ const phase = time() / state.duration % 1;
229
+ return state.list.map(({ k, offset }) => sign * (phase >= offset ? k + state.direction : k) * state.length);
230
+ }
231
+ };
232
+ }