@twistedandy/better-carousel 1.0.0 → 1.1.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.
@@ -45,35 +45,62 @@ export function readLayout(container, options) {
45
45
  }
46
46
 
47
47
  /**
48
- * Read the slide boxes on the main axis, relative to the viewport start at location 0.
48
+ * Read the slide boxes on the main axis, relative to the inner edge of the viewport padding at location 0. The snaps align to this edge.
49
+ * The values are in the px of the carousel: in a parent with a CSS scale, such as a modal window that opens with a scale animation, the
50
+ * values do not change with a scale or a rotation of a parent.
51
+ * A slide with no box, such as a slide with display: none, is hidden. It gets no snap, and it stays at the end of the slide before it.
49
52
  *
50
53
  * @param {HTMLElement} viewport
51
54
  * @param {HTMLElement[]} nodes All slides, clones included.
52
55
  * @param {object} layout The result of readLayout().
53
56
  * @param {{axis: string, container: number, slides: number[]}} written The translate values that the library wrote, in px on the screen.
54
- * @returns {{view: number, slides: Array<{start: number, end: number, cross: number}>, gap: number}}
55
- * gap is the loop gap: the space between the last slide and the next copy of the first slide.
57
+ * @returns {{view: number, slides: Array<{start: number, end: number, cross: number, hidden: boolean}>, gap: number, scale: number, pad: {start: number, end: number}}}
58
+ * view is the viewport size without the padding. gap is the loop gap: the space between the last slide and the next copy of the first slide.
59
+ * scale is the screen px of one px of the carousel. pad is the viewport padding at the start and at the end.
56
60
  */
57
61
  export function readRects(viewport, nodes, layout, written) {
58
62
  const box = viewport.getBoundingClientRect(),
59
63
  x = layout.axis === 'x',
60
64
  sign = layout.sign,
61
65
  known = written.axis === layout.axis,
62
- shift = known ? written.container : 0;
63
-
64
- let first = 0,
65
- last = 0;
66
+ shift = known ? written.container : 0,
67
+ width = viewport.offsetWidth,
68
+ height = viewport.offsetHeight,
69
+ // offsetWidth is a whole number: a difference of less than 1 px is not a transform
70
+ transformed = width && height && (Math.abs(box.width - width) >= 1 || Math.abs(box.height - height) >= 1),
71
+ // A scale s and a rotation by an angle a give a box of s(w cos a + h sin a) by s(w sin a + h cos a). The main axis gets s cos a.
72
+ scale = !transformed ? 1 : Math.abs(width - height) > 1 ? (width * box.width - height * box.height) / (width * width - height * height) : box.width / width,
73
+ view = !transformed ? (x ? box.width : box.height) : x ? width : height,
74
+ style = getComputedStyle(viewport),
75
+ [before, after] = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'],
76
+ pad = { start: parseFloat(style['padding' + before]) || 0, end: parseFloat(style['padding' + after]) || 0 };
66
77
 
67
78
  const slides = nodes.map((node, index) => {
68
79
  const rect = node.getBoundingClientRect(),
69
80
  offset = sign * (shift + (known && written.slides[index] || 0)),
70
- start = (x ? (layout.rtl ? box.right - rect.right : rect.left - box.left) : rect.top - box.top) - offset,
71
- size = x ? rect.width : rect.height;
81
+ start = (x ? (layout.rtl ? box.right - rect.right : rect.left - box.left) : rect.top - box.top) / scale - pad.start - offset,
82
+ size = (x ? rect.width : rect.height) / scale;
72
83
 
73
- return { start, end: start + size, cross: x ? rect.height : rect.width };
84
+ return { start, end: start + size, cross: (x ? rect.height : rect.width) / scale, hidden: !rect.width && !rect.height };
74
85
  });
75
86
 
87
+ let edge = slides.find((slide) => !slide.hidden)?.start || 0;
88
+
89
+ for (const slide of slides) {
90
+ if (slide.hidden) {
91
+ slide.start = slide.end = edge;
92
+ } else {
93
+ edge = slide.end;
94
+ }
95
+ }
96
+
97
+ let first = Math.max(0, slides.findIndex((slide) => !slide.hidden)),
98
+ last = first;
99
+
76
100
  slides.forEach((slide, index) => {
101
+ if (slide.hidden) {
102
+ return;
103
+ }
77
104
  if (slide.start < slides[first].start) {
78
105
  first = index;
79
106
  }
@@ -90,9 +117,11 @@ export function readRects(viewport, nodes, layout, written) {
90
117
  }
91
118
 
92
119
  return {
93
- view: x ? box.width : box.height,
120
+ view: view - pad.start - pad.end,
94
121
  slides,
95
- gap
122
+ gap,
123
+ scale,
124
+ pad
96
125
  };
97
126
  }
98
127
 
@@ -107,46 +136,70 @@ export function windowSize(axis) {
107
136
  }
108
137
 
109
138
  /**
110
- * Get the part of the main axis where the loop must show slides, relative to the viewport start.
111
- * It is the viewport. With clones: 'fill', it is the window, so that the slides fill it when the viewport overflow shows.
139
+ * Get the part of the main axis where the loop must show slides, relative to the inner edge of the viewport padding.
140
+ * It is the viewport with its padding. With clones: 'fill', it is the window, so that the slides fill it when the viewport overflow shows.
112
141
  *
113
142
  * @param {HTMLElement} viewport
114
143
  * @param {{axis: string, rtl: boolean}} layout
115
- * @param {number} view The viewport size.
144
+ * @param {number} view The viewport size without the padding.
145
+ * @param {{start: number, end: number}} pad The viewport padding.
116
146
  * @param {number} [size] The window size on the main axis, for clones: 'fill'. Without it, the area is the viewport.
117
147
  * @returns {{start: number, size: number}}
118
148
  */
119
- export function visibleArea(viewport, layout, view, size) {
149
+ export function visibleArea(viewport, layout, view, pad, size) {
120
150
  if (!size) {
121
- return { start: 0, size: view };
151
+ return { start: -pad.start, size: pad.start + view + pad.end };
122
152
  }
123
153
 
124
154
  const box = viewport.getBoundingClientRect(),
125
- before = Math.max(0, Math.round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top));
155
+ before = Math.max(0, Math.round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top)) + pad.start;
126
156
 
127
- return { start: -before, size: before + Math.max(view, Math.round(size - before)) };
157
+ return { start: -before, size: before + Math.max(view + pad.end, Math.round(size - before)) };
128
158
  }
129
159
 
130
160
  // One ResizeObserver for all carousels. Each callback first reads the layout of all carousels, then writes. In this way, the reads of one carousel do not
131
161
  // come after the writes of another carousel, and the browser does one layout for all of them.
132
- const owners = new WeakMap();
162
+ const owners = new WeakMap(),
163
+ // The elements of each owner, and the last size of each element
164
+ watched = new WeakMap(),
165
+ sizes = new WeakMap();
133
166
 
134
167
  let resizer;
135
168
 
136
169
  /**
137
170
  * Watch the size of elements. The ResizeObserver callback calls owner.read() for each owner, and then owner.write() for each owner whose read() returned true.
138
- * An entry for which owner.skip() returns true does not count.
171
+ * An entry for which owner.skip() returns true does not count. An entry with the same size as the last entry of its element does not count:
172
+ * a new watch of an element after a write sends such an entry. observeSize() clears the last size, so its first entry always counts.
139
173
  *
140
174
  * @param {Element[]} nodes
141
175
  * @param {{read: () => boolean, write: () => void, skip: (entry: ResizeObserverEntry) => boolean}} [owner] Without an owner, stop the watch.
142
176
  */
143
177
  export function observeSize(nodes, owner) {
144
178
  resizer ||= new ResizeObserver((entries) => {
145
- const list = new Set(entries.filter((entry) => !owners.get(entry.target)?.skip(entry)).map((entry) => owners.get(entry.target)));
146
- [...list].filter((item) => item && item.read()).forEach((item) => item.write());
179
+ const list = new Set(entries.filter((entry) => {
180
+ const { inlineSize, blockSize } = entry.borderBoxSize[0],
181
+ size = inlineSize + ',' + blockSize,
182
+ same = sizes.get(entry.target) === size;
183
+ sizes.set(entry.target, size);
184
+ return !same && !owners.get(entry.target)?.skip(entry);
185
+ }).map((entry) => owners.get(entry.target)));
186
+ const changed = [...list].filter((item) => item && item.read());
187
+ changed.forEach((item) => item.write());
188
+ // A write can change the size of an element that the observer watches, for example the auto height or the clones. If the observer has
189
+ // a change to report after its callback, the browser sends the "ResizeObserver loop" error to window.onerror. Stop the watch of these
190
+ // elements, and watch them again in the next frame. Then the first callback measures again and finds no change.
191
+ if (changed.length) {
192
+ changed.forEach((item) => watched.get(item)?.forEach((node) => resizer.unobserve(node)));
193
+ requestAnimationFrame(() => changed.forEach((item) => watched.get(item)?.forEach((node) => owners.get(node) === item && resizer.observe(node))));
194
+ }
147
195
  });
148
196
 
197
+ if (owner) {
198
+ watched.set(owner, nodes);
199
+ }
200
+
149
201
  for (const node of nodes) {
202
+ sizes.delete(node);
150
203
  if (owner) {
151
204
  owners.set(node, owner);
152
205
  resizer.observe(node);
@@ -208,15 +208,18 @@ const controls = 'a[href],button,input,select,textarea,[tabindex],[role]';
208
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
209
  const generic = 'div,span,section';
210
210
 
211
+ // The elements that never show, so they are not slides
212
+ const skipped = new Set(['template', 'script', 'style']);
213
+
211
214
  /**
212
- * Get the slides of a container. The clones that the library made are not slides.
215
+ * Get the slides of a container. The clones that the library made, and the template, script and style elements, are not slides.
213
216
  *
214
217
  * @param {HTMLElement} container
215
218
  * @param {string} [selector] The "slides" option.
216
219
  * @returns {HTMLElement[]}
217
220
  */
218
221
  export function readSlides(container, selector) {
219
- return [...(selector ? container.querySelectorAll(selector) : container.children)].filter((node) => !made.has(node));
222
+ return [...(selector ? container.querySelectorAll(selector) : container.children)].filter((node) => !made.has(node) && !skipped.has(node.localName));
220
223
  }
221
224
 
222
225
  /**
@@ -233,9 +236,7 @@ export function copySlides(slides, count, className) {
233
236
  for (let copy = 0; copy < count; copy++) {
234
237
  for (const node of slides) {
235
238
  const clone = node.cloneNode(true);
236
- for (const item of [clone, ...clone.querySelectorAll('[id]')]) {
237
- item.removeAttribute('id');
238
- }
239
+ removeIds(clone);
239
240
  clone.setAttribute('aria-hidden', 'true');
240
241
  clone.inert = true;
241
242
  clone.style.translate = '';
@@ -249,6 +250,25 @@ export function copySlides(slides, count, className) {
249
250
  return list;
250
251
  }
251
252
 
253
+ // An id must be unique in the page, so a copy has no ids
254
+ function removeIds(node) {
255
+ for (const item of [node, ...node.querySelectorAll('[id]')]) {
256
+ item.removeAttribute('id');
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Copy the content of a slide into its clone again.
262
+ *
263
+ * @param {HTMLElement} clone
264
+ * @param {HTMLElement} node The slide.
265
+ */
266
+ export function copyContent(clone, node) {
267
+ const copy = node.cloneNode(true);
268
+ removeIds(copy);
269
+ clone.replaceChildren(...copy.childNodes);
270
+ }
271
+
252
272
  /**
253
273
  * 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
274
  *
@@ -1,209 +1,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 { 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 { 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
+ }