@twistedandy/better-carousel 1.0.0 → 1.1.1

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.
@@ -54,6 +54,17 @@ export function cleanStyle(element) {
54
54
  }
55
55
  }
56
56
 
57
+ /**
58
+ * Make a function that adds or removes event listeners on a target.
59
+ *
60
+ * @param {EventTarget} target
61
+ * @param {Array<Array>} list [name, handler, options] for each listener.
62
+ * @returns {(on?: boolean) => void} With true, it adds the listeners. Without a value, it removes them.
63
+ */
64
+ export function bind(target, list) {
65
+ return (on) => list.forEach(([name, handler, options]) => target[on ? 'addEventListener' : 'removeEventListener'](name, handler, options));
66
+ }
67
+
57
68
  /**
58
69
  * Make an element.
59
70
  *
@@ -69,6 +80,24 @@ export function create(tag, className) {
69
80
  return element;
70
81
  }
71
82
 
83
+ /**
84
+ * Make a control button of a carousel.
85
+ *
86
+ * @param {string} className
87
+ * @param {HTMLElement} container The container of the slides, which the button controls.
88
+ * @param {string} label The aria-label. An empty label adds no attribute.
89
+ * @param {() => void} click
90
+ * @returns {HTMLButtonElement}
91
+ */
92
+ export function createButton(className, container, label, click) {
93
+ const element = create('button', className);
94
+ element.type = 'button';
95
+ setAttribute(element, 'aria-label', label);
96
+ element.setAttribute('aria-controls', container.id);
97
+ element.addEventListener('click', click);
98
+ return element;
99
+ }
100
+
72
101
  /**
73
102
  * Find the element of an option, such as "arrows", "dots" or "sync". true gives the root, and false gives null.
74
103
  * 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.
@@ -208,15 +237,18 @@ const controls = 'a[href],button,input,select,textarea,[tabindex],[role]';
208
237
  // 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
238
  const generic = 'div,span,section';
210
239
 
240
+ // The elements that never show, so they are not slides
241
+ const skipped = new Set(['template', 'script', 'style']);
242
+
211
243
  /**
212
- * Get the slides of a container. The clones that the library made are not slides.
244
+ * Get the slides of a container. The clones that the library made, and the template, script and style elements, are not slides.
213
245
  *
214
246
  * @param {HTMLElement} container
215
247
  * @param {string} [selector] The "slides" option.
216
248
  * @returns {HTMLElement[]}
217
249
  */
218
250
  export function readSlides(container, selector) {
219
- return [...(selector ? container.querySelectorAll(selector) : container.children)].filter((node) => !made.has(node));
251
+ return [...(selector ? container.querySelectorAll(selector) : container.children)].filter((node) => !made.has(node) && !skipped.has(node.localName));
220
252
  }
221
253
 
222
254
  /**
@@ -230,12 +262,9 @@ export function readSlides(container, selector) {
230
262
  export function copySlides(slides, count, className) {
231
263
  const list = [];
232
264
 
233
- for (let copy = 0; copy < count; copy++) {
265
+ for (let pass = 0; pass < count; pass++) {
234
266
  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
- }
267
+ const clone = copy(node);
239
268
  clone.setAttribute('aria-hidden', 'true');
240
269
  clone.inert = true;
241
270
  clone.style.translate = '';
@@ -249,6 +278,25 @@ export function copySlides(slides, count, className) {
249
278
  return list;
250
279
  }
251
280
 
281
+ // Copy a node with its content. An id must be unique in the page, so the copy has no ids.
282
+ function copy(node) {
283
+ const result = node.cloneNode(true);
284
+ for (const item of [result, ...result.querySelectorAll('[id]')]) {
285
+ item.removeAttribute('id');
286
+ }
287
+ return result;
288
+ }
289
+
290
+ /**
291
+ * Copy the content of a slide into its clone again.
292
+ *
293
+ * @param {HTMLElement} clone
294
+ * @param {HTMLElement} node The slide.
295
+ */
296
+ export function copyContent(clone, node) {
297
+ clone.replaceChildren(...copy(node).childNodes);
298
+ }
299
+
252
300
  /**
253
301
  * 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
302
  *
@@ -2,6 +2,7 @@
2
2
  * Motion: the easing, the duration of a goToSnap() motion, and the motion engine.
3
3
  */
4
4
 
5
+ import { abs } from './geometry.js';
5
6
  import { steps } from './loop.js';
6
7
 
7
8
  // The easing of a goToSnap() motion
@@ -30,10 +31,10 @@ export function bezier([x1, y1, x2, y2]) {
30
31
  for (let i = 0; i < 6; i++) {
31
32
  const error = axis(x1, x2, t) - x,
32
33
  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
+ if (abs(error) < 1e-5) {
34
35
  return axis(y1, y2, t);
35
36
  }
36
- if (Math.abs(slope) < 1e-6) {
37
+ if (abs(slope) < 1e-6) {
37
38
  break;
38
39
  }
39
40
  t -= error / slope;
@@ -1,209 +1,200 @@
1
- /*
2
- * Navigation: the arrows, the dots, and the link to another carousel (the sync option).
3
- *
4
- * Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
5
- */
6
-
7
- import { find } from './carousel.js';
8
- import { create, optionElement, setAttribute, setClass } from './markup.js';
9
-
10
- /**
11
- * Make the arrows and the dots of a carousel. They update on the carousel events.
12
- *
13
- * @param {object} context What the features share. See carousel.js.
14
- * @returns {{remove: () => void}|undefined} remove() removes the arrows and the dots.
15
- */
16
- export function nav(context) {
17
- const { api, root, cls, options } = context,
18
- labels = options.labels,
19
- arrows = optionElement(options.arrows, root),
20
- box = optionElement(options.dots, root),
21
- buttons = [],
22
- dots = [],
23
- // The window of 5 dots, or all dots with dotsStyle: 'all'
24
- windowed = options.dotsStyle !== 'all',
25
- // The window of the dots, the track that slides in it, and the marker of the selected dot
26
- list = box && create('div', windowed ? cls.dots : cls.dots + ' ' + cls.dotsAll),
27
- track = list && create('div', cls.dotsTrack);
28
-
29
- let marks = new Map();
30
-
31
- if (!arrows && !box) {
32
- return;
33
- }
34
-
35
- // Add the window of the dots now: its CSS height is fixed, so the dots that the first measure adds do not shift the page
36
- if (list) {
37
- track.append(create('span', cls.dotsMarker));
38
- list.append(track);
39
- box.append(list);
40
- }
41
-
42
- if (arrows) {
43
- [['prev', 'goToPrev'], ['next', 'goToNext']].forEach(([key, method]) => {
44
- const button = create('button', cls.button + ' ' + cls[key + 'Button']);
45
- button.type = 'button';
46
- button.setAttribute('aria-label', labels[key]);
47
- button.setAttribute('aria-controls', context.container.id);
48
- button.addEventListener('click', () => api[method]());
49
- buttons.push(button);
50
- });
51
- }
52
-
53
- function update() {
54
- const fit = api.isFit(),
55
- count = fit ? 0 : api.snapProgress().length,
56
- selected = api.selectedSnap();
57
-
58
- buttons.forEach((button, index) => {
59
- if (fit) {
60
- button.remove();
61
- } else {
62
- if (!button.isConnected) {
63
- // Before the dots, for the tab order
64
- list?.parentNode === arrows ? list.before(button) : arrows.append(button);
65
- }
66
- const disabled = !(index ? api.canGoToNext() : api.canGoToPrev());
67
- if (button.disabled !== disabled) {
68
- button.disabled = disabled;
69
- }
70
- }
71
- });
72
-
73
- if (!list) {
74
- return;
75
- }
76
-
77
- if (count < 2) {
78
- list.remove();
79
- return;
80
- }
81
-
82
- while (dots.length > count) {
83
- dots.pop().remove();
84
- marks.delete(dots.length);
85
- }
86
-
87
- while (dots.length < count) {
88
- const dot = create('button', cls.dot),
89
- index = dots.length;
90
- dot.type = 'button';
91
- dot.setAttribute('aria-label', labels.dot.replace('%d', index + 1));
92
- dot.setAttribute('aria-controls', context.container.id);
93
- // The window of the dots hides the dots out of the zoom: keep them out of the tab order
94
- if (windowed) {
95
- dot.tabIndex = -1;
96
- }
97
- dot.addEventListener('click', () => api.goToSnap(index));
98
- dots.push(dot);
99
- track.append(dot);
100
- }
101
-
102
- if (!list.isConnected) {
103
- box.append(list);
104
- }
105
-
106
- // The zoom effect: the 5 dots around the selected dot get state classes
107
- const next = new Map();
108
-
109
- ['first', 'prev', 'current', 'next', 'last'].forEach((key, offset) => {
110
- if (dots[selected + offset - 2]) {
111
- next.set(selected + offset - 2, cls[key]);
112
- }
113
- });
114
-
115
- marks.forEach((name, index) => {
116
- if (next.get(index) !== name) {
117
- setClass(dots[index], name, false);
118
- setAttribute(dots[index], 'aria-current', false);
119
- dots[index].tabIndex = windowed ? -1 : 0;
120
- }
121
- });
122
-
123
- next.forEach((name, index) => {
124
- setClass(dots[index], name, true);
125
- setAttribute(dots[index], 'aria-current', index === selected && 'true');
126
- dots[index].tabIndex = 0;
127
- });
128
-
129
- marks = next;
130
-
131
- // Center the group of up to 5 dots in the window of the dots, and move the marker to the selected dot. The CSS moves the track and the marker with "translate".
132
- if (windowed) {
133
- variable('--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
134
- }
135
- variable('--better-dot', selected);
136
- }
137
-
138
- // Set a CSS variable on the window of the dots, if its value changes
139
- function variable(name, value) {
140
- if (list.style.getPropertyValue(name) !== String(value)) {
141
- list.style.setProperty(name, value);
142
- }
143
- }
144
-
145
- ['init', 'reinit', 'resize', 'select', 'slideschanged'].forEach((name) => context.on(name, update));
146
-
147
- return {
148
- remove() {
149
- buttons.forEach((button) => button.remove());
150
- list?.remove();
151
- }
152
- };
153
- }
154
-
155
- /**
156
- * Connect a carousel to another carousel with the same slides, such as thumbnails to a main gallery. This carousel follows the slide
157
- * that the other carousel selects. Only a click on a slide of this carousel selects that slide in the other carousel: a drag does not.
158
- *
159
- * @param {object} context What the features share. See carousel.js. The "sync" option is the other carousel, its container or a selector.
160
- * @returns {{remove: () => void}|undefined} remove() disconnects the carousels.
161
- */
162
- export function sync(context) {
163
- const { api, container } = context,
164
- target = context.options.sync;
165
-
166
- let other = null;
167
-
168
- if (!target) {
169
- return;
170
- }
171
-
172
- // Show the slide that the other carousel selects
173
- function show(instant) {
174
- const index = other.selectedSlide();
175
- context.follow(index);
176
- api.goToSlide(index, instant === true);
177
- }
178
-
179
- function click(event) {
180
- // The slide or the clone that gets the click, and then its original slide
181
- const index = context.nodes().findIndex((node) => node.contains(event.target));
182
- if (other && index > -1) {
183
- other.goToSlide(index % api.slideNodes().length);
184
- }
185
- }
186
-
187
- // The other carousel can come later than this one, so find it at the init
188
- function connect() {
189
- if (other) {
190
- return;
191
- }
192
- other = target.goToSnap ? target : find(typeof target === 'string' ? optionElement(target, context.root) : target);
193
- if (other) {
194
- other.on('select', show);
195
- show(true);
196
- }
197
- }
198
-
199
- context.on('init', connect);
200
- context.on('reinit', connect);
201
- container.addEventListener('click', click);
202
-
203
- return {
204
- remove() {
205
- other?.off('select', show);
206
- container.removeEventListener('click', click);
207
- }
208
- };
209
- }
1
+ /*
2
+ * Navigation: the arrows, the dots, and the link to another carousel (the sync option).
3
+ *
4
+ * Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
5
+ */
6
+
7
+ import { find } from './carousel.js';
8
+ import { bind, create, createButton, optionElement, setAttribute, setClass } from './markup.js';
9
+
10
+ /**
11
+ * Make the arrows and the dots of a carousel. They update on the carousel events.
12
+ *
13
+ * @param {object} context What the features share. See carousel.js.
14
+ * @returns {{remove: () => void}|undefined} remove() removes the arrows and the dots.
15
+ */
16
+ export function nav(context) {
17
+ const { api, root, cls, options } = context,
18
+ labels = options.labels,
19
+ arrows = optionElement(options.arrows, root),
20
+ box = optionElement(options.dots, root),
21
+ buttons = [],
22
+ dots = [],
23
+ // The window of 5 dots, or all dots with dotsStyle: 'all'
24
+ windowed = options.dotsStyle !== 'all',
25
+ // The window of the dots, the track that slides in it, and the marker of the selected dot
26
+ list = box && create('div', windowed ? cls.dots : cls.dots + ' ' + cls.dotsAll),
27
+ track = list && create('div', cls.dotsTrack);
28
+
29
+ let marks = new Map();
30
+
31
+ if (!arrows && !box) {
32
+ return;
33
+ }
34
+
35
+ // Add the window of the dots now: its CSS height is fixed, so the dots that the first measure adds do not shift the page
36
+ if (list) {
37
+ track.append(create('span', cls.dotsMarker));
38
+ list.append(track);
39
+ box.append(list);
40
+ }
41
+
42
+ if (arrows) {
43
+ buttons.push(createButton(cls.button + ' ' + cls.prevButton, context.container, labels.prev, () => api.goToPrev()), createButton(cls.button + ' ' + cls.nextButton, context.container, labels.next, () => api.goToNext()));
44
+ }
45
+
46
+ function update() {
47
+ const fit = api.isFit(),
48
+ count = fit ? 0 : api.snapProgress().length,
49
+ selected = api.selectedSnap();
50
+
51
+ buttons.forEach((item, index) => {
52
+ if (fit) {
53
+ item.remove();
54
+ } else {
55
+ if (!item.isConnected) {
56
+ // Before the dots, for the tab order
57
+ list?.parentNode === arrows ? list.before(item) : arrows.append(item);
58
+ }
59
+ const disabled = !(index ? api.canGoToNext() : api.canGoToPrev());
60
+ if (item.disabled !== disabled) {
61
+ item.disabled = disabled;
62
+ }
63
+ }
64
+ });
65
+
66
+ if (!list) {
67
+ return;
68
+ }
69
+
70
+ if (count < 2) {
71
+ list.remove();
72
+ return;
73
+ }
74
+
75
+ while (dots.length > count) {
76
+ dots.pop().remove();
77
+ marks.delete(dots.length);
78
+ }
79
+
80
+ while (dots.length < count) {
81
+ const index = dots.length,
82
+ dot = createButton(cls.dot, context.container, labels.dot.replace('%d', index + 1), () => api.goToSnap(index));
83
+ // The window of the dots hides the dots out of the zoom: keep them out of the tab order
84
+ if (windowed) {
85
+ dot.tabIndex = -1;
86
+ }
87
+ dots.push(dot);
88
+ track.append(dot);
89
+ }
90
+
91
+ if (!list.isConnected) {
92
+ box.append(list);
93
+ }
94
+
95
+ // The zoom effect: the 5 dots around the selected dot get state classes
96
+ const next = new Map();
97
+
98
+ ['first', 'prev', 'current', 'next', 'last'].forEach((key, offset) => {
99
+ if (dots[selected + offset - 2]) {
100
+ next.set(selected + offset - 2, cls[key]);
101
+ }
102
+ });
103
+
104
+ marks.forEach((name, index) => {
105
+ if (next.get(index) !== name) {
106
+ setClass(dots[index], name, false);
107
+ setAttribute(dots[index], 'aria-current', false);
108
+ dots[index].tabIndex = windowed ? -1 : 0;
109
+ }
110
+ });
111
+
112
+ next.forEach((name, index) => {
113
+ setClass(dots[index], name, true);
114
+ setAttribute(dots[index], 'aria-current', index === selected && 'true');
115
+ dots[index].tabIndex = 0;
116
+ });
117
+
118
+ marks = next;
119
+
120
+ // Center the group of up to 5 dots in the window of the dots, and move the marker to the selected dot. The CSS moves the track and the marker with "translate".
121
+ if (windowed) {
122
+ variable('--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
123
+ }
124
+ variable('--better-dot', selected);
125
+ }
126
+
127
+ // Set a CSS variable on the window of the dots, if its value changes
128
+ function variable(name, value) {
129
+ if (list.style.getPropertyValue(name) !== String(value)) {
130
+ list.style.setProperty(name, value);
131
+ }
132
+ }
133
+
134
+ ['init', 'reinit', 'resize', 'select', 'slideschanged'].forEach((name) => context.on(name, update));
135
+
136
+ return {
137
+ remove() {
138
+ buttons.forEach((item) => item.remove());
139
+ list?.remove();
140
+ }
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Connect a carousel to another carousel with the same slides, such as thumbnails to a main gallery. This carousel follows the slide
146
+ * that the other carousel selects. Only a click on a slide of this carousel selects that slide in the other carousel: a drag does not.
147
+ *
148
+ * @param {object} context What the features share. See carousel.js. The "sync" option is the other carousel, its container or a selector.
149
+ * @returns {{remove: () => void}|undefined} remove() disconnects the carousels.
150
+ */
151
+ export function sync(context) {
152
+ const { api, container } = context,
153
+ target = context.options.sync;
154
+
155
+ let other = null;
156
+
157
+ if (!target) {
158
+ return;
159
+ }
160
+
161
+ // Show the slide that the other carousel selects
162
+ function show(instant) {
163
+ const index = other.selectedSlide();
164
+ context.follow(index);
165
+ api.goToSlide(index, instant === true);
166
+ }
167
+
168
+ function click(event) {
169
+ // The slide or the clone that gets the click, and then its original slide
170
+ const index = context.nodes().findIndex((node) => node.contains(event.target));
171
+ if (other && index > -1) {
172
+ other.goToSlide(index % api.slideNodes().length);
173
+ }
174
+ }
175
+
176
+ // The other carousel can come later than this one, so find it at the init
177
+ function connect() {
178
+ if (other) {
179
+ return;
180
+ }
181
+ other = target.goToSnap ? target : find(typeof target === 'string' ? optionElement(target, context.root) : target);
182
+ if (other) {
183
+ other.on('select', show);
184
+ show(true);
185
+ }
186
+ }
187
+
188
+ context.on('init', connect);
189
+ context.on('reinit', connect);
190
+ const listen = bind(container, [['click', click]]);
191
+
192
+ listen(true);
193
+
194
+ return {
195
+ remove() {
196
+ other?.off('select', show);
197
+ listen();
198
+ }
199
+ };
200
+ }