runtimeCarouselJs top-level constant

String const runtimeCarouselJs

Implementation

const String runtimeCarouselJs = r'''
function carouselRoot(groupId) {
  return document.querySelector('[data-arcane-carousel="' + cssEscape(groupId) +
    '"][data-arcane-carousel-active]');
}

function setCarouselSlide(groupId, idx) {
  const root = carouselRoot(groupId);
  if (!root) return;
  const count = parseInt(root.getAttribute('data-arcane-carousel-count') || '1', 10);
  const loop = root.getAttribute('data-arcane-carousel-loop') === 'true';
  let next = idx;
  if (loop) {
    if (next < 0) next = count - 1;
    if (next >= count) next = 0;
  } else {
    if (next < 0) next = 0;
    if (next >= count) next = count - 1;
  }
  root.setAttribute('data-arcane-carousel-active', next.toString());
  const slides = document.querySelectorAll(
    '[data-arcane-carousel="' + cssEscape(groupId) +
    '"][data-arcane-carousel-slide]'
  );
  for (let i = 0; i < slides.length; i++) {
    const s = slides[i];
    const sIdx = parseInt(s.getAttribute('data-arcane-carousel-slide') || '0', 10);
    s.setAttribute('data-arcane-state', sIdx === next ? 'active' : 'inactive');
  }
  fireEvent(root, 'arcane:carousel-change', { groupId: groupId, index: next });
}

function goToSlide(groupId, target) {
  const root = carouselRoot(groupId);
  if (!root) return;
  const cur = parseInt(root.getAttribute('data-arcane-carousel-active') || '0', 10);
  let next = cur;
  if (target === 'next') next = cur + 1;
  else if (target === 'prev') next = cur - 1;
  else {
    const n = parseInt(target, 10);
    if (!isNaN(n)) next = n;
  }
  setCarouselSlide(groupId, next);
}

function startCarouselAutoplay(root) {
  const ms = parseInt(root.getAttribute('data-arcane-carousel-autoplay') || '0', 10);
  if (!ms || ms <= 0) return;
  const groupId = root.getAttribute('data-arcane-carousel');
  if (root._arcaneCarouselTimer) clearInterval(root._arcaneCarouselTimer);
  root._arcaneCarouselTimer = setInterval(function() {
    goToSlide(groupId, 'next');
  }, ms);
  root.addEventListener('mouseenter', function() {
    if (root._arcaneCarouselTimer) clearInterval(root._arcaneCarouselTimer);
  });
  root.addEventListener('mouseleave', function() {
    startCarouselAutoplay(root);
  });
}

ARCANE.carousel = {
  go: goToSlide,
  set: setCarouselSlide,
  startAutoplay: startCarouselAutoplay
};
''';