Modal Image in rule

Add modal Image to rule34

Verzia zo dňa 23.12.2021. Pozri najnovšiu verziu.

Na nainštalovanie skriptu si budete musieť nainštalovať rozšírenie, ako napríklad Tampermonkey, Greasemonkey alebo Violentmonkey.

Na nainštalovanie skriptu si budete musieť nainštalovať rozšírenie, ako napríklad Tampermonkey, % alebo Violentmonkey.

Na nainštalovanie skriptu si budete musieť nainštalovať rozšírenie, ako napríklad Tampermonkey, % alebo Violentmonkey.

Na nainštalovanie skriptu si budete musieť nainštalovať rozšírenie, ako napríklad Tampermonkey alebo Userscripts.

Na inštaláciu tohto skriptu je potrebné nainštalovať rozšírenie, ako napríklad Tampermonkey.

Na inštaláciu tohto skriptu je potrebné nainštalovať rozšírenie správcu používateľských skriptov.

(Už mám správcu používateľských skriptov, nechajte ma ho nainštalovať!)

Na inštaláciu tohto štýlu je potrebné nainštalovať rozšírenie, ako napríklad Stylus.

Na inštaláciu tohto štýlu je potrebné nainštalovať rozšírenie, ako napríklad Stylus.

Na inštaláciu tohto štýlu je potrebné nainštalovať rozšírenie, ako napríklad Stylus.

Na inštaláciu tohto štýlu je potrebné nainštalovať rozšírenie správcu používateľských štýlov.

Na inštaláciu tohto štýlu je potrebné nainštalovať rozšírenie správcu používateľských štýlov.

Na inštaláciu tohto štýlu je potrebné nainštalovať rozšírenie správcu používateľských štýlov.

(Už mám správcu používateľských štýlov, nechajte ma ho nainštalovať!)

// ==UserScript==
// @name         Modal Image in rule
// @namespace    http://tampermonkey.net/
// @version      4.5
// @description  Add modal Image to rule34
// @author       falaz
// @match        https://rule34.xxx/index.php?page=po*
// @icon         https://www.google.com/s2/favicons?domain=rule34.xxx
// @grant        none
// ==/UserScript==

// @ts-check
class Falaz {
  /**
   * Like querySelector, but small
   * @param {String} selector
   * @param {Element|Document} element
   * @returns {HTMLElement}
   */
  q(selector, element = document) {
    return element.querySelector(selector);
  }
  /**
   * Like querySelectorAll, but small
   * @param {String} selector
   * @param {Element|Document} element
   * @returns
   */
  qa(selector, element = document) {
    return element.querySelectorAll(selector);
  }
}

class Modal {
  constructor(document, dp) {
    this.pointer = 0;
    this.dp = dp;
    this.infinityScroll = new InfinityScroll(document, dp);
    this.createModalNode(document);
    /**
     * @property {Media[]} medias
     */
    this.medias = this.infinityScroll.getMedias(document, 0);
  }

  createModalNode(document) {
    const div = document.createElement("div");
    const css = document.createElement("style");
    div.innerHTML =
      '<div id="modal-container" style="display:none"><div id="modal"></div></div>';
    css.innerHTML =
      "#modal-container{background: #000000a8;width: 100%;height: 100%;position: fixed;z-index: 10;}" +
      "#modal{height: 90%;width: 80%;background: transparent;padding: 0% 5%;margin: 2% 5% 2% 0;position: fixed}" +
      "#modal img{width: auto;border: none;vertical-align: middle;height: 100%;margin 0 auto;display:block;}" +
      "#modal video{width: 100%;height:100%}";
    document.body.prepend(div);
    document.head.prepend(css);
    this.modalContainer = F.q("#modal-container");
    this.modal = F.q("#modal");
    this.infinityScroll.nextPage =this.infinityScroll.getNextPageHref(document);
  }
  /**
   * @param {Media} media
   */
  async render(media) {
    if (!this.modalContainer) {
      this.createModalNode(document);
    }
    if (media.src == "Retry") {
      await this.reloadMediaSrc(media);
    }
    if (media.type == "video") {
      this.modal.innerHTML = `<video src="${media.src}" autoplay controls loop></video>`;
    } else {
      this.modal.innerHTML = `<img src="${media.src}"/>`;
    }
    this.modalContainer.style.display = "block";
  }
  async getNextPage() {
    if (!this.infinityScroll.nextSended) {
      this.infinityScroll.nextSended = true;
      const docResponse = await this.infinityScroll.getNextPage();
      if (docResponse) {
        const medias = this.infinityScroll.getMedias(
          docResponse,
          this.medias.length
        );
        console.log('medias to add');
        console.log(medias);
        this.addMedias(medias);
        this.infinityScroll.nextSended = false;
      }else{
          console.log('The page requested is on the medias');
      }
    }
  }

  close() {
    if (!this.modalContainer) {
      this.createModalNode(document);
    }
    try {
      this.modal.querySelector("video").pause();
    } catch (e) {}
    this.modalContainer.style.display = "none";
  }
  nextMedia() {
    if (this.pointer < this.medias.length - 1) {
      this.pointer++;
      this.render(this.medias[this.pointer]);
    } else {
      console.error("Reach the end of the medias");
    }
    // // Get New medias from the next page
    // // @todo add to the current page.
    // comment because the idea is scrolling with tapping the next button
    // if(this.pointer > this.medias.length -5 && !this.nextSended){
    //     this.nextSended= true;
    //     this.getNextPage();
    // }
  }
  prevMedia() {
    if (this.pointer > 0) {
      this.pointer--;
      this.render(this.medias[this.pointer]);
    } else {
      console.error("Reach the end of the medias");
    }
  }

  /**
   *
   * @param {Media[]} medias
   */
  addMedias(medias) {
    const mediasTemp = [...this.medias, ...medias];
    // @ts-ignore
    this.medias = mediasTemp;
  }
  async reloadMediaSrcFromMedias(index) {
    await this.medias[index].reloadSrc();
  }
  async reloadMediaSrc(media) {
    await media.reloadSrc();
  }
}
class Media {
  /**
   * @param {string} _page This is the page of the media. Not the real src.
   * @param {string} _type
   * @param {string} _thumb
   */
  constructor(_page, _type, _thumb, dp) {
    this.page = _page;
    this.type = _type;
    this.thumb = _thumb;
    this.dp = dp;
    this.getSrc().then((src) => {
      this.src = src;
    });
  }
  async getSrc() {
    const response = await fetch(this.page);
    if ([202, 200].includes(response.status)) {
      const body = await response.text();
      const dp = new DOMParser();
      const pageDocument = dp.parseFromString(body, "text/html");
      const video = F.q("video source", pageDocument);
      const image = F.q(".flexi img", pageDocument);
      if (video) {
        this.type = "video";
        return video.src;
      } else {
        this.type = "image";
        return image.src;
      }
    } else {
      return "Retry";
    }
  }
  async reloadSrc() {
    this.src = await this.getSrc();
  }
}
class InfinityScroll {
  /**
   * @param {Document} document
   * @param {DOMParser} _dp
   */
  constructor(document, _dp) {
    this.nextSended = false;
    this.pagesParsed = [this.getPageNumber(document)];
    this.nextPage = this.getNextPageHref(document);
    this.dp = _dp;
  }
  /**
   * @param {Document} doc
   */
  getPageNumber(doc) {
    return parseInt(doc.querySelector("#paginator div b").innerHTML);
  }
  /**
   * @param {Document} doc
   */
  getNextPageHref(doc) {
    const nextNode = doc.querySelector('#paginator [alt="next"]');
    return nextNode ? nextNode.href : null;
  }
  async getNextPage() {
    console.log("getNextPage");
    if (!this.nextPage) {
      this.nextPage = F.q('#paginator [alt="next"]').href;
    }
    const response = await fetch(this.nextPage);
    if([204,202,200,201].includes(response.status)){
        const body = await response.text();
        const dp = new DOMParser();
        const pageDocument = dp.parseFromString(body, "text/html");
        const pageNum = this.getPageNumber(pageDocument);
        this.nextPage = this.getNextPageHref(pageDocument);
        if (!this.pagesParsed.includes(pageNum)) { // remove the page allready parsed
          this.pagesParsed.push(pageNum);
          return pageDocument;
        } else {
          return false;
        }
    }else{
        await this.sleep(500);
        return await this.getNextPage();
    }
  }
  sleep(ms){
      return new Promise(resolve=>setTimeout(resolve,ms));
  }
  /**
   *
   * @param {Document} document
   * @param {number} pad The length of medias in the Modal Object
   * @returns {Media[]}
   */
  getMedias(document, pad) {
    const thumbsNode = F.qa("#content .thumb", document);
    const medias = [];
    const nodes = [];
    //const pad = this.medias? this.medias.length : 0;
    for (let i = 0; i < thumbsNode.length; i++) {
      const node = thumbsNode[i];
      /**
       * @type {HTMLImageElement} img
       */
      // @ts-ignore
      const img = F.q("img", node);
      const title = img.title;
      const anchor = node.querySelector("a");
      const media = new Media(
        anchor.href,
        /animated|video/.test(title) ? "video" : "image",
        img.src,
        this.dp
      );
      anchor.dataset.index = (i + pad).toString();
      img.dataset.index = (i + pad).toString();
      //node.dataset.index = (i+pad).toString();
      medias.push(media);
      nodes.push(node);
    }
    this.addElementsToCurrentContentView(nodes); // async
    return medias;
  }
  async addElementsToCurrentContentView(nodes) {
    for (const node of nodes) {
      this.clickFunction(node);
      F.q(".content").insertBefore(node, F.q("#paginator"));
    }
  }
  clickFunction(element){
    element.addEventListener("click", (e) => {
        e.preventDefault();
        const index = e.target.dataset.index
          ? e.target.dataset.index
          : modalObj.pointer;
        modalObj.pointer = index;
        modalObj.render(modalObj.medias[index]);
      });
  }
}
const dp = new DOMParser();
const F = new Falaz();
let modalObj;
const loadingSVG = "https://samherbert.net/svg-loaders/svg-loaders/puff.svg";

(function () {
  "use strict";
  modalObj = new Modal(document, dp);
  document.modalObj = modalObj;
  F.qa(".content .thumb").forEach((element) => {
    modalObj.infinityScroll.clickFunction(element);
  });
  document.addEventListener("keydown", (e) => {
    if (e.key == "ArrowRight") {
      modalObj.nextMedia();
    } else if (e.key == "ArrowLeft") {
      modalObj.prevMedia();
    } else if (e.key == "Escape") {
      modalObj.close();
    }
  });
  document.addEventListener("scroll", (e) => {
    const inner = window.innerHeight;
    if (
      window.scrollY + inner >
      document.documentElement.scrollHeight - inner * 2
    ) {
      modalObj.getNextPage();
    }
  });
})();