From bf8e0a28f2ac8bc42a9822df2b1d35b69ff101f9 Mon Sep 17 00:00:00 2001 From: castellon Date: Wed, 25 Nov 2026 12:43:21 +0100 Subject: [PATCH] Carousel: expose window.frontblocksCarousel.init() to start lists added after load The script only started carousels in the window "load" event and had no way to start lists added later (AJAX, REST), so add-ons had to re-run the whole file. - init( container ) starts the lists inside the container (default: document) and skips the ones already running, so calling it twice is safe. - If the script runs after the window has loaded, it starts at once instead of waiting for a "load" that never comes. - Declare two variables that were implicit globals (arrowsHTML, actualView). - Add JS tests, registered in package.json and the CI workflow. --- .github/workflows/phpunit.yml | 1 + assets/carousel/frontblocks-carousel.js | 31 ++++++- package.json | 1 + tests/js/carousel-init-api.test.js | 118 ++++++++++++++++++++++++ 4 files changed, 146 insertions(+), 5 deletions(-) create mode 100644 tests/js/carousel-init-api.test.js diff --git a/.github/workflows/phpunit.yml b/.github/workflows/phpunit.yml index 936ab2ad..66408d1f 100644 --- a/.github/workflows/phpunit.yml +++ b/.github/workflows/phpunit.yml @@ -62,6 +62,7 @@ jobs: npm run test:table-of-contents npm run test:accessibility-utils npm run test:carousel-accessibility + npm run test:carousel-init-api npm run test:text-animation phpunit: diff --git a/assets/carousel/frontblocks-carousel.js b/assets/carousel/frontblocks-carousel.js index e793a18a..5d621e24 100644 --- a/assets/carousel/frontblocks-carousel.js +++ b/assets/carousel/frontblocks-carousel.js @@ -1,5 +1,18 @@ -window.addEventListener('load', function (event) { - const carouselItem = document.querySelectorAll('.frontblocks-carousel'); +/** + * FrontBlocks carousel. + * + * Starts every ".frontblocks-carousel" list on window "load". Code that adds lists later (AJAX, REST) can call + * window.frontblocksCarousel.init( container ) to start only the new lists inside "container" (default: the whole + * document). Lists that are already running are skipped, so calling it again is safe. + */ +window.frontblocksCarousel = window.frontblocksCarousel || {}; +window.frontblocksCarousel.init = function (root) { + const scope = root && root.querySelectorAll ? root : document; + // A running carousel has "glide__slides"; it is skipped so the list is never wrapped twice. + const carouselItem = Array.prototype.filter.call( + scope.querySelectorAll('.frontblocks-carousel'), + (el) => ! el.classList.contains('glide__slides') + ); if (carouselItem.length > 0) { carouselItem.forEach((item) => { @@ -127,7 +140,7 @@ window.addEventListener('load', function (event) { const leftSvg = carouselArrowLeftUrl ? '' : defaultLeftSvg; const rightSvg = carouselArrowRightUrl ? '' : defaultRightSvg; - arrowsHTML = '