Fanatical bundles carousel enhancer

In all Fanatical Build Your Own bundles, adds "Add to bundle" button to the carousel - like in game bundles. It is handy to have arrows, to browse products, and button to add to cart close by. In bundles with tiers, adds tier info to the carousel. All bundles: moves carousel on top.

目前為 2024-07-11 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Fanatical bundles carousel enhancer
// @version      2024.7.11
// @namespace    Jakub Marcinkowski
// @description  In all Fanatical Build Your Own bundles, adds "Add to bundle" button to the carousel - like in game bundles. It is handy to have arrows, to browse products, and button to add to cart close by. In bundles with tiers, adds tier info to the carousel. All bundles: moves carousel on top.
// @author       Jakub Marcinkowski <kuba.marcinkowski on g mail>
// @copyright    2023, Jakub Marcinkowski <kuba.marcinkowski on g mail>
// @license      Zlib
// @homepageURL  https://gist.github.com/JakubMarcinkowski
// @homepageURL  https://github.com/JakubMarcinkowski
// @match        https://*.fanatical.com/*
// @icon         https://cdn.fanatical.com/production/icons/favicon.ico
// @run-at       document-body
// ==/UserScript==

(function()
{
  'use strict';

  let listening = new Set();
  let carousel, tileCard, tileTarget, carouselTarget, button, buttonDummy, tilesTitles, carouselTitle, observerAddRem;
  const observerInitial = new MutationObserver
  (
    function()
    {
      const contentElem = document.getElementsByClassName('content')[0];
      if (!contentElem) return;
      if (contentElem.parentElement.parentElement.id !== 'root') return;
      observerInitial.disconnect();
      observePageChange(contentElem);
    }
  );
  observerInitial.observe(document.body, {childList: true, subtree: true});

  function observePageChange(elem)
  {
    const observerPage = new MutationObserver
    (
      function(mutationsList)
      {
        const addedBundle = mutationsList.find
        (
          mutation => [...mutation.addedNodes].find(checkIfBundle)
        );
        if (addedBundle)
        {
          carousel = document.querySelector('section.bundle-carousel');
          if (carousel)
          {
            carouselOnTop();
            carouselTitle = carousel.querySelector('.product-name').firstChild; // text node
            carouselTarget = document.querySelector('h4.mb-3'); // On top of right pane in carousel
            if (document.querySelector('main.bundle-page')
                && document.getElementsByClassName('tier-title')[0]
               ) // Not a BYOB
            {
              tilesTitles = [...document.querySelectorAll('h3.card-product-name')];
              addTier();
            }
            if (document.querySelector('main.PickAndMixProductPage')
                && !document.querySelector('.bundle-carousel .pnm-add-btn') // Add buttons exists in game bundles by default
               )
            {
              tilesTitles = [...document.querySelectorAll('h2.card-product-name')];
              addButton();
            }
          }
          return;
        }
        const removedBundle = mutationsList.find
        (
          mutation => [...mutation.removedNodes].find(checkIfBundle)
        );
        if (removedBundle)
        {
          if (observerAddRem) observerAddRem.disconnect();
          if (tileCard) removeListeners(tileCard);
        }
      }
    );
    observerPage.observe(elem, {childList: true});
  }

  function checkIfBundle(node)
  {
    return node.tagName && node.tagName === 'MAIN'
    && (node.classList.contains('PickAndMixProductPage') || node.classList.contains('bundle-page'))
  }

  function carouselOnTop()
  {
    unwrap(carousel);
    unwrap(carousel.parentElement);
    const bgContrast = document.querySelector('[class$="backgroundContrast"]');
    if (bgContrast) carousel.parentElement.before(bgContrast);
  }

  function unwrap(relElem)
  {
    while (relElem.previousElementSibling)
    {
      carousel.after(relElem.previousElementSibling);
    }
  }

  function addButton()
  {
    moveTheButton();
    const observerTitle = new MutationObserver(moveTheButton);
    observerTitle.observe(carouselTitle, {characterData: true});
    observerAddRem = new MutationObserver
    (
      function(mutationsList)
      {
        if (mutationsList[0].target
            && mutationsList[0].target.tagName === 'A'
            || !buttonDummy) return;
        mutationsList.forEach
        (
          mutation =>
          {
            if (mutation.target.tagName !== 'BUTTON') return;
            const buttonDummy2 = button.cloneNode(true);
            buttonDummy.replaceWith(buttonDummy2);
            buttonDummy = buttonDummy2;
          }
        );
      }
    );
    observerAddRem.observe(
      document.querySelector('div.PickAndMixProductPage__content.container > section')
      , {subtree: true, attributeFilter: ["class"]}
    );
  }

  function moveTheButton()
  {
    if (tileCard) // Not on first run
    {
      moveToTile();
      removeListeners(tileCard);
    }
    tileCard = tilesTitles
      .find(x => x.textContent === carouselTitle.nodeValue)
      .closest('article');
    tileTarget = tileCard.querySelector('.PickAndMixCard__addToBundle > div');
    button = tileTarget.querySelector('button');
    moveToCarousel();
    addListeners(tileCard);
  }

  function moveToTile(event)
  {
    tileTarget.append(button);
    if (buttonDummy) buttonDummy.remove();
    buttonDummy = button.cloneNode(true);
    carouselTarget.prepend(buttonDummy);
  }

  function moveToCarousel(event)
  {
    carouselTarget.prepend(button);
    if (buttonDummy) buttonDummy.remove();
    if (!event) buttonDummy = button.cloneNode(true);
    tileTarget.append(buttonDummy);
  }

  function removeListeners(node)
  {
    listening.delete(node);
    node.removeEventListener('mouseenter', moveToTile);
    node.removeEventListener('mouseleave', moveToCarousel);
  }

  function addListeners(node)
  {
    listening.add(node);
    node.addEventListener('mouseenter', moveToTile);
    node.addEventListener('mouseleave', moveToCarousel);
  }

  function addTier()
  {
    const container = document.createElement('div');
    container.className = 'tierInfo';
    carouselTarget.prepend(container);
    carouselTarget = container;
    copyTierInfo();
    const observerTitle = new MutationObserver(copyTierInfo);
    observerTitle.observe(carouselTitle, {characterData: true});
  }

  function copyTierInfo()
  {
    const tierElem = tilesTitles
      .find(x => x.textContent === carouselTitle.nodeValue)
      .closest('.tier');
    let string = [...tierElem.children[0].childNodes]
      .reduce((str, node) => {return str += node.nodeType === Node.TEXT_NODE ? node.textContent : ''}, '') // Get all text nodes
    carouselTarget.textContent = string + tierElem.children[0].firstElementChild.textContent;
  }

  const styleSheet = document.head.appendChild(document.createElement('style')).sheet;
  function addStyleRules(rules)
  {
    rules.forEach(rule => styleSheet.insertRule(rule));
  }
  addStyleRules
  ([
    `h4.mb-3 > button {
      float: right;
      padding: 6px;
      margin-left: 0.3rem;
      margin-bottom: 1rem;
    }`
    ,`h4.mb-3 > div.tierInfo {
      margin-bottom: 1rem;
    }`
    ,`h4.mb-3 + .overview-container {
      clear: both;
    }`
    ,`section.bundle-carousel {
      padding-top: 1px;
    }`
    ,`#carousel-content {
      padding: 1rem;
    }`
    ,`.PickAndMixProductPage__content {
      padding-top: 0 !important;
    }`
    ,`article.left-column > div.product-details {
      word-break: break-word;
    }` // Fix. BYO Fantasy Game Assets Bundle had Pixelart Fonts Asset packs. Description contained "supported characters", which swelled container.
    ,`:root {
      margin-left: -1.1rem;
    }` // Fix. Sometimes fanatical have unnecesary horizontal scrollbar
  ]);

  /* Tested:
    https://www.fanatical.com/en/pick-and-mix/essential-game-music-build-your-own-bundle - audio
    https://www.fanatical.com/en/pick-and-mix/ultimate-machine-learning-and-ai-build-your-own-bundle - ebook
    https://www.fanatical.com/en/pick-and-mix/build-your-own-tabletop-wargame-bundle - games, already has Add
    https://www.fanatical.com/en/pick-and-mix/new-skills-new-you-build-your-own-bundle - elearning
    https://www.fanatical.com/en/pick-and-mix/build-your-own-fantasy-game-assets-bundle - mixed audio + graphics
  */
})();