@ideasonpurpose/wp-theme-addons 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,360 @@
1
+ // @ts-check
2
+
3
+ import EmblaCarousel from "embla-carousel";
4
+ import Accessibility from "embla-carousel-accessibility";
5
+ import Autoplay from "embla-carousel-autoplay";
6
+ import ClassNames from "embla-carousel-class-names";
7
+ import { CAROUSEL_DEFAULTS } from "../lib/carousel-defaults.js";
8
+
9
+ const SCROLL_DURATION = 25;
10
+
11
+ /**
12
+ * @param {string | undefined} value
13
+ * @param {boolean} fallback
14
+ */
15
+ function booleanAttr(value, fallback) {
16
+ if (value === "false") return false;
17
+ if (value === "true") return true;
18
+ return fallback;
19
+ }
20
+
21
+ /**
22
+ * @param {HTMLElement} wrapper
23
+ */
24
+ export function readCarouselOptions(wrapper) {
25
+ const data = wrapper.dataset;
26
+ const duration = Number(data.duration);
27
+ const random = Number(data.random);
28
+
29
+ return {
30
+ autoplay: booleanAttr(data.autoplay, CAROUSEL_DEFAULTS.autoplay),
31
+ duration:
32
+ Number.isFinite(duration) && duration > 0
33
+ ? duration
34
+ : CAROUSEL_DEFAULTS.duration,
35
+ arrows: booleanAttr(data.arrows, CAROUSEL_DEFAULTS.arrows),
36
+ dots: booleanAttr(data.dots, CAROUSEL_DEFAULTS.dots),
37
+ loop: booleanAttr(data.loop, CAROUSEL_DEFAULTS.loop),
38
+ random:
39
+ Number.isFinite(random) && random > 0
40
+ ? Math.floor(random)
41
+ : CAROUSEL_DEFAULTS.random,
42
+ };
43
+ }
44
+
45
+ /**
46
+ * Pick `count` items in random order. A count of 0, or a count that covers
47
+ * every item, returns the original list in its original order.
48
+ *
49
+ * @template T
50
+ * @param {ArrayLike<T>} slides
51
+ * @param {number} count
52
+ * @param {() => number} [random]
53
+ * @returns {T[]}
54
+ */
55
+ export function selectRandomSlides(slides, count, random = Math.random) {
56
+ const list = Array.from(slides);
57
+ const n = Math.floor(count);
58
+ if (!n || n >= list.length) return list;
59
+
60
+ for (let i = list.length - 1; i > 0; i--) {
61
+ const j = Math.floor(random() * (i + 1));
62
+ [list[i], list[j]] = [list[j], list[i]];
63
+ }
64
+ return list.slice(0, n);
65
+ }
66
+
67
+ /**
68
+ * @param {HTMLElement} slide
69
+ * @param {number} fallbackSeconds
70
+ */
71
+ export function slideDelayMs(slide, fallbackSeconds) {
72
+ const seconds = Number(slide.dataset.slideDuration);
73
+ const value =
74
+ Number.isFinite(seconds) && seconds > 0 ? seconds : fallbackSeconds;
75
+ return value * 1000;
76
+ }
77
+
78
+ /**
79
+ * @param {EventTarget | null} target
80
+ */
81
+ function isTypingTarget(target) {
82
+ if (
83
+ !target ||
84
+ !("closest" in target) ||
85
+ typeof target.closest !== "function"
86
+ ) {
87
+ return false;
88
+ }
89
+ const element = /** @type {HTMLElement} */ (target);
90
+ if (element.isContentEditable) return true;
91
+ return Boolean(element.closest("input, textarea, select"));
92
+ }
93
+
94
+ /**
95
+ * @param {string} className
96
+ * @param {string} label
97
+ */
98
+ function createButton(className, label) {
99
+ const button = document.createElement("button");
100
+ button.type = "button";
101
+ button.className = className;
102
+ button.setAttribute("aria-label", label);
103
+ return button;
104
+ }
105
+
106
+ /**
107
+ * @param {ParentNode} [root]
108
+ */
109
+ export function initCarousels(root = document) {
110
+ const doc = root?.nodeType === 9 ? root : root?.ownerDocument;
111
+ if (doc && root === doc && doc.readyState === "loading") {
112
+ doc.addEventListener("DOMContentLoaded", () => initCarousels(doc), {
113
+ once: true,
114
+ });
115
+ return;
116
+ }
117
+
118
+ /** @type {HTMLElement[]} */
119
+ const nodes = [];
120
+ if (
121
+ root?.nodeType === 1 &&
122
+ "matches" in root &&
123
+ root.matches(".iop-carousel")
124
+ ) {
125
+ nodes.push(/** @type {HTMLElement} */ (root));
126
+ }
127
+ if (root?.querySelectorAll) {
128
+ nodes.push(
129
+ .../** @type {HTMLElement[]} */ ([
130
+ ...root.querySelectorAll(".iop-carousel"),
131
+ ]),
132
+ );
133
+ }
134
+
135
+ for (const wrapper of nodes) mountCarousel(wrapper);
136
+ }
137
+
138
+ /**
139
+ * @param {HTMLElement} wrapper
140
+ */
141
+ function mountCarousel(wrapper) {
142
+ if (wrapper.dataset.carouselInit === "true") return;
143
+
144
+ const viewport = wrapper.querySelector(".iop-carousel__viewport");
145
+ const container = viewport?.querySelector(".iop-carousel__container");
146
+ if (viewport?.nodeType !== 1 || container?.nodeType !== 1) return;
147
+
148
+ wrapper.dataset.carouselInit = "true";
149
+
150
+ const options = readCarouselOptions(wrapper);
151
+ const view = wrapper.ownerDocument.defaultView || window;
152
+
153
+ if (options.random) {
154
+ const kept = selectRandomSlides(container.children, options.random);
155
+ const keep = new Set(kept);
156
+ for (const slide of [...container.children]) {
157
+ if (!keep.has(slide)) slide.remove();
158
+ }
159
+ for (const slide of kept) container.appendChild(slide);
160
+ }
161
+
162
+ for (const slide of container.children) {
163
+ slide.classList.add("iop-carousel__slide");
164
+ }
165
+
166
+ const slides = [...container.children];
167
+ if (slides.length < 2) {
168
+ wrapper.classList.add("is-ready");
169
+ return;
170
+ }
171
+
172
+ const motion = view.matchMedia?.("(prefers-reduced-motion: reduce)");
173
+ let reduceMotion = Boolean(motion?.matches);
174
+ let userPaused = false;
175
+ let hovered = false;
176
+ let onScreen = true;
177
+
178
+ /** @type {HTMLButtonElement | null} */
179
+ let pauseButton = null;
180
+ /** @type {HTMLElement | null} */
181
+ let dotsNode = null;
182
+
183
+ const plugins = [
184
+ Accessibility({
185
+ announceChanges: true,
186
+ rootNode: (emblaRoot) => emblaRoot.parentElement,
187
+ }),
188
+ ClassNames(),
189
+ ];
190
+
191
+ if (options.autoplay) {
192
+ plugins.push(
193
+ Autoplay({
194
+ delay: (_snaps, api) =>
195
+ api
196
+ .slideNodes()
197
+ .map((slide) => slideDelayMs(slide, options.duration)),
198
+ // Play and pause are owned here so dots, arrows, and the pause
199
+ // button follow one rule. The plugin's default stops on pointerdown.
200
+ defaultInteraction: false,
201
+ }),
202
+ );
203
+ }
204
+
205
+ const api = EmblaCarousel(
206
+ viewport,
207
+ {
208
+ loop: options.loop,
209
+ // Full-width slides should sit flush. Center alignment can show a sliver of the next slide.
210
+ align: "start",
211
+ duration: reduceMotion ? 0 : SCROLL_DURATION,
212
+ container,
213
+ },
214
+ plugins,
215
+ );
216
+
217
+ const autoplay = () => api.plugins()?.autoplay;
218
+
219
+ const shouldPlay = () =>
220
+ options.autoplay && !reduceMotion && !userPaused && !hovered && onScreen;
221
+
222
+ const sync = () => {
223
+ const player = autoplay();
224
+ // The autoplay plugin leaves its timer unset when there is a single snap.
225
+ if (player && api.snapList().length > 1) {
226
+ if (shouldPlay()) player.play();
227
+ else if (player.isPlaying()) player.pause();
228
+ }
229
+ if (!pauseButton) return;
230
+ const show = options.autoplay && !reduceMotion;
231
+ pauseButton.hidden = !show;
232
+ pauseButton.classList.toggle("is-paused", userPaused);
233
+ pauseButton.setAttribute("aria-pressed", userPaused ? "true" : "false");
234
+ pauseButton.setAttribute(
235
+ "aria-label",
236
+ userPaused ? "Play automatic slides" : "Pause automatic slides",
237
+ );
238
+ };
239
+
240
+ /**
241
+ * @param {"prev" | "next" | number} target
242
+ */
243
+ const go = (target) => {
244
+ if (target === "prev") api.goToPrev();
245
+ else if (target === "next") api.goToNext();
246
+ else api.goTo(target);
247
+ autoplay()?.reset();
248
+ sync();
249
+ };
250
+
251
+ if (options.arrows) {
252
+ const arrows = document.createElement("div");
253
+ arrows.className = "iop-carousel-arrows";
254
+ const prev = createButton(
255
+ "iop-carousel-arrow iop-carousel-arrow--prev",
256
+ "Previous slide",
257
+ );
258
+ const next = createButton(
259
+ "iop-carousel-arrow iop-carousel-arrow--next",
260
+ "Next slide",
261
+ );
262
+ prev.addEventListener("click", () => go("prev"));
263
+ next.addEventListener("click", () => go("next"));
264
+ arrows.append(prev, next);
265
+ wrapper.append(arrows);
266
+ api.plugins()?.accessibility?.setupPrevAndNextButtons(prev, next);
267
+ }
268
+
269
+ /** @type {HTMLElement | null} */
270
+ let controls = null;
271
+ const ensureControls = () => {
272
+ if (controls) return controls;
273
+ controls = document.createElement("div");
274
+ controls.className = "iop-carousel-controls";
275
+ wrapper.append(controls);
276
+ return controls;
277
+ };
278
+
279
+ if (options.autoplay) {
280
+ pauseButton = createButton("iop-carousel-pause", "Pause automatic slides");
281
+ pauseButton.setAttribute("aria-pressed", "false");
282
+ pauseButton.addEventListener("click", () => {
283
+ userPaused = !userPaused;
284
+ if (!userPaused) hovered = false;
285
+ sync();
286
+ });
287
+ ensureControls().append(pauseButton);
288
+ }
289
+
290
+ const updateDots = () => {
291
+ if (!dotsNode) return;
292
+ const selected = api.selectedSnap();
293
+ for (const [index, button] of [...dotsNode.children].entries()) {
294
+ button.classList.toggle("is-active", index === selected);
295
+ }
296
+ };
297
+
298
+ if (options.dots) {
299
+ dotsNode = document.createElement("div");
300
+ dotsNode.className = "iop-carousel-dotnav";
301
+ dotsNode.setAttribute("role", "group");
302
+ dotsNode.setAttribute("aria-label", "Choose slide");
303
+ for (const [index] of api.snapList().entries()) {
304
+ const dot = createButton(
305
+ "iop-carousel-dotnav__dot",
306
+ `Go to slide ${index + 1}`,
307
+ );
308
+ dot.addEventListener("click", () => go(index));
309
+ dotsNode.append(dot);
310
+ }
311
+ ensureControls().append(dotsNode);
312
+ api.plugins()?.accessibility?.setupDotButtons(dotsNode);
313
+ updateDots();
314
+ }
315
+
316
+ const live = document.createElement("div");
317
+ live.className = "iop-carousel__live";
318
+ wrapper.append(live);
319
+ api.plugins()?.accessibility?.setupLiveRegion(live);
320
+
321
+ wrapper.addEventListener("keydown", (event) => {
322
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
323
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
324
+ return;
325
+ if (isTypingTarget(event.target)) return;
326
+ event.preventDefault();
327
+ go(event.key === "ArrowLeft" ? "prev" : "next");
328
+ });
329
+
330
+ wrapper.addEventListener("mouseenter", () => {
331
+ hovered = true;
332
+ sync();
333
+ });
334
+ wrapper.addEventListener("mouseleave", () => {
335
+ hovered = false;
336
+ sync();
337
+ });
338
+
339
+ const Observer = view.IntersectionObserver;
340
+ if (typeof Observer === "function") {
341
+ const observer = new Observer((entries) => {
342
+ onScreen = entries.some((entry) => entry.isIntersecting);
343
+ sync();
344
+ });
345
+ observer.observe(wrapper);
346
+ }
347
+
348
+ motion?.addEventListener?.("change", () => {
349
+ reduceMotion = Boolean(motion.matches);
350
+ sync();
351
+ });
352
+
353
+ api.on("select", updateDots);
354
+ api.on("reinit", () => {
355
+ sync();
356
+ });
357
+
358
+ sync();
359
+ wrapper.classList.add("is-ready");
360
+ }
package/index.d.ts CHANGED
@@ -30,6 +30,7 @@ declare module "@ideasonpurpose/wp-theme-addons" {
30
30
  icons?: { label?: string; value: string }[],
31
31
  defaultIcon?: string,
32
32
  ): void;
33
+ export function initCarouselBlock(): void;
33
34
  export function initCssLocalProps(blockNames?: string[]): void;
34
35
  export function initLinkedGroupBlock(): void;
35
36
  export function initRelatedPostsQueryBlock(): void;
package/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { initCssLocalProps } from "./CssLocalProps/css-local-props.js";
2
2
  export { initButtonIconPicker } from "./editor/Block/Extension/Button/button-icon-picker.js";
3
+ export { initCarouselBlock } from "./editor/Block/Variation/Group/Carousel/carousel.js";
3
4
  export { initLinkedGroupBlock } from "./editor/Block/Variation/Group/LinkedGroup/linked-group.js";
4
5
  export { initRelatedPostsQueryBlock } from "./editor/Block/Variation/Query/RelatedPostsQuery/related-posts-query.js";
5
6
  export { usePublicPostTypes } from "./lib/use-public-post-types.js";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Shared by the editor controls and the front-end module.
3
+ * PHP does not repeat these: it only prints attributes an author has set,
4
+ * and the front end applies these when the attribute is absent.
5
+ */
6
+ export const CAROUSEL_DEFAULTS = {
7
+ autoplay: true,
8
+ duration: 6,
9
+ arrows: true,
10
+ dots: true,
11
+ loop: true,
12
+ random: 0,
13
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ideasonpurpose/wp-theme-addons",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "WordPress Block Editor add-ons — JavaScript blocks, utilities, and PHP components",
5
5
  "keywords": [
6
6
  "wordpress",
@@ -26,7 +26,16 @@
26
26
  }
27
27
  ],
28
28
  "type": "module",
29
- "exports": "./index.js",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./index.d.ts",
32
+ "default": "./index.js"
33
+ },
34
+ "./carousel": {
35
+ "types": "./frontend/carousel.d.ts",
36
+ "default": "./frontend/carousel.js"
37
+ }
38
+ },
30
39
  "main": "index.js",
31
40
  "types": "index.d.ts",
32
41
  "directories": {
@@ -37,10 +46,12 @@
37
46
  "index.d.ts",
38
47
  "lib",
39
48
  "editor",
49
+ "frontend",
40
50
  "CssLocalProps",
41
51
  "README.md"
42
52
  ],
43
53
  "scripts": {
54
+ "test": "node --test test/carousel.test.js",
44
55
  "version": "version-everything && git add -u"
45
56
  },
46
57
  "prettier": "@ideasonpurpose/prettier-config",
@@ -49,12 +60,13 @@
49
60
  },
50
61
  "devDependencies": {
51
62
  "@ideasonpurpose/prettier-config": "^1.1.1",
52
- "@ideasonpurpose/stylelint-config": "^1.1.6",
53
- "@prettier/plugin-php": "^0.25.0",
54
- "@types/wordpress__block-editor": "^15.0.6",
55
- "@wordpress/compose": "^8.3.0",
56
- "@wordpress/hooks": "^4.50.0",
57
- "prettier": "^3.9.4",
63
+ "@ideasonpurpose/stylelint-config": "^1.1.7",
64
+ "@prettier/plugin-php": "^0.26.0",
65
+ "@types/wordpress__block-editor": "^15.0.9",
66
+ "@wordpress/compose": "^8.10.0",
67
+ "@wordpress/hooks": "^4.57.0",
68
+ "jsdom": "^31.0.1",
69
+ "prettier": "^3.10.1",
58
70
  "version-everything": "^0.12.2"
59
71
  },
60
72
  "version-everything": {
@@ -62,5 +74,11 @@
62
74
  "README.md"
63
75
  ],
64
76
  "prefix": "\"@ideasonpurpose/wp-theme-addons\": \"\\^"
77
+ },
78
+ "dependencies": {
79
+ "embla-carousel": "9.0.0-rc04",
80
+ "embla-carousel-accessibility": "9.0.0-rc04",
81
+ "embla-carousel-autoplay": "9.0.0-rc04",
82
+ "embla-carousel-class-names": "9.0.0-rc04"
65
83
  }
66
84
  }