@zazz-ui/core 0.13.1 → 0.14.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +5 -9
  3. package/dist/sri.json +34 -30
  4. package/dist/zazz.css +1 -1
  5. package/dist/zazz.js +1 -1
  6. package/editor/zazz.css-data.json +173 -3
  7. package/editor/zazz.html-data.json +138 -0
  8. package/editor/zazz.language-data.json +313 -125
  9. package/editor/zazz.lint-data.json +1501 -1383
  10. package/package.json +1 -5
  11. package/src/base/_defaults.css +1 -1
  12. package/src/base/_reset.css +16 -2
  13. package/src/base/_variables.css +43 -31
  14. package/src/base/carousel-scroll.d.ts +161 -0
  15. package/src/base/carousel-scroll.d.ts.map +1 -0
  16. package/src/base/carousel-scroll.js +1035 -0
  17. package/src/base/carousel-scroll.ts +1227 -0
  18. package/src/base/carousel.d.ts +34 -0
  19. package/src/base/carousel.d.ts.map +1 -0
  20. package/src/base/carousel.js +279 -0
  21. package/src/base/carousel.ts +292 -0
  22. package/src/base/dialog-lifecycle.js +1 -1
  23. package/src/base/dialog-lifecycle.ts +1 -1
  24. package/src/base/gesture.d.ts +201 -0
  25. package/src/base/gesture.d.ts.map +1 -0
  26. package/src/base/gesture.js +317 -0
  27. package/src/base/gesture.ts +494 -0
  28. package/src/base/kit-styling.d.ts.map +1 -1
  29. package/src/base/kit-styling.js +182 -162
  30. package/src/base/kit-styling.ts +182 -162
  31. package/src/base/utils.d.ts +1 -1
  32. package/src/base/utils.js +2 -2
  33. package/src/base/utils.ts +2 -2
  34. package/src/globals.d.ts +7 -30
  35. package/src/head.d.ts.map +1 -1
  36. package/src/head.js +1 -25
  37. package/src/head.ts +1 -25
  38. package/src/index.css +1 -0
  39. package/src/index.d.ts +6 -5
  40. package/src/index.d.ts.map +1 -1
  41. package/src/index.js +6 -5
  42. package/src/index.ts +6 -5
  43. package/src/manifest.d.ts +1 -1
  44. package/src/manifest.d.ts.map +1 -1
  45. package/src/manifest.js +25 -13
  46. package/src/manifest.ts +26 -14
  47. package/src/primitives/button/button.css +1 -1
  48. package/src/primitives/carousel/carousel.css +103 -20
  49. package/src/primitives/carousel/carousel.d.ts +4 -32
  50. package/src/primitives/carousel/carousel.d.ts.map +1 -1
  51. package/src/primitives/carousel/carousel.js +39 -14
  52. package/src/primitives/carousel/carousel.ts +21 -25
  53. package/src/primitives/dialog/dialog.css +14 -8
  54. package/src/primitives/drawer/drawer-indent.html +27 -0
  55. package/src/primitives/drawer/drawer-nested.html +72 -0
  56. package/src/primitives/drawer/drawer-responsive-dialog.html +44 -0
  57. package/src/primitives/drawer/drawer-snap.html +26 -0
  58. package/src/primitives/drawer/drawer.css +528 -0
  59. package/src/primitives/drawer/drawer.d.ts +24 -0
  60. package/src/primitives/drawer/drawer.d.ts.map +1 -0
  61. package/src/primitives/drawer/drawer.html +42 -0
  62. package/src/primitives/drawer/drawer.js +765 -0
  63. package/src/primitives/drawer/drawer.ts +823 -0
  64. package/src/primitives/fields/fields.css +4 -2
  65. package/src/primitives/input/input.css +1 -1
  66. package/src/primitives/input-group/input-group.css +5 -5
  67. package/src/primitives/lightbox/lightbox.css +2 -2
  68. package/src/primitives/lightbox/lightbox.d.ts.map +1 -1
  69. package/src/primitives/lightbox/lightbox.js +9 -8
  70. package/src/primitives/lightbox/lightbox.ts +9 -8
  71. package/src/primitives/password-group/password-group.css +5 -5
  72. package/src/primitives/radio/radio.css +15 -10
  73. package/src/primitives/slider/slider.css +2 -2
  74. package/src/primitives/switch/switch.css +6 -6
  75. package/src/primitives/tabs/tabs.css +10 -10
  76. package/src/primitives/toaster/toaster.css +29 -1
  77. package/src/primitives/toaster/toaster.d.ts.map +1 -1
  78. package/src/primitives/toaster/toaster.js +117 -9
  79. package/src/primitives/toaster/toaster.ts +136 -9
  80. package/src/primitives/tooltip/tooltip.css +93 -10
  81. package/src/base/embla.d.ts +0 -90
  82. package/src/base/embla.d.ts.map +0 -1
  83. package/src/base/embla.js +0 -878
  84. package/src/base/embla.ts +0 -1066
@@ -0,0 +1,1035 @@
1
+ "use strict";
2
+ /**
3
+ * @fileoverview The carousel engine: native scroll snap, plus what it lacks.
4
+ * @description Started per carousel root by base/carousel.ts (which documents
5
+ * the markup and the attributes). The viewport is a real scroll container (`scroll-snap-type: x mandatory`,
6
+ * set in carousel.css), so touch, trackpad, wheel, and keyboard scrolling are
7
+ * the browser's own: compositor-driven, no script per frame, and the content
8
+ * stays scrollable without JS. This module adds what the platform lacks:
9
+ *
10
+ * - **Mouse drag** (`base/gesture.ts`): a mouse press drags the track 1:1 with
11
+ * snapping off, rubber-bands past the ends, and on release projects the
12
+ * flick's velocity to a snap and scrolls there. Touch and pen are left to
13
+ * native scrolling (`canStart` rejects them).
14
+ * - **Selection**: the nearest snap, tracked from a rAF-throttled `scroll`
15
+ * listener and settled on `scrollend` (debounced `scroll` where missing);
16
+ * a click's pending target wins while its scroll is in flight.
17
+ * - **Loop** without clones: slides are rotated with `order` so the current
18
+ * one sits mid-track with neighbours on both sides, then an instant scroll
19
+ * compensates the shift, all while snapping and overflow are locked.
20
+ * Wrapped slides that are out of view are `inert`, so Tab order and the
21
+ * accessibility tree only skip content the user cannot see.
22
+ * - **Axis and direction**: every position is logical (px from the track's
23
+ * start edge), so a vertical track (`data-carousel-axis="y"`) and a
24
+ * right-to-left one (`dir="rtl"` anywhere above it) run the same code.
25
+ * - **Thumbs** (`linkThumbs`): a second engine on the thumb strip, drag-free
26
+ * by default, that keeps the selected thumb in view.
27
+ * - **Autoplay / auto-scroll** (`data-carousel-plugins="autoplay"` or
28
+ * `"auto-scroll"`), with the kit's interaction rules (see `readAutoOptions`).
29
+ * Both pause while the carousel is off screen or the tab is hidden.
30
+ * - Prev/next, dot pagination, the `in-view` / `snapped` / `active` /
31
+ * `playing` state tokens, and a `zazz:carousel-select` event on the root.
32
+ *
33
+ * Supported options (on the root): `data-carousel-loop`, `-align`
34
+ * (`start` | `center` | `end`), `-axis` (`x` | `y`), `-draggable="false"`,
35
+ * `-drag-free`, `-skip-snaps` (a flick may pass several snaps; default one),
36
+ * `-start-snap`. Thumb strips read the same names under
37
+ * `data-carousel-thumbs-*` on the thumbs slot.
38
+ */
39
+ import { rubberBand, trackDrag } from "./gesture.js";
40
+ import { Utils } from "./utils.js";
41
+ // --- Constants ---
42
+ /** Deceleration for projecting a release, in px/ms² (≈ a native fling's end distance). */
43
+ const DECELERATION = 0.0025;
44
+ /** Release speed (px/ms) that steps a snap even when the projection lands back on the start one. */
45
+ const STEP_VELOCITY = 0.3;
46
+ /** Where `scrollend` is missing, the quiet time that counts as settled, in ms. */
47
+ const SETTLE_FALLBACK_MS = 120;
48
+ /** Fastest a drag-free coast may decay (per ms), when an end cuts its distance short. */
49
+ const MAX_COAST_RATE = 0.02;
50
+ /** Auto-scroll `speed` is px per 60 Hz frame, scaled by real frame time. */
51
+ const FRAME_MS = 1000 / 60;
52
+ // --- State tokens ---
53
+ /**
54
+ * @description Adds or removes one token of an element's `data-carousel-state`
55
+ * list, leaving the other tokens in place.
56
+ */
57
+ function setCarouselState(node, token, on) {
58
+ const current = node.getAttribute("data-carousel-state") ?? "";
59
+ const tokens = current.split(/\s+/).filter(Boolean);
60
+ if (tokens.includes(token) === on)
61
+ return;
62
+ const next = on ? [...tokens, token] : tokens.filter((t) => t !== token);
63
+ if (next.length)
64
+ node.setAttribute("data-carousel-state", next.join(" "));
65
+ else
66
+ node.removeAttribute("data-carousel-state");
67
+ }
68
+ // --- Pure helpers ---
69
+ /**
70
+ * @description The distance a release coasts at constant deceleration
71
+ * (v² / 2a), signed like the velocity.
72
+ */
73
+ function projectRelease(velocity, deceleration = DECELERATION) {
74
+ return (Math.sign(velocity) * velocity * velocity) / (2 * deceleration);
75
+ }
76
+ /** Index of the snap nearest to `pos`. */
77
+ function nearestSnap(snaps, pos) {
78
+ let best = 0;
79
+ let bestDistance = Infinity;
80
+ snaps.forEach((snap, index) => {
81
+ const distance = Math.abs(snap.pos - pos);
82
+ if (distance < bestDistance) {
83
+ bestDistance = distance;
84
+ best = index;
85
+ }
86
+ });
87
+ return best;
88
+ }
89
+ /**
90
+ * @description Visual order for a looped track: rotates the slides so `center`
91
+ * has `before` slides ahead of it (by default half the track).
92
+ *
93
+ * @returns The `order` value per slide, in DOM order.
94
+ */
95
+ function loopOrders(count, center, before = Math.floor(count / 2)) {
96
+ return Array.from({ length: count }, (_, i) => (((i - center + before) % count) + count) % count);
97
+ }
98
+ /**
99
+ * @description How many slides a looped track keeps ahead of the current one:
100
+ * the spare slides (those not in view) split evenly around the view, so a
101
+ * drag or flick in either direction has the same room before an end.
102
+ *
103
+ * @param count - Slides in the track.
104
+ * @param perView - Slides the viewport shows at once (current included).
105
+ */
106
+ function loopLead(count, perView) {
107
+ return Math.max(1, Math.floor((count - Math.max(1, perView)) / 2));
108
+ }
109
+ /**
110
+ * @description How far to rotate a looped track so a step fits: the slides in
111
+ * view and the slides the target shows must all sit inside the track, in
112
+ * order. Ranges are positions along the track (`order` values); the target's
113
+ * may run past either end.
114
+ *
115
+ * @param count - Slides in the track.
116
+ * @param view - First and last position in view now.
117
+ * @param target - First and last position in view once the step lands.
118
+ * @returns Positions to rotate by (0 when the step already fits, with the
119
+ * span centred otherwise), or null when the span needs more slides than exist.
120
+ */
121
+ function loopShift(count, view, target) {
122
+ const lo = Math.min(view.first, target.first);
123
+ const hi = Math.max(view.last, target.last);
124
+ if (lo >= 0 && hi <= count - 1)
125
+ return 0;
126
+ const span = hi - lo + 1;
127
+ if (span > count)
128
+ return null;
129
+ return Math.floor((count - span) / 2) - lo;
130
+ }
131
+ /**
132
+ * @description Which snap a release lands on: the one nearest to the
133
+ * projected position, stepping at least one snap in the flick's direction
134
+ * when the release was fast but the projection fell back to the start.
135
+ *
136
+ * @param velocity - Logical px/ms: positive moves the content toward the end
137
+ * edge, which scrolls toward the start.
138
+ */
139
+ function releaseTarget(snaps, from, projected, velocity, skipSnaps = false) {
140
+ let target = nearestSnap(snaps, projected);
141
+ if (target === from && Math.abs(velocity) > STEP_VELOCITY) {
142
+ target = from + (velocity > 0 ? -1 : 1);
143
+ }
144
+ // a flick moves one snap at most unless `skip-snaps` is on
145
+ if (!skipSnaps)
146
+ target = Math.min(from + 1, Math.max(from - 1, target));
147
+ return Math.min(snaps.length - 1, Math.max(0, target));
148
+ }
149
+ /**
150
+ * @description Reads autoplay / auto-scroll from the root: the slug in
151
+ * `data-carousel-plugins` picks the mode (auto-scroll wins when both are
152
+ * listed), and its options come from that plugin's attributes:
153
+ * - autoplay (`data-carousel-autoplay-*`): `delay` (ms, 4000),
154
+ * `stop-on-last-snap` (false; otherwise wraps to the first snap).
155
+ * - auto-scroll (`data-carousel-auto-scroll-*`): `speed` (px per 60 Hz frame,
156
+ * 2), `start-delay` (ms before it moves, and before it resumes, 1000),
157
+ * `direction` (`forward` | `backward`). It doesn't start on its own under
158
+ * `prefers-reduced-motion: reduce`.
159
+ * - both: `play-on-init` (true), `stop-on-interaction` (true: a drag, a
160
+ * scroll, slide focus, or a manual step stops it for good; `false` holds it
161
+ * until the interaction ends), `stop-on-mouse-enter` (false).
162
+ *
163
+ * @returns The settings, or null when neither slug is listed.
164
+ */
165
+ function readAutoOptions(root) {
166
+ const slugs = (root.getAttribute("data-carousel-plugins") ?? "").split(/[\s,]+/);
167
+ const mode = slugs.includes("auto-scroll")
168
+ ? "auto-scroll"
169
+ : slugs.includes("autoplay")
170
+ ? "autoplay"
171
+ : null;
172
+ if (!mode)
173
+ return null;
174
+ const raw = Utils.parseDataAttributes(root, mode === "autoplay" ? "data-carousel-autoplay-" : "data-carousel-auto-scroll-");
175
+ const num = (value, fallback) => typeof value === "number" && value >= 0 ? value : fallback;
176
+ return {
177
+ mode,
178
+ delay: num(raw.delay, 4000),
179
+ speed: num(raw.speed, 2),
180
+ startDelay: num(raw.startDelay, 1000),
181
+ backward: raw.direction === "backward",
182
+ playOnInit: raw.playOnInit !== false,
183
+ stopOnInteraction: raw.stopOnInteraction !== false,
184
+ stopOnMouseEnter: raw.stopOnMouseEnter === true,
185
+ stopOnLastSnap: raw.stopOnLastSnap === true,
186
+ };
187
+ }
188
+ // --- Engine ---
189
+ /**
190
+ * @description Starts the engine on a carousel root.
191
+ *
192
+ * @param root - The carousel root (`<ui-carousel>` or `[data-ui~="carousel"]`),
193
+ * or a thumbs slot.
194
+ * @param viewport - Its viewport slot.
195
+ * @param signal - Aborting it tears everything down.
196
+ * @param config - Where options come from and which controls to wire.
197
+ * @returns The API, or null when the markup has no container.
198
+ */
199
+ function createCarousel(root, viewport, signal, config = {}) {
200
+ const container = viewport.querySelector('[data-carousel-slot~="container"]');
201
+ if (!container)
202
+ return null;
203
+ const slides = [
204
+ ...container.querySelectorAll(':scope > [data-carousel-slot~="slide"]'),
205
+ ];
206
+ const { prefix = "data-carousel-", defaults = {}, controls = true } = config;
207
+ const raw = Utils.parseDataAttributes(root, prefix);
208
+ const flag = (value, fallback) => typeof value === "boolean" ? value : fallback;
209
+ const options = {
210
+ // loop needs a neighbour on each side of the current slide
211
+ loop: flag(raw.loop, defaults.loop ?? false) && slides.length >= 3,
212
+ draggable: flag(raw.draggable, true),
213
+ dragFree: flag(raw.dragFree, defaults.dragFree ?? false),
214
+ skipSnaps: flag(raw.skipSnaps, false),
215
+ startSnap: typeof raw.startSnap === "number" ? raw.startSnap : 0,
216
+ vertical: raw.axis === "y",
217
+ };
218
+ let snapsCache = null;
219
+ let perViewCache = 1;
220
+ /** Slides a resting snap shows before and after its own slide (from alignment). */
221
+ let reach = { back: 0, ahead: 0 };
222
+ let selected = -1;
223
+ /** A click's destination while its scroll is in flight (snap index). */
224
+ let pending = null;
225
+ /** With loop, the slide `pending` stands for (end snaps merge several slides). */
226
+ let pendingSlide = null;
227
+ let inView = new Set();
228
+ let orders = slides.map(() => 0);
229
+ /** Mirrors the `gliding` token: snapping is off while the script moves the track. */
230
+ let gliding = false;
231
+ /** Mirrors the `settling` token: a loop rotation's lock. */
232
+ let settling = false;
233
+ /** A scroll asked for while settling; run once the lock lifts. */
234
+ let queued = null;
235
+ let dragging = false;
236
+ /** True while the auto-scroll loop is writing the scroll position. */
237
+ let autoScrolling = false;
238
+ const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
239
+ const behavior = (instant) => instant || reducedMotion.matches ? "auto" : "smooth";
240
+ // --- Axis ---
241
+ // Positions are logical: px from the track's start edge, growing toward the
242
+ // end. In RTL the start edge is the right one and `scrollLeft` runs from 0
243
+ // down to negative values (the spec's model, shipped in every engine).
244
+ const vertical = options.vertical;
245
+ const rtl = !vertical && getComputedStyle(viewport).direction === "rtl";
246
+ const sign = rtl ? -1 : 1;
247
+ const getPos = () => (vertical ? viewport.scrollTop : viewport.scrollLeft * sign);
248
+ const writePos = (pos) => {
249
+ if (vertical)
250
+ viewport.scrollTop = pos;
251
+ else
252
+ viewport.scrollLeft = pos * sign;
253
+ };
254
+ const scrollToPos = (pos, how) => viewport.scrollTo(vertical ? { top: pos, behavior: how } : { left: pos * sign, behavior: how });
255
+ const clientSize = () => (vertical ? viewport.clientHeight : viewport.clientWidth);
256
+ const maxScroll = () => Math.max(0, (vertical ? viewport.scrollHeight : viewport.scrollWidth) - clientSize());
257
+ const clampPos = (pos) => Math.min(maxScroll(), Math.max(0, pos));
258
+ /** A box's start edge, in px from the viewport's start edge. */
259
+ const startOf = (rect, box) => vertical ? rect.top - box.top : rtl ? box.right - rect.right : rect.left - box.left;
260
+ const sizeOf = (rect) => (vertical ? rect.height : rect.width);
261
+ /** Pointer travel (px, on the drag axis) as logical travel. */
262
+ const logical = (physical) => (vertical ? physical : physical * sign);
263
+ /**
264
+ * An instant scroll. The `jumping` token sets `scroll-behavior: auto` in CSS,
265
+ * so the jump never inherits the viewport's smooth scrolling, whatever an
266
+ * engine makes of `behavior: "instant"`. Gliding and settling already set
267
+ * it, so their per-frame writes skip the two attribute changes.
268
+ */
269
+ const jump = (pos) => {
270
+ if (gliding || settling) {
271
+ writePos(pos);
272
+ return;
273
+ }
274
+ setCarouselState(viewport, "jumping", true);
275
+ writePos(pos);
276
+ setCarouselState(viewport, "jumping", false);
277
+ };
278
+ const setGliding = (on) => {
279
+ gliding = on;
280
+ setCarouselState(viewport, "gliding", on);
281
+ };
282
+ // --- Geometry ---
283
+ /** Snap points from layout, clamped to the scroll range and merged where they coincide. */
284
+ const measure = () => {
285
+ const box = viewport.getBoundingClientRect();
286
+ const styles = getComputedStyle(viewport);
287
+ const padStart = Number.parseFloat(vertical ? styles.scrollPaddingBlockStart : styles.scrollPaddingInlineStart) || 0;
288
+ const padEnd = Number.parseFloat(vertical ? styles.scrollPaddingBlockEnd : styles.scrollPaddingInlineEnd) ||
289
+ 0;
290
+ const max = maxScroll();
291
+ const client = clientSize();
292
+ const at = getPos();
293
+ let firstSize = 0;
294
+ let firstAlign = "start";
295
+ const points = slides.map((slide, index) => {
296
+ const rect = slide.getBoundingClientRect();
297
+ const size = sizeOf(rect);
298
+ if (index === 0)
299
+ firstSize = size;
300
+ const start = startOf(rect, box) + at;
301
+ // one value applies to both axes; two are `block inline`
302
+ const parts = getComputedStyle(slide).scrollSnapAlign.split(" ");
303
+ const align = vertical ? parts[0] : parts.at(-1);
304
+ if (index === 0)
305
+ firstAlign = align ?? "start";
306
+ const raw = align === "center"
307
+ ? start + size / 2 - client / 2
308
+ : align === "end"
309
+ ? start + size - client + padEnd
310
+ : start - padStart;
311
+ return { index, pos: Math.round(Math.min(max, Math.max(0, raw))) };
312
+ });
313
+ perViewCache = firstSize > 0 ? Math.max(1, Math.round(client / firstSize)) : 1;
314
+ const side = perViewCache - 1;
315
+ // centred slides that don't fill the view show a neighbour's edge on each side
316
+ const peek = firstSize * perViewCache < client - 1 ? 1 : 0;
317
+ reach =
318
+ firstAlign === "center"
319
+ ? { back: Math.floor(perViewCache / 2) + peek, ahead: Math.floor(perViewCache / 2) + peek }
320
+ : firstAlign === "end"
321
+ ? { back: side, ahead: 0 }
322
+ : { back: 0, ahead: side };
323
+ points.sort((a, b) => a.pos - b.pos);
324
+ const snaps = [];
325
+ for (const { index, pos } of points) {
326
+ const last = snaps.at(-1);
327
+ if (last && Math.abs(last.pos - pos) < 1)
328
+ last.slides.push(index);
329
+ else
330
+ snaps.push({ pos, slides: [index] });
331
+ }
332
+ return snaps;
333
+ };
334
+ const snaps = () => (snapsCache ??= measure());
335
+ const invalidate = () => {
336
+ snapsCache = null;
337
+ };
338
+ /** Slides in view at once, from the first slide's size. */
339
+ const perView = () => {
340
+ snaps();
341
+ return perViewCache;
342
+ };
343
+ /** The index the API speaks in: the snap, or with loop the slide (rotation-independent). */
344
+ const publicIndex = (snapIndex) => options.loop ? (snaps()[snapIndex]?.slides[0] ?? 0) : snapIndex;
345
+ const snapOfSlide = (slide) => Math.max(0, snaps().findIndex((snap) => snap.slides.includes(slide)));
346
+ // --- Output ---
347
+ let dots = [];
348
+ const dotsNode = controls ? root.querySelector('[data-carousel-slot~="dots"]') : null;
349
+ const templateDot = dotsNode?.querySelector('[data-carousel-slot~="dot"]')?.cloneNode(true);
350
+ const buildDots = () => {
351
+ if (!dotsNode || !(templateDot instanceof HTMLElement))
352
+ return;
353
+ const count = options.loop ? slides.length : snaps().length;
354
+ if (count === dots.length)
355
+ return;
356
+ dotsNode.replaceChildren();
357
+ dots = [];
358
+ if (count <= 1)
359
+ return;
360
+ for (let i = 0; i < count; i++) {
361
+ const dot = templateDot.cloneNode(true);
362
+ dot.addEventListener("click", () => {
363
+ api.interact();
364
+ api.goTo(i);
365
+ }, { signal });
366
+ dots.push(dot);
367
+ }
368
+ dotsNode.append(...dots);
369
+ };
370
+ const render = (snapIndex) => {
371
+ const index = publicIndex(snapIndex);
372
+ const snapped = new Set(snaps()[snapIndex]?.slides ?? []);
373
+ slides.forEach((slide, i) => setCarouselState(slide, "snapped", snapped.has(i)));
374
+ dots.forEach((dot, i) => setCarouselState(dot, "active", i === index));
375
+ };
376
+ const select = (snapIndex) => {
377
+ if (snapIndex === selected)
378
+ return;
379
+ selected = snapIndex;
380
+ render(snapIndex);
381
+ root.dispatchEvent(new CustomEvent("zazz:carousel-select", { detail: { index: publicIndex(snapIndex) } }));
382
+ };
383
+ // --- Loop rotation ---
384
+ /** Wrapped slides (moved against DOM order) that are out of view leave Tab order. */
385
+ const syncInert = () => {
386
+ if (!options.loop)
387
+ return;
388
+ const current = snaps()[selected]?.slides[0] ?? 0;
389
+ const lead = orders[current] ?? 0;
390
+ slides.forEach((slide, i) => {
391
+ const wrapped = orders[i] < lead ? i > current : i < current;
392
+ slide.inert = wrapped && !inView.has(i);
393
+ });
394
+ };
395
+ /** Invalidates an older rotation's pending unlock when a newer one starts. */
396
+ let lockToken = 0;
397
+ /**
398
+ * Reorders the track and scrolls by the anchor slide's shift so nothing
399
+ * visibly moves. `lock` also freezes snapping and the axis for two frames;
400
+ * the auto-scroll loop reorders without it.
401
+ */
402
+ const applyOrders = (next, anchorIndex, lock = true) => {
403
+ if (next.every((order, i) => order === orders[i]))
404
+ return;
405
+ const anchor = slides[anchorIndex];
406
+ const box = viewport.getBoundingClientRect();
407
+ const before = startOf(anchor.getBoundingClientRect(), box);
408
+ // snapping off (some engines re-snap elsewhere mid-compensation) and the
409
+ // axis locked (iOS Safari paints the reordered frame before the scroll lands)
410
+ // an unlocked reorder (auto-scroll) leaves an earlier lock's unlock in place
411
+ const token = lock ? ++lockToken : lockToken;
412
+ if (lock) {
413
+ settling = true;
414
+ setCarouselState(viewport, "settling", true);
415
+ }
416
+ slides.forEach((slide, i) => {
417
+ if (orders[i] !== next[i])
418
+ slide.style.order = String(next[i]);
419
+ });
420
+ orders = next;
421
+ const shift = startOf(anchor.getBoundingClientRect(), box) - before;
422
+ jump(getPos() + shift);
423
+ invalidate();
424
+ if (!lock)
425
+ return;
426
+ // Two frames: restoring overflow at once breaks the compensation in iOS
427
+ // Safari. A smooth scroll started under the lock is dropped by WebKit when
428
+ // overflow changes, so scrolls asked for meanwhile wait for the lift.
429
+ requestAnimationFrame(() => requestAnimationFrame(() => {
430
+ if (token !== lockToken)
431
+ return;
432
+ settling = false;
433
+ setCarouselState(viewport, "settling", false);
434
+ const run = queued;
435
+ queued = null;
436
+ run?.();
437
+ }));
438
+ };
439
+ /** Rotates the track so `center` sits mid-track with neighbours on both sides. */
440
+ const rotate = (center, lock = true) => applyOrders(loopOrders(slides.length, center, loopLead(slides.length, perView())), center, lock);
441
+ /** Track positions (`order`) of the first and last slide in view right now. */
442
+ const viewRange = () => {
443
+ const box = viewport.getBoundingClientRect();
444
+ const client = clientSize();
445
+ let first = Infinity;
446
+ let last = -Infinity;
447
+ slides.forEach((slide, i) => {
448
+ const rect = slide.getBoundingClientRect();
449
+ const start = startOf(rect, box);
450
+ if (start + sizeOf(rect) <= 1 || start >= client - 1)
451
+ return;
452
+ first = Math.min(first, orders[i]);
453
+ last = Math.max(last, orders[i]);
454
+ });
455
+ return { first, last };
456
+ };
457
+ // --- Scroll tracking ---
458
+ let frame = 0;
459
+ const onScroll = () => {
460
+ if (holds.has("pointer"))
461
+ pointerScrolled = true;
462
+ if (frame)
463
+ return;
464
+ frame = requestAnimationFrame(() => {
465
+ frame = 0;
466
+ if (pending == null && !dragging)
467
+ select(nearestSnap(snaps(), getPos()));
468
+ });
469
+ };
470
+ const settle = () => {
471
+ if (dragging || autoScrolling || coastFrame)
472
+ return;
473
+ // a scrollend from an earlier scroll can land after the next one started
474
+ // (WebKit); acting on it would rotate the track under the new scroll
475
+ const target = pending == null ? null : snaps()[pending];
476
+ if (target && Math.abs(getPos() - target.pos) > 1)
477
+ return;
478
+ pending = null;
479
+ const nearest = nearestSnap(snaps(), getPos());
480
+ // a glide that stopped between snaps (auto-scroll paused) lands on the
481
+ // nearest one before snapping resumes, or the browser would jump there
482
+ if (gliding && !options.dragFree && Math.abs(getPos() - snaps()[nearest].pos) > 1) {
483
+ scrollToSnap(nearest);
484
+ return;
485
+ }
486
+ setGliding(false);
487
+ select(nearest);
488
+ if (options.loop) {
489
+ rotate(snaps()[selected]?.slides[0] ?? 0);
490
+ selected = nearestSnap(snaps(), getPos());
491
+ syncInert();
492
+ }
493
+ afterSettle();
494
+ };
495
+ viewport.addEventListener("scroll", onScroll, { passive: true, signal });
496
+ if ("onscrollend" in window) {
497
+ viewport.addEventListener("scrollend", settle, { signal });
498
+ }
499
+ else {
500
+ let timer = 0;
501
+ viewport.addEventListener("scroll", () => {
502
+ clearTimeout(timer);
503
+ timer = window.setTimeout(settle, SETTLE_FALLBACK_MS);
504
+ }, { passive: true, signal });
505
+ signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
506
+ }
507
+ /** Scrolls to a snap; settles at once when there is nowhere to go (no scrollend follows). */
508
+ const scrollToSnap = (snapIndex, instant, slide = null) => {
509
+ stopCoast();
510
+ const list = snaps();
511
+ const target = Math.min(list.length - 1, Math.max(0, snapIndex));
512
+ if (settling) {
513
+ // the target is already the destination, so a step asked for under the
514
+ // lock continues from it and the compensating scroll's scrollend is ignored
515
+ pending = target;
516
+ pendingSlide = slide;
517
+ select(target);
518
+ queued = () => scrollToSnap(snapIndex, instant, slide);
519
+ return;
520
+ }
521
+ const pos = list[target]?.pos ?? 0;
522
+ if (Math.abs(getPos() - pos) < 1) {
523
+ settle();
524
+ return;
525
+ }
526
+ pending = target;
527
+ pendingSlide = slide;
528
+ select(target);
529
+ if (instant) {
530
+ jump(pos);
531
+ settle();
532
+ return;
533
+ }
534
+ scrollToPos(pos, behavior());
535
+ };
536
+ /** One step toward the end (+1) or the start (-1), from a click's pending target if any. */
537
+ const step = (direction) => {
538
+ const from = pending ?? selected;
539
+ if (!options.loop) {
540
+ scrollToSnap(from + direction);
541
+ return;
542
+ }
543
+ const count = slides.length;
544
+ const fromSlide = (pending != null ? pendingSlide : null) ?? publicIndex(from);
545
+ const slide = (fromSlide + direction + count) % count;
546
+ // The track is only re-centred when a scroll settles, so steps taken while
547
+ // one is in flight run out of slides. Rotate first when this one wouldn't
548
+ // fit: the rotation and its compensating scroll cancel the scroll in
549
+ // flight, and the new one starts from where the track visibly is.
550
+ const at = orders[fromSlide] + direction;
551
+ const view = viewRange();
552
+ const shift = loopShift(count, view, { first: at - reach.back, last: at + reach.ahead });
553
+ // every slide is already in play between the view and the target
554
+ if (shift == null)
555
+ return;
556
+ if (shift) {
557
+ const current = publicIndex(Math.max(0, selected));
558
+ pending = null;
559
+ applyOrders(orders.map((order) => (((order + shift) % count) + count) % count), Math.max(0, orders.indexOf(view.first)));
560
+ selected = snapOfSlide(current);
561
+ syncInert();
562
+ }
563
+ scrollToSnap(snapOfSlide(slide), false, slide);
564
+ };
565
+ // --- Autoplay / auto-scroll ---
566
+ const auto = controls ? readAutoOptions(root) : null;
567
+ /** Should play: play-on-init or play(), until stop() or a stopping interaction. */
568
+ let wanted = false;
569
+ /** What holds it with stop-on-interaction false; it resumes once this empties. */
570
+ const holds = new Set();
571
+ /** A scroll happened under the pointer hold, so its scrollend (not the pointer up) ends it. */
572
+ let pointerScrolled = false;
573
+ let onScreen = true;
574
+ let running = false;
575
+ let autoTimer = 0;
576
+ let autoFrame = 0;
577
+ let lastTick = 0;
578
+ let carry = 0;
579
+ const advance = () => {
580
+ autoTimer = 0;
581
+ const from = pending ?? selected;
582
+ if (!options.loop && from >= snaps().length - 1) {
583
+ if (auto?.stopOnLastSnap) {
584
+ wanted = false;
585
+ reconcile();
586
+ }
587
+ else
588
+ scrollToSnap(0);
589
+ }
590
+ else
591
+ step(1);
592
+ };
593
+ /** One auto-scroll frame: moves by speed × elapsed time and keeps a looped track rotated. */
594
+ const tick = (now) => {
595
+ if (!auto)
596
+ return;
597
+ autoFrame = requestAnimationFrame(tick);
598
+ const elapsed = lastTick ? Math.min(50, now - lastTick) : 0;
599
+ lastTick = now;
600
+ carry += ((auto.backward ? -auto.speed : auto.speed) * elapsed) / FRAME_MS;
601
+ // whole px only: fractional scroll offsets round differently per engine
602
+ const whole = Math.trunc(carry);
603
+ if (!whole)
604
+ return;
605
+ carry -= whole;
606
+ const next = getPos() + whole;
607
+ if (!options.loop && (next <= 0 || next >= maxScroll())) {
608
+ writePos(clampPos(next));
609
+ wanted = false;
610
+ reconcile();
611
+ return;
612
+ }
613
+ writePos(next);
614
+ const nearest = nearestSnap(snaps(), getPos());
615
+ select(nearest);
616
+ if (options.loop) {
617
+ rotate(snaps()[nearest]?.slides[0] ?? 0, false);
618
+ selected = nearestSnap(snaps(), getPos());
619
+ }
620
+ };
621
+ const stopMotion = () => {
622
+ clearTimeout(autoTimer);
623
+ cancelAnimationFrame(autoFrame);
624
+ autoTimer = 0;
625
+ autoFrame = 0;
626
+ if (!autoScrolling)
627
+ return;
628
+ autoScrolling = false;
629
+ settle();
630
+ };
631
+ const startMotion = () => {
632
+ if (!auto)
633
+ return;
634
+ if (auto.mode === "autoplay") {
635
+ autoTimer = window.setTimeout(advance, auto.delay);
636
+ return;
637
+ }
638
+ autoTimer = window.setTimeout(() => {
639
+ autoTimer = 0;
640
+ pending = null;
641
+ setGliding(true);
642
+ autoScrolling = true;
643
+ lastTick = 0;
644
+ carry = 0;
645
+ autoFrame = requestAnimationFrame(tick);
646
+ }, auto.startDelay);
647
+ };
648
+ /** Starts or stops the motion to match what should be happening; `restart` re-arms its delay. */
649
+ function reconcile(restart = false) {
650
+ const run = !!auto &&
651
+ wanted &&
652
+ holds.size === 0 &&
653
+ onScreen &&
654
+ !document.hidden &&
655
+ maxScroll() > 0 &&
656
+ snaps().length > 1;
657
+ if (auto)
658
+ setCarouselState(root, "playing", wanted);
659
+ if (run === running && !restart)
660
+ return;
661
+ running = run;
662
+ stopMotion();
663
+ if (run)
664
+ startMotion();
665
+ }
666
+ /** Each settled scroll restarts autoplay's delay; it also ends a pointer hold. */
667
+ function afterSettle() {
668
+ if (!auto)
669
+ return;
670
+ if (holds.delete("pointer")) {
671
+ reconcile();
672
+ return;
673
+ }
674
+ if (running && auto.mode === "autoplay") {
675
+ clearTimeout(autoTimer);
676
+ autoTimer = window.setTimeout(advance, auto.delay);
677
+ }
678
+ }
679
+ /** An interaction: stops for good, or with stop-on-interaction false holds until it ends. */
680
+ const holdFor = (reason) => {
681
+ if (!auto || !wanted)
682
+ return;
683
+ if (auto.stopOnInteraction)
684
+ wanted = false;
685
+ else
686
+ holds.add(reason);
687
+ if (reason === "pointer") {
688
+ pointerScrolled = false;
689
+ // the user takes over mid auto-scroll: snapping back on at once, so
690
+ // their own scroll lands on a snap the native way
691
+ if (autoScrolling) {
692
+ cancelAnimationFrame(autoFrame);
693
+ autoFrame = 0;
694
+ autoScrolling = false;
695
+ setGliding(false);
696
+ }
697
+ }
698
+ reconcile();
699
+ };
700
+ const release = (reason) => {
701
+ if (holds.delete(reason))
702
+ reconcile();
703
+ };
704
+ // the user taking over ends a scripted scroll short of its target; its
705
+ // scrollend must then count, so the pending target goes
706
+ const keyboardOff = viewport.closest('[data-carousel-keyboard="false"]') !== null;
707
+ const onUserInput = (event) => {
708
+ // the kit steps on arrow keys itself (carousel.ts), from the pending target
709
+ if (event instanceof KeyboardEvent && event.key.startsWith("Arrow") && !keyboardOff)
710
+ return;
711
+ if (event instanceof MouseEvent && event.button !== 0)
712
+ return;
713
+ holdFor("pointer");
714
+ pending = null;
715
+ // catching the track mid-coast stops it where it is
716
+ if (stopCoast())
717
+ settle();
718
+ };
719
+ for (const type of ["pointerdown", "wheel", "touchstart", "keydown"]) {
720
+ viewport.addEventListener(type, onUserInput, { passive: true, signal });
721
+ }
722
+ if (auto) {
723
+ // a tap (no scroll) ends the hold at once; a scroll ends it on settle.
724
+ // pointercancel means the browser took the touch for a pan: wait for that
725
+ viewport.addEventListener("pointerup", () => {
726
+ if (!pointerScrolled)
727
+ release("pointer");
728
+ }, { signal });
729
+ viewport.addEventListener("focusin", (event) => {
730
+ if (event.target !== viewport)
731
+ holdFor("focus");
732
+ }, { signal });
733
+ viewport.addEventListener("focusout", (event) => {
734
+ if (!(event.relatedTarget instanceof Node && viewport.contains(event.relatedTarget))) {
735
+ release("focus");
736
+ }
737
+ }, { signal });
738
+ if (auto.stopOnMouseEnter) {
739
+ root.addEventListener("mouseenter", () => holdFor("hover"), { signal });
740
+ root.addEventListener("mouseleave", () => release("hover"), { signal });
741
+ }
742
+ document.addEventListener("visibilitychange", () => reconcile(), { signal });
743
+ }
744
+ // --- Mouse drag ---
745
+ let dragFrom = 0;
746
+ let dragSnap = 0;
747
+ // No page-wide drag flag: trackDrag captures the pointer on the viewport, so
748
+ // its own `dragging` cursor holds wherever the pointer goes. Flagging :root
749
+ // would restyle every element on the page at each drag start and end.
750
+ const setDragging = (on) => {
751
+ dragging = on;
752
+ setCarouselState(viewport, "dragging", on);
753
+ };
754
+ /** The drag-free coast's frame, 0 when none is running. */
755
+ let coastFrame = 0;
756
+ const stopCoast = () => {
757
+ if (!coastFrame)
758
+ return false;
759
+ cancelAnimationFrame(coastFrame);
760
+ coastFrame = 0;
761
+ return true;
762
+ };
763
+ /**
764
+ * Drag-free release: the track keeps the pointer's speed and decays
765
+ * exponentially over the projected distance (x = target − d·e^(−kt), with
766
+ * k = v/d so the first frame moves at the release speed). The browser's
767
+ * smooth scroll would start from rest instead, a visible hitch. An end cuts
768
+ * the distance short, which raises k: the track brakes into the end.
769
+ */
770
+ const coast = (velocity) => {
771
+ const from = getPos();
772
+ const target = clampPos(from - projectRelease(velocity));
773
+ const distance = target - from;
774
+ if (reducedMotion.matches || Math.abs(distance) < 1) {
775
+ settle();
776
+ return;
777
+ }
778
+ const rate = Math.min(MAX_COAST_RATE, Math.abs(velocity) / Math.abs(distance));
779
+ const start = performance.now();
780
+ const frame = (now) => {
781
+ const left = distance * Math.exp(-rate * Math.max(0, now - start));
782
+ if (Math.abs(left) < 0.5) {
783
+ coastFrame = 0;
784
+ writePos(target);
785
+ settle();
786
+ return;
787
+ }
788
+ writePos(target - left);
789
+ coastFrame = requestAnimationFrame(frame);
790
+ };
791
+ coastFrame = requestAnimationFrame(frame);
792
+ };
793
+ const endDrag = (velocity) => {
794
+ setDragging(false);
795
+ // The rubber band's translate shrinks the scrollable width while it
796
+ // springs back, so a release past the end rests short of it: once the
797
+ // spring is done, finish the last few px.
798
+ if (container.style.translate && getPos() >= maxScroll() - 1) {
799
+ container.addEventListener("transitionend", () => {
800
+ if (!dragging && !coastFrame && pending == null)
801
+ jump(maxScroll());
802
+ }, { once: true, signal });
803
+ }
804
+ container.style.translate = "";
805
+ const projected = getPos() - projectRelease(velocity);
806
+ if (options.dragFree) {
807
+ coast(velocity);
808
+ return;
809
+ }
810
+ // snapping stays off ("gliding") until the scroll ends on the snap,
811
+ // or re-enabling it mid-scroll would re-snap from where the glide is
812
+ scrollToSnap(releaseTarget(snaps(), dragSnap, projected, velocity, options.skipSnaps));
813
+ };
814
+ if (options.draggable) {
815
+ trackDrag(viewport, {
816
+ axis: vertical ? "y" : "x",
817
+ signal,
818
+ canStart: ({ pointerType }) => pointerType === "mouse" && maxScroll() > 0,
819
+ onStart: () => {
820
+ pending = null;
821
+ stopCoast();
822
+ dragFrom = getPos();
823
+ dragSnap = nearestSnap(snaps(), dragFrom);
824
+ setGliding(true);
825
+ setDragging(true);
826
+ },
827
+ onMove: ({ offset }) => {
828
+ const wanted = dragFrom - logical(offset);
829
+ const clamped = clampPos(wanted);
830
+ jump(clamped);
831
+ // logical overshoot: positive pushes the content away from the start edge
832
+ const overshoot = rubberBand(clamped - wanted, clientSize() / 4);
833
+ container.style.translate = !overshoot
834
+ ? ""
835
+ : vertical
836
+ ? `0 ${overshoot}px`
837
+ : `${overshoot * sign}px 0`;
838
+ },
839
+ onEnd: ({ velocity }) => endDrag(logical(velocity)),
840
+ onCancel: () => endDrag(0),
841
+ });
842
+ // a dragged image or link would start a native drag-and-drop instead
843
+ viewport.addEventListener("dragstart", (event) => event.preventDefault(), { signal });
844
+ }
845
+ // --- Observers ---
846
+ const inViewObserver = new IntersectionObserver((entries) => {
847
+ inView = new Set(inView);
848
+ for (const entry of entries) {
849
+ const index = slides.indexOf(entry.target);
850
+ if (entry.isIntersecting)
851
+ inView.add(index);
852
+ else
853
+ inView.delete(index);
854
+ setCarouselState(entry.target, "in-view", entry.isIntersecting);
855
+ }
856
+ syncInert();
857
+ },
858
+ // 1px in on the scroll axis: a neighbour that only touches the viewport's
859
+ // edge counts as intersecting otherwise (edge-adjacent boxes do)
860
+ { root: viewport, rootMargin: vertical ? "-1px 0px" : "0px -1px" });
861
+ slides.forEach((slide) => inViewObserver.observe(slide));
862
+ // autoplay and auto-scroll pause while the carousel is off screen
863
+ const screenObserver = auto
864
+ ? new IntersectionObserver(([entry]) => {
865
+ onScreen = entry?.isIntersecting ?? true;
866
+ reconcile();
867
+ })
868
+ : null;
869
+ screenObserver?.observe(root);
870
+ // Fires once on observe too; only a real change of snap emits a select.
871
+ const resizeObserver = new ResizeObserver(() => {
872
+ invalidate();
873
+ buildDots();
874
+ if (pending == null && !dragging && !autoScrolling)
875
+ select(nearestSnap(snaps(), getPos()));
876
+ // rebuilt dots and regrouped snaps need the current state redrawn
877
+ render(selected);
878
+ reconcile();
879
+ });
880
+ resizeObserver.observe(viewport);
881
+ slides.forEach((slide) => resizeObserver.observe(slide));
882
+ // --- Controls ---
883
+ const api = {
884
+ goTo(index, instant) {
885
+ scrollToSnap(options.loop ? snapOfSlide(index) : index, instant, options.loop ? index : null);
886
+ },
887
+ goToNext: () => step(1),
888
+ goToPrev: () => step(-1),
889
+ selectedSnap: () => publicIndex(Math.max(0, selected)),
890
+ snapList: () => snaps().map((snap) => snap.pos),
891
+ revealSlide(index, instant) {
892
+ const slide = slides[index];
893
+ if (!slide)
894
+ return;
895
+ const at = getPos();
896
+ const start = startOf(slide.getBoundingClientRect(), viewport.getBoundingClientRect()) + at;
897
+ const end = start + sizeOf(slide.getBoundingClientRect());
898
+ const target = clampPos(start < at ? start : end > at + clientSize() ? end - clientSize() : at);
899
+ if (Math.abs(target - at) < 1)
900
+ return;
901
+ if (instant)
902
+ jump(target);
903
+ else
904
+ scrollToPos(target, behavior());
905
+ },
906
+ play() {
907
+ wanted = true;
908
+ reconcile();
909
+ },
910
+ stop() {
911
+ wanted = false;
912
+ reconcile();
913
+ },
914
+ isPlaying: () => running,
915
+ interact() {
916
+ if (!auto || !wanted)
917
+ return;
918
+ if (auto.stopOnInteraction) {
919
+ wanted = false;
920
+ reconcile();
921
+ }
922
+ else
923
+ reconcile(true);
924
+ },
925
+ vertical,
926
+ rtl,
927
+ };
928
+ if (controls) {
929
+ for (const [slot, direction] of [
930
+ ["prev", -1],
931
+ ["next", 1],
932
+ ]) {
933
+ root.querySelector(`[data-carousel-slot~="${slot}"]`)?.addEventListener("click", () => {
934
+ api.interact();
935
+ step(direction);
936
+ }, { signal });
937
+ }
938
+ }
939
+ // --- Start ---
940
+ setCarouselState(viewport, "free", options.dragFree);
941
+ buildDots();
942
+ // nothing has painted yet, so the start rotation needs no lock
943
+ if (options.loop)
944
+ rotate(options.startSnap % slides.length, false);
945
+ const start = options.loop ? snapOfSlide(options.startSnap) : options.startSnap;
946
+ jump(snaps()[start]?.pos ?? 0);
947
+ select(nearestSnap(snaps(), getPos()));
948
+ syncInert();
949
+ if (auto) {
950
+ // continuous motion never starts on its own for reduced-motion users
951
+ wanted = auto.playOnInit && !(auto.mode === "auto-scroll" && reducedMotion.matches);
952
+ reconcile();
953
+ }
954
+ signal.addEventListener("abort", () => {
955
+ cancelAnimationFrame(frame);
956
+ cancelAnimationFrame(coastFrame);
957
+ clearTimeout(autoTimer);
958
+ cancelAnimationFrame(autoFrame);
959
+ inViewObserver.disconnect();
960
+ screenObserver?.disconnect();
961
+ resizeObserver.disconnect();
962
+ if (dragging)
963
+ setDragging(false);
964
+ for (const token of ["gliding", "settling", "free"]) {
965
+ setCarouselState(viewport, token, false);
966
+ }
967
+ setCarouselState(root, "playing", false);
968
+ container.style.translate = "";
969
+ for (const slide of slides) {
970
+ slide.style.order = "";
971
+ slide.inert = false;
972
+ setCarouselState(slide, "in-view", false);
973
+ setCarouselState(slide, "snapped", false);
974
+ }
975
+ // put the template dot back so a re-insert can build from it again
976
+ if (templateDot)
977
+ dotsNode?.replaceChildren(templateDot);
978
+ delete root._carousel;
979
+ }, { once: true });
980
+ root._carousel = api;
981
+ return api;
982
+ }
983
+ // --- Thumbs ---
984
+ /**
985
+ * @description Runs a thumb strip on its own engine (options from
986
+ * `data-carousel-thumbs-*` on the thumbs slot; drag-free by default) and links
987
+ * it to the main carousel: a thumb click steps the main carousel there, and
988
+ * each main selection marks its thumb (`active` token and `aria-current`) and
989
+ * scrolls the strip just enough to show it.
990
+ *
991
+ * @param main - The main carousel's API.
992
+ * @param root - The main carousel root (its `zazz:carousel-select` drives the strip).
993
+ * @param thumbsNode - The thumbs slot.
994
+ * @param signal - Aborting it tears the strip down.
995
+ * @returns The strip's API, or null when it has no viewport or container.
996
+ */
997
+ function linkThumbs(main, root, thumbsNode, signal) {
998
+ const viewport = thumbsNode.querySelector('[data-carousel-slot~="viewport"]');
999
+ if (!viewport)
1000
+ return null;
1001
+ const strip = createCarousel(thumbsNode, viewport, signal, {
1002
+ prefix: "data-carousel-thumbs-",
1003
+ defaults: { dragFree: true },
1004
+ controls: false,
1005
+ });
1006
+ if (!strip)
1007
+ return null;
1008
+ const thumbs = [
1009
+ ...viewport.querySelectorAll('[data-carousel-slot~="container"] > [data-carousel-slot~="slide"]'),
1010
+ ];
1011
+ thumbs.forEach((thumb, index) => thumb.addEventListener("click", () => {
1012
+ main.interact();
1013
+ main.goTo(index);
1014
+ }, { signal }));
1015
+ const mark = (index, instant) => {
1016
+ thumbs.forEach((thumb, i) => {
1017
+ setCarouselState(thumb, "active", i === index);
1018
+ if (i === index)
1019
+ thumb.setAttribute("aria-current", "true");
1020
+ else
1021
+ thumb.removeAttribute("aria-current");
1022
+ });
1023
+ strip.revealSlide(index, instant);
1024
+ };
1025
+ root.addEventListener("zazz:carousel-select", (event) => mark(event.detail.index), { signal });
1026
+ mark(main.selectedSnap(), true);
1027
+ signal.addEventListener("abort", () => {
1028
+ for (const thumb of thumbs) {
1029
+ setCarouselState(thumb, "active", false);
1030
+ thumb.removeAttribute("aria-current");
1031
+ }
1032
+ }, { once: true });
1033
+ return strip;
1034
+ }
1035
+ export { createCarousel, linkThumbs, loopLead, loopShift, loopOrders, projectRelease, readAutoOptions, releaseTarget, setCarouselState, };