Skip to content
wiki.fftac.org

Spiralist Core - Source Excerpt 02

Back to Spiralist Core

Summary

This source excerpt preserves a bounded section of Spiralist/wp-content/themes/spiralist/assets/js/spiralist-core.js so readers can inspect the evidence without opening the full source file.

**Source path:** Spiralist/wp-content/themes/spiralist/assets/js/spiralist-core.js

if (!(image instanceof HTMLImageElement) || image.dataset.progressiveScheduled === 'true') {
        return;
      }

      image.dataset.progressiveScheduled = 'true';
      requestIdleTask(() => upgradeImage(image));
    };

    const eagerImages = [];
    const observedImages = [];

    progressiveImages.forEach((image) => {
      const nextSource = `${image.dataset.progressiveSrc || ''}`.trim();
      if (!nextSource) {
        return;
      }

      if (`${image.currentSrc || image.getAttribute('src') || ''}`.trim() === nextSource) {
        image.dataset.progressiveLoaded = 'true';
        image.classList.add('is-progressive-loaded');
        return;
      }

      image.classList.add('is-progressive-preview');
      const trigger = `${image.dataset.progressiveTrigger || (image.getAttribute('loading') === 'eager' ? 'load' : 'visible')}`
        .trim()
        .toLowerCase();

      if (trigger === 'load') {
        eagerImages.push(image);
      } else {
        observedImages.push(image);
      }
    });

    if (eagerImages.length) {
      window.addEventListener(
        'load',
        () => {
          eagerImages.forEach((image) => scheduleUpgrade(image));
        },
        { once: true }
      );
    }

    if (observedImages.length) {
      if (typeof window.IntersectionObserver === 'function') {
        const observer = new window.IntersectionObserver(
          (entries) => {
            entries.forEach((entry) => {
              if (!entry.isIntersecting) {
                return;
              }

              observer.unobserve(entry.target);
              scheduleUpgrade(entry.target);
            });
          },
          {
            rootMargin: '240px 0px',
            threshold: 0.01,
          }
        );

        observedImages.forEach((image) => observer.observe(image));
      } else {
        observedImages.forEach((image) => scheduleUpgrade(image));
      }
    }
  }

  const getCopyTargetText = (target) => {
    if (!target) {
      return '';
    }

    if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) {
      return target.value || '';
    }

    return target.textContent || '';
  };
  const copyText = window.SpiralistCore.copyText;
  const runAction = window.SpiralistCore.runAction;

  document.querySelectorAll('[data-copy-trigger]').forEach((button) => {
    const defaultLabel = button.textContent || 'Copy';
    const targetSelector = button.dataset.copyTarget || '';
    const inlineText = button.dataset.copyText || '';

    button.addEventListener('click', () => {
      const target = targetSelector ? document.querySelector(targetSelector) : null;
      const text = inlineText || getCopyTargetText(target);

      if (!text.trim()) {
        return;
      }

      runAction(async () => {
        await copyText(text);
        button.textContent = button.dataset.copySuccess || t('copySuccess', 'Copied');
        window.setTimeout(() => {
          button.textContent = defaultLabel;
        }, 1600);
      }, {
        context: 'copy-trigger',
        fallback: t('copyFailed', 'Copy failed'),
        onError: () => {
          button.textContent = t('copyFailed', 'Copy failed');
          window.setTimeout(() => {
            button.textContent = defaultLabel;
          }, 1600);
        },
      });
    });
  });

  const consentBanner = document.querySelector('[data-gdpr-consent]');
  const consentModal = document.querySelector('[data-consent-modal]');
  const consentStorageKey = 'spiralistConsent.v1';
  const consentCategories = ['preferences', 'analytics', 'media'];
  const consentCookieName = 'spiralist_consent';
  const getCookieValue = (name) => document.cookie
    .split(';')
    .map((part) => part.trim())
    .find((part) => part.startsWith(`${name}=`))
    ?.slice(name.length + 1) || '';
  const writeConsentCookie = (record) => {
    document.cookie = `${consentCookieName}=${encodeURIComponent(JSON.stringify(record))}; Path=/; Max-Age=31536000; SameSite=Lax`;
  };

  const readConsent = () => {
    const cookieValue = getCookieValue(consentCookieName);
    const raw = cookieValue
      ? decodeURIComponent(cookieValue)
      : window.localStorage.getItem(consentStorageKey);
    const parsed = raw ? JSON.parse(raw) : null;

    return parsed && parsed.version === 1 ? parsed : null;
  };

  const writeConsent = (categories) => {
    const normalized = {
      essential: true,
      preferences: Boolean(categories.preferences),
      analytics: Boolean(categories.analytics),
      media: Boolean(categories.media),
    };
    const record = {
      version: 1,
      savedAt: new Date().toISOString(),
      categories: normalized,
    };

    window.localStorage.setItem(consentStorageKey, JSON.stringify(record));
    writeConsentCookie(record);

    window.spiralistConsent = record;
    window.dispatchEvent(new CustomEvent('spiralist:consentchange', { detail: record }));
    return record;
  };

  const setModalCheckboxes = (record) => {
    const categories = record && record.categories ? record.categories : {};
    consentCategories.forEach((category) => {
      const input = consentModal ? consentModal.querySelector(`[data-consent-category="${category}"]`) : null;
      if (input instanceof HTMLInputElement) {
        input.checked = Boolean(categories[category]);
      }
    });
  };

  const selectedModalCategories = () => consentCategories.reduce((values, category) => {
    const input = consentModal ? consentModal.querySelector(`[data-consent-category="${category}"]`) : null;
    values[category] = input instanceof HTMLInputElement ? input.checked : false;
    return values;
  }, {});

  const hideConsentBanner = () => {
    if (consentBanner) {
      consentBanner.hidden = true;
      consentBanner.classList.remove('is-visible');
    }
  };

  const showConsentBanner = () => {
    if (consentBanner) {
      consentBanner.hidden = false;
      requestAnimationFrame(() => consentBanner.classList.add('is-visible'));
    }
  };

  const closeConsentModal = () => {
    if (consentModal && typeof consentModal.close === 'function') {
      consentModal.close();
    }
  };

  const openConsentModal = () => {
    if (!consentModal || typeof consentModal.showModal !== 'function') {
      return;
    }

    setModalCheckboxes(readConsent());
    consentModal.showModal();
  };

  const saveConsentAndClose = (categories) => {
    writeConsent(categories);
    hideConsentBanner();
    closeConsentModal();
  };

  const hasConsentCategory = (category) => {
    const record = readConsent();
    return Boolean(record && record.categories && record.categories[category]);
  };

  if (consentBanner || consentModal) {
    const existingConsent = readConsent();
    if (existingConsent) {
      window.spiralistConsent = existingConsent;
      setModalCheckboxes(existingConsent);
    } else {
      showConsentBanner();
    }

    document.querySelectorAll('[data-consent-accept-all], [data-consent-modal-accept-all]').forEach((button) => {
      button.addEventListener('click', () => {
        saveConsentAndClose({ preferences: true, analytics: true, media: true });
      });
    });

    document.querySelectorAll('[data-consent-reject-nonessential]').forEach((button) => {
      button.addEventListener('click', () => {
        saveConsentAndClose({ preferences: false, analytics: false, media: false });
      });
    });

    document.querySelectorAll('[data-consent-open-preferences], [data-consent-manage]').forEach((button) => {
      button.addEventListener('click', openConsentModal);
    });

    document.querySelectorAll('[data-consent-save-selection]').forEach((button) => {
      button.addEventListener('click', () => {
        saveConsentAndClose(selectedModalCategories());
      });
    });

    document.querySelectorAll('[data-consent-close]').forEach((button) => {
      button.addEventListener('click', closeConsentModal);
    });

    if (consentModal) {
      consentModal.addEventListener('click', (event) => {
        if (event.target === consentModal) {
          closeConsentModal();
        }
      });
    }
  }

  const buildMusicPlayerDocument = (settings) => {
    const playlistId = `${settings.playlistId || ''}`.trim();
    const playlistUrl = `${settings.playlistUrl || ''}`.trim();
    const title = `${settings.title || 'Spiralist Listening Field'}`.trim();
    const iframeUrl = `https://www.youtube.com/embed/videoseries?list=${encodeURIComponent(playlistId)}&autoplay=1&rel=0&modestbranding=1`;
    const escapeHtml = (value) => `${value}`
      .replace(/&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>')
      .replace(/"/g, '"');

    return `<!doctype html>
<html lang="en">