@zazz-ui/core 0.13.0 → 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 +93 -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 +4 -3
  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
package/src/base/embla.js DELETED
@@ -1,878 +0,0 @@
1
- "use strict";
2
- /**
3
- * @fileoverview Embla Carousel initialization and controls.
4
- * @description Discovers carousel roots (`<ui-carousel>` or `[data-ui~="carousel"]`),
5
- * initializes Embla instances with optional plugins, and wires navigation,
6
- * keyboard, and dialog-open behaviors (subscribing to `zazz:dialog-open`
7
- * from base/dialog-lifecycle.ts; lightbox choreography lives in lightbox.ts).
8
- *
9
- * Structure: root is the element itself; parts are slots (`data-carousel-slot="<part>"`):
10
- * - root (`<ui-carousel>` | `[data-ui~="carousel"]`): Carousel container; holds all config attributes
11
- * - `carousel-viewport`: Visible window (required)
12
- * - `carousel-container`: Slides flex track
13
- * - `carousel-slide`: Individual slide
14
- * - `carousel-prev` / `carousel-next`: Navigation buttons (optional)
15
- * - `carousel-dots` / `carousel-dot`: Dot pagination container and template dot (optional)
16
- * - `carousel-thumbs`: Linked thumb carousel container (optional)
17
- *
18
- * thumb navigation (on `data-carousel-slot="thumbs"`):
19
- * - `data-carousel-thumbs-*`: thumb carousel options (defaults: containScroll keepSnaps, dragFree true)
20
- * - Syncs with the main carousel in the same root
21
- *
22
- * Lifecycle and dialog start index:
23
- * - `data-carousel-init`: Set by script when a carousel is initialized
24
- * - `data-carousel-start`: On a trigger; slide index to open to (pairs with commandfor)
25
- * - `data-carousel-start-index`: Set on root by script; consumed when dialog opens
26
- * - `data-carousel-keyboard`: Set to `"false"` to disable ArrowLeft/ArrowRight navigation
27
- *
28
- * Configuration (on the carousel root: `<ui-carousel>` or `[data-ui~="carousel"]`):
29
- * - `data-carousel-*`: Core Embla options
30
- * - `data-carousel-plugins`: Space-separated plugin slugs (`autoplay`, `auto-scroll`, `class-names`)
31
- * - `data-carousel-autoplay-*`: Autoplay plugin options (requires `autoplay` in plugins)
32
- * - `data-carousel-auto-scroll-*`: Auto scroll plugin options (requires `auto-scroll` in plugins)
33
- * - `data-carousel-class-names-*`: Class names plugin options (requires `class-names` in plugins)
34
- *
35
- * Built on Embla v9 (`9.0.0-rc04`). Core options pass straight through, so they
36
- * use Embla's v9 names (`data-carousel-start-snap`, `data-carousel-draggable`,
37
- * `data-carousel-drag-free="snap"`, …).
38
- *
39
- * Autoplay and Auto Scroll: the kit owns their interaction handling (it sets
40
- * Embla's `defaultInteraction: false`) and adds two kit-level options, read
41
- * from the plugin's own prefix (`data-carousel-autoplay-*`, `data-carousel-auto-scroll-*`):
42
- * - `…-play-on-init`: `"false"` leaves the plugin stopped until `play()` (default plays)
43
- * - `…-stop-on-interaction`: `"false"` holds the plugin during a drag or slide focus and
44
- * resumes it after; Prev/Next, the dots, the thumbs, and the arrow keys restart its
45
- * delay. By default (`true`) any of those stops it for good.
46
- * The kit also restarts a playing plugin after Embla's `reinit` (a resize or a
47
- * breakpoint change re-creates plugins, which Embla v9 leaves stopped).
48
- *
49
- * @see https://www.embla-carousel.com/api/options/
50
- * @see https://www.embla-carousel.com/plugins/autoplay/
51
- * @see https://www.embla-carousel.com/plugins/auto-scroll/
52
- * @see https://www.embla-carousel.com/plugins/class-names/
53
- *
54
- * @example
55
- * data-carousel-loop="true"
56
- *
57
- * @example
58
- * data-carousel-align="start"
59
- *
60
- * @example
61
- * data-carousel-plugins="autoplay" data-carousel-autoplay-delay="3000"
62
- *
63
- * @example
64
- * data-carousel-plugins="auto-scroll" data-carousel-auto-scroll-speed="2"
65
- *
66
- * @example
67
- * data-carousel-plugins="class-names" data-carousel-class-names-snapped="is-snapped"
68
- *
69
- * @example Barebones carousel (4 text slides; auto-inits on DOMContentLoaded):
70
- * <div data-ui="carousel">
71
- * <div data-carousel-slot="viewport">
72
- * <div data-carousel-slot="container">
73
- * <div data-carousel-slot="slide">Slide 1</div>
74
- * <div data-carousel-slot="slide">Slide 2</div>
75
- * <div data-carousel-slot="slide">Slide 3</div>
76
- * <div data-carousel-slot="slide">Slide 4</div>
77
- * </div>
78
- * </div>
79
- * <button type="button" data-carousel-slot="prev">Prev</button>
80
- * <button type="button" data-carousel-slot="next">Next</button>
81
- * </div>
82
- */
83
- import { Utils } from "./utils.js";
84
- import { registerRefresh } from "./zazz-element.js";
85
- // Bare specifiers resolve through the page's import map in browsers (pinned
86
- // jsDelivr URLs; see `head.ts`) and through node_modules in tests/bundlers.
87
- import EmblaCarousel from "embla-carousel";
88
- import EmblaCarouselAutoplay from "embla-carousel-autoplay";
89
- import EmblaCarouselAutoScroll from "embla-carousel-auto-scroll";
90
- import EmblaCarouselClassNames from "embla-carousel-class-names";
91
- /**
92
- * @description Parses a space-separated `data-carousel-plugins` value into
93
- * plugin slug tokens. Empty / null / whitespace-only values yield `[]`.
94
- *
95
- * @param value - Raw attribute value (or `null` when absent).
96
- * @returns Plugin slug tokens in authoring order.
97
- */
98
- function parseCarouselPlugins(value) {
99
- if (!value)
100
- return [];
101
- return value.trim().split(/\s+/).filter(Boolean);
102
- }
103
- /**
104
- * Map of plugin slug → Embla factory. Slugs match Embla package names
105
- * (`embla-carousel-auto-scroll`, etc.).
106
- */
107
- const PLUGIN_BY_SLUG = {
108
- autoplay: (node) => EmblaCarouselAutoplay(readAutoPluginOptions(node, "data-carousel-autoplay-")),
109
- "auto-scroll": (node) => EmblaCarouselAutoScroll(readAutoPluginOptions(node, "data-carousel-auto-scroll-")),
110
- "class-names": (node) => EmblaCarouselClassNames(readCarouselOptions(node, "data-carousel-class-names-")),
111
- };
112
- /**
113
- * @description Reads a node's prefixed `data-carousel-*` attributes as an
114
- * options object of the shape Embla (or one of its plugins) expects.
115
- *
116
- * Attributes are strings, so the single type assertion into Embla's option
117
- * types lives here (Embla validates its own options at runtime).
118
- *
119
- * @param node - Element carrying the configuration attributes.
120
- * @param prefix - Attribute prefix, e.g. `"data-carousel-autoplay-"`.
121
- * @returns The parsed attributes, typed as `T`.
122
- * @private
123
- */
124
- function readCarouselOptions(node, prefix) {
125
- return Utils.parseDataAttributes(node, prefix);
126
- }
127
- /** The two plugins the kit drives: their `plugins()` key, attribute prefix, and interaction event. */
128
- const AUTO_PLUGINS = [
129
- {
130
- key: "autoplay",
131
- prefix: "data-carousel-autoplay-",
132
- interaction: "autoplay:interaction",
133
- },
134
- {
135
- key: "autoScroll",
136
- prefix: "data-carousel-auto-scroll-",
137
- interaction: "autoscroll:interaction",
138
- },
139
- ];
140
- /**
141
- * @description Reads an Autoplay / Auto Scroll plugin's attributes as Embla
142
- * options: drops the kit-level `playOnInit` / `stopOnInteraction` and sets
143
- * `defaultInteraction: false`, so the plugin reports interactions
144
- * (`autoplay:interaction`) and `bindAutoPlugins` decides what they do.
145
- * @private
146
- */
147
- function readAutoPluginOptions(node, prefix) {
148
- const options = Utils.parseDataAttributes(node, prefix);
149
- delete options.playOnInit;
150
- delete options.stopOnInteraction;
151
- return { ...options, defaultInteraction: false };
152
- }
153
- /** Per-carousel manual-step handlers, one per driven plugin (see onManualNavigation). */
154
- const manualStepHandlers = new WeakMap();
155
- /** Form fields Embla never starts a drag on (its DragHandler `focusNodes`). */
156
- const NON_DRAG_TARGETS = ["INPUT", "SELECT", "TEXTAREA"];
157
- /**
158
- * @description Whether a pointer down starts an Embla drag. Embla v9 emits
159
- * `pointerdown` before its own checks, then ignores a non-primary mouse button
160
- * or a press in a form field, and no `pointerup` follows; state set on such a
161
- * pointer down would never clear.
162
- * @private
163
- */
164
- function startsDrag(evt) {
165
- if (evt instanceof MouseEvent && evt.button !== 0)
166
- return false;
167
- return !(evt.target instanceof Element && NON_DRAG_TARGETS.includes(evt.target.nodeName));
168
- }
169
- /**
170
- * @description Drives the Autoplay and Auto Scroll plugins the way the kit
171
- * documents them, on top of Embla v9's bare plugins (which neither start on
172
- * their own nor survive a `reinit`):
173
- * - plays on init unless `…-play-on-init="false"`;
174
- * - a pointer down or slide focus stops the plugin; with
175
- * `…-stop-on-interaction="false"` it only holds it, and the pointer up or
176
- * focus leaving the slides resumes it;
177
- * - after a `reinit` (resize, breakpoint change, `reInit()`), which re-creates
178
- * the plugin stopped, resumes it if it was playing, or is still waiting to
179
- * play (no second snap yet, or the carousel was inactive at a breakpoint);
180
- * - registers the manual-step handler `onManualNavigation` runs.
181
- *
182
- * Takes the plugin instances themselves: `plugins()` is empty while the
183
- * carousel is inactive (`active: false` at the current breakpoint).
184
- * @private
185
- */
186
- function bindAutoPlugins(emblaApi, node, plugins) {
187
- const handlers = [];
188
- for (const { key, prefix, interaction } of AUTO_PLUGINS) {
189
- const plugin = plugins.find((p) => p.name === key);
190
- if (!plugin)
191
- continue;
192
- const { playOnInit, stopOnInteraction } = readCarouselOptions(node, prefix);
193
- const holds = stopOnInteraction === false;
194
- // `pending`: should play as soon as it can. `held`: what paused it with
195
- // stop-on-interaction false (its end resumes it), or "" when nothing does.
196
- let pending = playOnInit !== false;
197
- let held = "";
198
- let wasPlaying = false;
199
- const playIfPending = () => {
200
- if (!pending || emblaApi.snapList().length <= 1)
201
- return;
202
- // An inactive carousel never inits its plugins, and play() before init throws.
203
- if (!emblaApi.internalEngine().options.active)
204
- return;
205
- plugin.play();
206
- // play() does nothing while the plugin itself is inactive; keep waiting then.
207
- pending = !plugin.isPlaying();
208
- };
209
- // Embla re-creates plugins on reinit by calling destroy() then init() on the
210
- // same object, and destroy() stops it; note whether it was playing first.
211
- const destroy = plugin.destroy;
212
- plugin.destroy = () => {
213
- wasPlaying = plugin.isPlaying();
214
- destroy();
215
- };
216
- emblaApi.on("reinit", () => {
217
- pending ||= wasPlaying;
218
- wasPlaying = false;
219
- // A reinit mid-drag drops the drag, so its pointer up never comes.
220
- if (held === "pointer") {
221
- held = "";
222
- pending = true;
223
- }
224
- if (!held)
225
- playIfPending();
226
- });
227
- emblaApi.on(interaction, (_api, { detail }) => {
228
- const { interaction: type, originalEvent } = detail;
229
- if (type === "pointerdown" || type === "slidefocus") {
230
- // A pointerdown's originalEvent is Embla's event model; its detail is the DOM event.
231
- const pointer = originalEvent instanceof Event ? null : originalEvent.detail;
232
- if (type === "pointerdown" && pointer && !startsDrag(pointer))
233
- return;
234
- if (!plugin.isPlaying() && !held)
235
- return;
236
- held = holds ? (type === "pointerdown" ? "pointer" : "focus") : "";
237
- pending = false;
238
- plugin.stop();
239
- }
240
- else if ((type === "pointerup" && held === "pointer") ||
241
- (type === "slidefocusout" && held === "focus")) {
242
- held = "";
243
- plugin.play();
244
- }
245
- });
246
- handlers.push(() => {
247
- pending = false;
248
- if (holds)
249
- plugin.reset();
250
- else
251
- plugin.stop();
252
- });
253
- playIfPending();
254
- }
255
- if (handlers.length)
256
- manualStepHandlers.set(emblaApi, handlers);
257
- }
258
- /**
259
- * @description The kit's own Embla plugin, placed first in the plugin list so
260
- * its `pointerdown` listener runs before any other plugin's, on init and
261
- * after every reinit (Embla re-registers plugins in list order):
262
- * - vetoes a drag when every slide already fits (one snap): Embla would still
263
- * rubber-band. Returning false cancels Embla's drag and the later listeners
264
- * (Class Names' pointer-down class, the plugins' interactions). Skipped when
265
- * the author set `data-carousel-draggable`.
266
- * - marks a drag as a `dragging` token on the viewport, and `data-ui-dragging`
267
- * on the document root for the page-wide grabbing cursor (a `body:has(…) *`
268
- * rule would restyle the whole page on every DOM insertion). Cleared on
269
- * pointer up and on destroy (a reinit mid-drag drops the pointer up).
270
- * @private
271
- */
272
- function KitDragPlugin(viewport, vetoesDrag) {
273
- const root = viewport.ownerDocument.documentElement;
274
- let api;
275
- const setDragging = (on) => {
276
- setCarouselState(viewport, "dragging", on);
277
- root.toggleAttribute("data-ui-dragging", on);
278
- };
279
- const onPointerDown = (emblaApi, { detail }) => {
280
- if (vetoesDrag && !emblaApi.canGoToPrev() && !emblaApi.canGoToNext())
281
- return false;
282
- if (startsDrag(detail))
283
- setDragging(true);
284
- };
285
- const onPointerUp = () => setDragging(false);
286
- return {
287
- name: "zazzDrag",
288
- options: {},
289
- init(emblaApi) {
290
- api = emblaApi;
291
- emblaApi.on("pointerdown", onPointerDown).on("pointerup", onPointerUp);
292
- },
293
- destroy() {
294
- api?.off("pointerdown", onPointerDown).off("pointerup", onPointerUp);
295
- setDragging(false);
296
- },
297
- };
298
- }
299
- // --- Manual navigation ---
300
- /**
301
- * @description Treats a manual step (Prev/Next, a dot, a thumb, an arrow key) as
302
- * user interaction for the Autoplay and Auto Scroll plugins, which on their own
303
- * only count a pointer-down on the viewport. Without it the plugin's timer keeps
304
- * running, and a tick that lands just after a click moves a second slide.
305
- * `stop-on-interaction` (default true) stops the plugin; `false` restarts its delay.
306
- * This is the pattern Embla's own examples use for navigation buttons.
307
- * @private
308
- */
309
- function onManualNavigation(emblaApi) {
310
- for (const handler of manualStepHandlers.get(emblaApi) ?? [])
311
- handler();
312
- }
313
- // --- Active-index sync ---
314
- /**
315
- * @description Adds or removes one token of an element's `data-carousel-state`
316
- * list, leaving the other tokens in place.
317
- * @private
318
- */
319
- function setCarouselState(node, token, on) {
320
- const tokens = (node.getAttribute("data-carousel-state") ?? "").split(/\s+/).filter(Boolean);
321
- const next = on ? [...new Set([...tokens, token])] : tokens.filter((t) => t !== token);
322
- if (next.length)
323
- node.setAttribute("data-carousel-state", next.join(" "));
324
- else
325
- node.removeAttribute("data-carousel-state");
326
- }
327
- /**
328
- * @description Mirrors Embla's view state onto the slides as `data-carousel-state`
329
- * tokens: `in-view` for slides inside the viewport and `snapped` for the slides
330
- * of the selected snap (what the ClassNames plugin exposes as classes).
331
- * @private
332
- */
333
- function bindSlideStates(emblaApi) {
334
- const update = () => {
335
- const slides = emblaApi.slideNodes();
336
- const inView = new Set(emblaApi.slidesInView());
337
- const snapped = new Set(emblaApi.internalEngine().scrollSnapList.slidesBySnap[emblaApi.selectedSnap()] ?? []);
338
- slides.forEach((slide, index) => {
339
- setCarouselState(slide, "in-view", inView.has(index));
340
- setCarouselState(slide, "snapped", snapped.has(index));
341
- });
342
- };
343
- emblaApi.on("reinit", update).on("select", update).on("slidesinview", update);
344
- update();
345
- }
346
- /**
347
- * @description Sets `data-carousel-state="active"` on the node at `selected` and clears it
348
- * from every other node: the shared "which one is current" marker used by
349
- * both dot pagination and thumb navigation.
350
- *
351
- * @param nodes - Candidate nodes, in slide order.
352
- * @param selected - The active index.
353
- * @param options - Set `ariaCurrent` to also toggle `aria-current` (thumbs only;
354
- * dot pagination is purely visual).
355
- * @private
356
- */
357
- function setActiveIndex(nodes, selected, options = {}) {
358
- nodes.forEach((node, idx) => {
359
- const active = idx === selected;
360
- setCarouselState(node, "active", active);
361
- if (!options.ariaCurrent)
362
- return;
363
- if (active) {
364
- node.setAttribute("aria-current", "true");
365
- }
366
- else {
367
- node.removeAttribute("aria-current");
368
- }
369
- });
370
- }
371
- // --- Dot navigation ---
372
- /**
373
- * @description Adds dot navigation buttons and click handlers for an Embla carousel.
374
- *
375
- * @param emblaApi - The Embla carousel API instance.
376
- * @param dotsNode - Container element for dot navigation.
377
- * @param signal - Aborts the dot click listeners on teardown.
378
- * @returns Cleanup function to remove dots.
379
- */
380
- const addDotBtnsAndClickHandlers = (emblaApi, dotsNode, signal) => {
381
- if (!dotsNode)
382
- return;
383
- const templateDot = dotsNode.querySelector('[data-carousel-slot~="dot"]');
384
- if (!templateDot)
385
- return;
386
- let dotNodes = [];
387
- /**
388
- * @description Creates dot buttons for each slide and binds click handlers.
389
- *
390
- * @private
391
- */
392
- const addDotBtnsWithClickHandlers = () => {
393
- const snapCount = emblaApi.snapList().length;
394
- dotsNode.innerHTML = "";
395
- if (snapCount <= 1) {
396
- dotNodes = [];
397
- return;
398
- }
399
- dotNodes = [];
400
- for (let i = 0; i < snapCount; i++) {
401
- const dot = templateDot.cloneNode(true);
402
- dotNodes.push(dot);
403
- dotsNode.appendChild(dot);
404
- dot.addEventListener("click", () => {
405
- onManualNavigation(emblaApi);
406
- emblaApi.goTo(i);
407
- }, { signal });
408
- }
409
- };
410
- /**
411
- * @description Updates the active state of dot buttons based on the current slide.
412
- *
413
- * @private
414
- */
415
- const toggleDotBtnsActive = () => {
416
- if (!dotNodes.length)
417
- return;
418
- setActiveIndex(dotNodes, emblaApi.selectedSnap());
419
- };
420
- emblaApi
421
- .on("reinit", addDotBtnsWithClickHandlers)
422
- .on("reinit", toggleDotBtnsActive)
423
- .on("select", toggleDotBtnsActive);
424
- addDotBtnsWithClickHandlers();
425
- toggleDotBtnsActive();
426
- return () => {
427
- dotsNode.innerHTML = "";
428
- };
429
- };
430
- // --- thumb navigation ---
431
- /**
432
- * @description Adds click handlers on thumb slides to scroll the main carousel.
433
- *
434
- * @param emblaApiMain - Main carousel API instance.
435
- * @param emblaApiThumb - thumb carousel API instance.
436
- * @param signal - Aborts the thumb click listeners on teardown.
437
- */
438
- const addThumbClickHandlers = (emblaApiMain, emblaApiThumb, signal) => {
439
- const slidesthumbs = emblaApiThumb.slideNodes();
440
- slidesthumbs.forEach((slideNode, index) => {
441
- slideNode.addEventListener("click", () => {
442
- onManualNavigation(emblaApiMain);
443
- emblaApiMain.goTo(index);
444
- }, { signal });
445
- });
446
- };
447
- /**
448
- * @description Keeps the thumb carousel and active state in sync with the main carousel.
449
- *
450
- * @param emblaApiMain - Main carousel API instance.
451
- * @param emblaApiThumb - thumb carousel API instance.
452
- */
453
- const addTogglethumbsActive = (emblaApiMain, emblaApiThumb) => {
454
- const slidesthumbs = emblaApiThumb.slideNodes();
455
- /**
456
- * @description Scrolls thumbs to the selected snap and toggles active classes.
457
- *
458
- * @private
459
- */
460
- const toggleThumbBtnsActive = () => {
461
- const selected = emblaApiMain.selectedSnap();
462
- emblaApiThumb.goTo(selected);
463
- setActiveIndex(slidesthumbs, selected, { ariaCurrent: true });
464
- };
465
- emblaApiMain.on("select", toggleThumbBtnsActive);
466
- toggleThumbBtnsActive();
467
- };
468
- // --- Drag-aware click suppression ---
469
- /**
470
- * Deadline (ms, `performance.now()`) until which invoker `command` events are
471
- * cancelled because a carousel drag just ended. Set by bindDragClickSuppression
472
- * for command-bearing slides (the lightbox stage) and enforced by
473
- * initCommandDragGuard. A bare `click` guard is not enough: the native /
474
- * polyfilled invoker opens the dialog from its own `command` dispatch.
475
- */
476
- let suppressCommandsUntil = 0;
477
- /**
478
- * @description Suppresses click activation immediately after a drag gesture.
479
- *
480
- * This prevents click-style actions (invoker commands, thumb navigation clicks)
481
- * from firing when the intent was dragging the carousel.
482
- *
483
- * @param root - Embla root/subtree to monitor.
484
- * @param emblaApi - Carousel instance tied to this root.
485
- * @param clickSelector - Click targets to suppress after dragging.
486
- * @param options - Per-carousel drag tolerance.
487
- * @param signal - Aborts the pointer/click listeners on teardown.
488
- */
489
- function bindDragClickSuppression(root, emblaApi, clickSelector, options = {}, signal) {
490
- const DRAG_THRESHOLD_PX = options.dragThresholdPx ?? 6;
491
- const SUPPRESS_WINDOW_MS = 250;
492
- // Slides that open a dialog (command="show-modal") also need command suppression.
493
- const guardsCommands = clickSelector.includes("commandfor");
494
- let pointerDown = false;
495
- let moved = false;
496
- let startX = 0;
497
- let startY = 0;
498
- let lastX = 0;
499
- let lastY = 0;
500
- let snapAtDown = 0;
501
- let suppressUntil = 0;
502
- const pointerDistance = () => Math.hypot(lastX - startX, lastY - startY);
503
- root.addEventListener("pointerdown", (e) => {
504
- if (!(e instanceof PointerEvent))
505
- return;
506
- if (e.pointerType === "mouse" && e.button !== 0)
507
- return;
508
- pointerDown = true;
509
- moved = false;
510
- startX = e.clientX;
511
- startY = e.clientY;
512
- lastX = e.clientX;
513
- lastY = e.clientY;
514
- snapAtDown = emblaApi.selectedSnap();
515
- }, { passive: true, signal });
516
- root.addEventListener("pointermove", (e) => {
517
- if (!pointerDown || !(e instanceof PointerEvent))
518
- return;
519
- lastX = e.clientX;
520
- lastY = e.clientY;
521
- if (moved)
522
- return;
523
- if (pointerDistance() >= DRAG_THRESHOLD_PX)
524
- moved = true;
525
- }, { passive: true, signal });
526
- const finalizePointer = () => {
527
- if (pointerDown && moved) {
528
- suppressUntil = performance.now() + SUPPRESS_WINDOW_MS;
529
- if (guardsCommands)
530
- suppressCommandsUntil = suppressUntil;
531
- }
532
- pointerDown = false;
533
- moved = false;
534
- };
535
- root.addEventListener("pointerup", finalizePointer, { passive: true, signal });
536
- root.addEventListener("pointercancel", finalizePointer, { passive: true, signal });
537
- emblaApi.on("pointerup", finalizePointer);
538
- // Touch/trackpad drags can move with tiny deltas. Treat Embla scroll as drag intent,
539
- // but lightbox openers need extra tolerance so minor carousel settle does not block clicks.
540
- emblaApi.on("scroll", () => {
541
- if (!pointerDown)
542
- return;
543
- if (guardsCommands) {
544
- if (pointerDistance() >= DRAG_THRESHOLD_PX || emblaApi.selectedSnap() !== snapAtDown) {
545
- moved = true;
546
- }
547
- return;
548
- }
549
- moved = true;
550
- });
551
- root.addEventListener("click", (e) => {
552
- if (performance.now() > suppressUntil)
553
- return;
554
- const target = e.target instanceof Element ? e.target.closest(clickSelector) : null;
555
- if (!target || !root.contains(target))
556
- return;
557
- e.preventDefault();
558
- e.stopImmediatePropagation();
559
- }, { capture: true, signal });
560
- }
561
- let commandDragGuardBound = false;
562
- /**
563
- * @description Cancels invoker `command` events fired right after a carousel drag.
564
- *
565
- * Lightbox stage slides carry `command="show-modal"`, so a drag would both scroll
566
- * the carousel and open the dialog. The `command` event (native or polyfill) is
567
- * the single point that runs the built-in command, and it is cancelable, so we
568
- * preventDefault() it within the drag-suppress window. Bound once on `document` in
569
- * the capture phase; `command` does not bubble, but capture still reaches it.
570
- */
571
- function initCommandDragGuard() {
572
- if (commandDragGuardBound)
573
- return;
574
- commandDragGuardBound = true;
575
- document.addEventListener("command", (e) => {
576
- if (e.cancelable && performance.now() <= suppressCommandsUntil)
577
- e.preventDefault();
578
- }, true);
579
- }
580
- // --- Carousel initialization ---
581
- /**
582
- * @description Initializes a single Embla carousel root.
583
- *
584
- * Configures the carousel from its `data-carousel-*` attributes, wires navigation
585
- * (prev/next, dots, thumbs), and stores the API on `root._emblaApi`. Idempotent:
586
- * skips roots that are already initialized or inside a closed dialog (no
587
- * measurable viewport until open).
588
- *
589
- * Called by `initEmblaCarousels()` for attribute-form (`[data-ui~="carousel"]`) markup and by
590
- * the `<ui-carousel>` web component on connect.
591
- *
592
- * @param emblaNode - The carousel root element.
593
- */
594
- function initEmblaRoot(emblaNode) {
595
- if (emblaNode.hasAttribute("data-carousel-init"))
596
- return;
597
- // Defer init inside closed dialogs: viewport has no measurable size until open
598
- if (emblaNode.closest("dialog:not([open])"))
599
- return;
600
- emblaNode.setAttribute("data-carousel-init", "");
601
- const emblathumbsNode = emblaNode.querySelector('[data-carousel-slot~="thumbs"]');
602
- const emblaViewportNode = emblathumbsNode
603
- ? emblaNode.querySelector('[data-carousel-slot~="viewport"]:not([data-carousel-slot~="thumbs"] *)')
604
- : emblaNode.querySelector('[data-carousel-slot~="viewport"]');
605
- const emblaPrevButtonNode = emblaNode.querySelector('[data-carousel-slot~="prev"]');
606
- const emblaNextButtonNode = emblaNode.querySelector('[data-carousel-slot~="next"]');
607
- const emblaDotsNode = emblaNode.querySelector('[data-carousel-slot~="dots"]');
608
- if (!emblaViewportNode)
609
- return;
610
- if (!emblaViewportNode.hasAttribute("tabindex")) {
611
- emblaViewportNode.setAttribute("tabindex", "0");
612
- }
613
- const apiOptions = readCarouselOptions(emblaNode, "data-carousel-");
614
- // Keep kit-only / plugin keys out of core Embla options
615
- Object.keys(apiOptions).forEach(function (key) {
616
- if (key === "name" ||
617
- key === "keyboard" ||
618
- key === "plugins" ||
619
- key.startsWith("autoplay") ||
620
- key.startsWith("autoScroll") ||
621
- key.startsWith("classNames")) {
622
- delete apiOptions[key];
623
- }
624
- });
625
- // Plugins load only when listed in data-carousel-plugins; option attrs alone
626
- // do not enable them. Unknown slugs are ignored.
627
- // The kit's drag plugin goes first (see KitDragPlugin).
628
- const plugins = [
629
- KitDragPlugin(emblaViewportNode, !("draggable" in apiOptions)),
630
- ];
631
- for (const slug of parseCarouselPlugins(emblaNode.getAttribute("data-carousel-plugins"))) {
632
- const create = PLUGIN_BY_SLUG[slug];
633
- if (!create)
634
- continue;
635
- plugins.push(create(emblaNode));
636
- }
637
- // The options come from untyped data attributes; Embla validates at runtime.
638
- const emblaApi = EmblaCarousel(emblaViewportNode, apiOptions, plugins);
639
- bindSlideStates(emblaApi);
640
- bindAutoPlugins(emblaApi, emblaNode, plugins);
641
- emblaNode._emblaApi = emblaApi;
642
- // One controller per root scopes every carousel listener below; the owner
643
- // (`<ui-carousel>` disconnectedCallback) aborts it on teardown so the DOM
644
- // listeners are removed alongside the destroyed Embla instance.
645
- const controller = new AbortController();
646
- const { signal } = controller;
647
- emblaNode._emblaController = controller;
648
- if (emblaPrevButtonNode) {
649
- emblaPrevButtonNode.addEventListener("click", () => {
650
- onManualNavigation(emblaApi);
651
- emblaApi.goToPrev();
652
- }, { signal });
653
- }
654
- if (emblaNextButtonNode) {
655
- emblaNextButtonNode.addEventListener("click", () => {
656
- onManualNavigation(emblaApi);
657
- emblaApi.goToNext();
658
- }, { signal });
659
- }
660
- if (emblaDotsNode) {
661
- addDotBtnsAndClickHandlers(emblaApi, emblaDotsNode, signal);
662
- }
663
- // Any command-bearing slide (e.g. a lightbox stage slide that opens the
664
- // dialog) needs its click suppressed when it was really a drag.
665
- if (emblaNode.querySelector('[data-carousel-slot~="slide"][commandfor]')) {
666
- bindDragClickSuppression(emblaNode, emblaApi, '[data-carousel-slot~="slide"][commandfor]', { dragThresholdPx: 14 }, signal);
667
- }
668
- if (emblathumbsNode) {
669
- const emblathumbsViewportNode = emblathumbsNode.querySelector('[data-carousel-slot~="viewport"]');
670
- if (emblathumbsViewportNode) {
671
- const thumbDefaults = { containScroll: "keepSnaps", dragFree: true };
672
- const thumbOptions = readCarouselOptions(emblathumbsNode, "data-carousel-thumbs-");
673
- const emblaApiThumb = EmblaCarousel(emblathumbsViewportNode, {
674
- ...thumbDefaults,
675
- ...thumbOptions,
676
- });
677
- emblaNode._emblaApiThumb = emblaApiThumb;
678
- addThumbClickHandlers(emblaApi, emblaApiThumb, signal);
679
- addTogglethumbsActive(emblaApi, emblaApiThumb);
680
- bindDragClickSuppression(emblathumbsNode, emblaApiThumb, '[data-carousel-slot~="slide"]', {}, signal);
681
- }
682
- }
683
- }
684
- /**
685
- * @description Initializes all Embla carousels within a scope.
686
- *
687
- * Discovers carousel elements via `:is(ui-carousel, [data-ui~="carousel"])` and configures them
688
- * based on their data attributes. Roots managed by the `<ui-carousel>` web
689
- * component are skipped: they initialize themselves via `connectedCallback()`.
690
- *
691
- * @param scope - Root element to search within. Defaults to `document`.
692
- */
693
- function initEmblaCarousels(scope) {
694
- const root = scope || document;
695
- const emblaRoots = root.querySelectorAll(':is(ui-carousel, [data-ui~="carousel"])');
696
- emblaRoots.forEach(function (emblaNode) {
697
- // <ui-carousel> elements own their lifecycle (init on connect, destroy
698
- // on disconnect); double-initializing would leak a second Embla instance.
699
- if (emblaNode.closest("ui-carousel"))
700
- return;
701
- initEmblaRoot(emblaNode);
702
- });
703
- }
704
- // --- Dialog open subscription ---
705
- /**
706
- * @description Reacts to dialogs opening (via `zazz:dialog-open` from
707
- * base/dialog-lifecycle.ts) with the carousel-domain work:
708
- * initializes class-form roots that deferred while the dialog was
709
- * `display: none`, applies a stored `data-carousel-start-index`, and focuses
710
- * the viewport for keyboard navigation.
711
- *
712
- * Listens on `document`, so it runs after any dialog- or ancestor-level
713
- * subscriber (`<ui-carousel>` self-init, `<ui-lightbox>` choreography).
714
- */
715
- function initDialogOpenSubscription() {
716
- document.addEventListener("zazz:dialog-open", function (e) {
717
- if (!(e.target instanceof HTMLDialogElement))
718
- return;
719
- const dialog = e.target;
720
- initEmblaCarousels(dialog);
721
- const roots = dialog.querySelectorAll(':is(ui-carousel, [data-ui~="carousel"])');
722
- roots.forEach(function (root) {
723
- const startIndex = root.getAttribute("data-carousel-start-index");
724
- if (startIndex != null && root._emblaApi) {
725
- root._emblaApi.goTo(Number(startIndex), true);
726
- root.removeAttribute("data-carousel-start-index");
727
- }
728
- const viewport = root.querySelector('[data-carousel-slot~="viewport"]');
729
- if (viewport instanceof HTMLElement) {
730
- viewport.focus({ preventScroll: true });
731
- }
732
- });
733
- });
734
- }
735
- // --- Keyboard navigation ---
736
- /**
737
- * @description Returns the active Embla root for keyboard navigation.
738
- *
739
- * Prefers a carousel inside an open dialog, then the carousel containing focus.
740
- * Respects `data-carousel-keyboard="false"`.
741
- *
742
- * @returns The active carousel root, or null when none applies.
743
- * @private
744
- */
745
- function getActiveEmblaRoot() {
746
- const openDialog = document.querySelector("dialog[open]");
747
- if (openDialog) {
748
- const dialogRoot = openDialog.querySelector(':is(ui-carousel, [data-ui~="carousel"])[data-carousel-init]');
749
- if (dialogRoot?._emblaApi && dialogRoot.getAttribute("data-carousel-keyboard") !== "false") {
750
- return dialogRoot;
751
- }
752
- }
753
- const focusedRoot = document.activeElement?.closest(':is(ui-carousel, [data-ui~="carousel"])[data-carousel-init]');
754
- if (focusedRoot?._emblaApi && focusedRoot.getAttribute("data-carousel-keyboard") !== "false") {
755
- return focusedRoot;
756
- }
757
- return null;
758
- }
759
- /**
760
- * @description Binds ArrowLeft/ArrowRight keyboard navigation for active carousels.
761
- *
762
- * Embla is headless: arrow keys are not built in. Opt out per carousel with
763
- * `data-carousel-keyboard="false"`.
764
- */
765
- const initEmblaKeyboardNav = function () {
766
- if (initEmblaKeyboardNav._bound)
767
- return;
768
- initEmblaKeyboardNav._bound = true;
769
- document.addEventListener("keydown", function (e) {
770
- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight")
771
- return;
772
- if (e.defaultPrevented)
773
- return;
774
- const target = e.target;
775
- if (!(target instanceof HTMLElement))
776
- return;
777
- if (target instanceof HTMLInputElement ||
778
- target instanceof HTMLTextAreaElement ||
779
- target instanceof HTMLSelectElement ||
780
- target.isContentEditable) {
781
- return;
782
- }
783
- const root = getActiveEmblaRoot();
784
- if (!root)
785
- return;
786
- e.preventDefault();
787
- onManualNavigation(root._emblaApi);
788
- if (e.key === "ArrowLeft")
789
- root._emblaApi.goToPrev();
790
- else
791
- root._emblaApi.goToNext();
792
- });
793
- };
794
- /**
795
- * @namespace EmblaInit
796
- * @description Public API for Embla carousel initialization and helpers.
797
- *
798
- * @property init - Initializes all carousels within a scope.
799
- * @property initRoot - Initializes a single carousel root (used by `<ui-carousel>`).
800
- * @property addDotBtnsAndClickHandlers - Wires dot pagination.
801
- * @property addThumbClickHandlers - Wires thumb click handlers.
802
- * @property addTogglethumbsActive - Syncs thumb active state.
803
- */
804
- const EmblaInit = {
805
- init: initEmblaCarousels,
806
- initRoot: initEmblaRoot,
807
- addDotBtnsAndClickHandlers,
808
- addThumbClickHandlers,
809
- addTogglethumbsActive,
810
- };
811
- // --- Start index control ---
812
- /**
813
- * @description Stores or applies a start slide index from `[data-carousel-start]` triggers.
814
- *
815
- * Clicking an element with `data-carousel-start="N"` stores that index on the target
816
- * carousel (found via `commandfor` → dialog → `:is(ui-carousel, [data-ui~="carousel"])`). The dialog
817
- * open observer scrolls to it on open.
818
- */
819
- function initEmblaStartLinks() {
820
- document.addEventListener("click", function (e) {
821
- if (!(e.target instanceof HTMLElement))
822
- return;
823
- const trigger = e.target.closest("[data-carousel-start], [data-carousel-slot~='slide'][commandfor]");
824
- if (!trigger)
825
- return;
826
- let index = trigger.getAttribute("data-carousel-start");
827
- if (index == null && trigger.hasAttribute("commandfor")) {
828
- const emblaRoot = trigger.closest(':is(ui-carousel, [data-ui~="carousel"])');
829
- if (emblaRoot?._emblaApi) {
830
- index = String(emblaRoot._emblaApi.selectedSnap());
831
- }
832
- }
833
- const dialogId = trigger.getAttribute("commandfor");
834
- if (!dialogId)
835
- return;
836
- const dialog = document.getElementById(dialogId);
837
- if (!dialog)
838
- return;
839
- const root = dialog.querySelector(':is(ui-carousel, [data-ui~="carousel"])');
840
- if (!root)
841
- return;
842
- if (root._emblaApi) {
843
- root._emblaApi.goTo(Number(index), true);
844
- }
845
- else if (index != null) {
846
- root.setAttribute("data-carousel-start-index", index);
847
- }
848
- });
849
- }
850
- // Auto-initialize when DOM is ready (only in browser environment)
851
- if (typeof window !== "undefined" && typeof document !== "undefined") {
852
- // After an in-page navigation swap, initialize class-form carousels in the new content
853
- // (<ui-carousel> elements ride the swap via their own lifecycle; init() skips
854
- // already-initialized roots and closed dialogs).
855
- registerRefresh((scope) => initEmblaCarousels(scope));
856
- if (document.readyState === "loading") {
857
- document.addEventListener("DOMContentLoaded", function () {
858
- initEmblaCarousels();
859
- initDialogOpenSubscription();
860
- initEmblaStartLinks();
861
- initEmblaKeyboardNav();
862
- initCommandDragGuard();
863
- });
864
- }
865
- else {
866
- initEmblaCarousels();
867
- initDialogOpenSubscription();
868
- initEmblaStartLinks();
869
- initEmblaKeyboardNav();
870
- initCommandDragGuard();
871
- }
872
- }
873
- // Attach to window for the documented public API (`window.EmblaInit`), and export
874
- // for module consumers (carousel.js / navigation.js import it via the index.js entry).
875
- if (typeof window !== "undefined") {
876
- window.EmblaInit = EmblaInit;
877
- }
878
- export { EmblaInit, setActiveIndex, parseCarouselPlugins };