leobm / Imgur Copy Thumbnail Urls

/**
  The MIT License (MIT)

  Copyright (c) 2021 Jan-Felix Wittmann

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/
// ==UserScript==
// @id           ImgurCopyThumbnailUrls
// @name         Imgur Copy Thumbnail Urls
// @description  Displays buttons above imgur images so that you can copy the corresponding thumbnails URLs of the image.
// @version      0.5
// @author       Jan-Felix Wittmann <jfwittmann7@gmail.com>
// @copyright    2021, leobm (https://openuserjs.org/users/leobm)
// @license      MIT
// @match        *://imgur.com/*
// @icon         https://www.google.com/s2/favicons?domain=imgur.com
// @grant        GM_setClipboard
// @run-at       document-start
// @updateURL    https://openuserjs.org/meta/leobm/Imgur_Copy_Thumbnail_Urls.meta.js
// @downloadURL  https://openuserjs.org/install/leobm/Imgur_Copy_Thumbnail_Urls.user.js
// ==/UserScript==
/*jshint esversion: 9 */

(function (d) {
  'use strict';

  const thumbSizes = {
    's': 'Small Square 90x90',
    'b': 'Big Square 160x160',
    't': 'Small Thumbnail 160x160',
    'm': 'Medium Thumbnail 320x320',
    'l': 'Large Thumbnail 640x640',
    'h': 'Huge Thumbnail 1024x1024'
  };

  const idRegex = /i.imgur.com\/([^\._]+)(?:_d)?\.(jpeg|jpg|png|gif|webp)/;

  const renderClipboardButton = function (btnId, imgId, thumbSize, imgExt, isThumb) {
    let btn = d.createElement('button');
    btn.id = btnId;
    btn.style = `border: none;
                   border-radius:3px;
                   font-size: 0.8em;
                   color:#fff;
                   margin: 4px;
                   padding: 0.4em 1em;
                   font-weight:normal;
                   background-color: #1bb76e;
                   box-shadow: 0 6px 10px 0 rgba(27,28,30,.31);
                   cursor: pointer;
        `;
    btn.style.display = 'inline-block';
    btn.textContent = thumbSizes[thumbSize];
    btn.value = `https://i.imgur.com/${imgId}${thumbSize}.jpg`;
    btn.addEventListener("click", (e) => {
      alert(`Copy URL of the ${thumbSizes[thumbSize]} image to the clipboard`);
      GM_setClipboard(btn.value);
    });
    return btn;
  };

  const renderJSONViewer = function (aId, imgId) {
    let c = d.createElement('div');
    c.style = 'margin: 4px;';
    let a = d.createElement('a');
    a.id = aId;
    a.href = '#';
    a.textContent = "JSON";
    a.style = `display: inline-block;
                  border-radius:3px;
                  padding: 0.4em 1em;
                  font-size: 0.8em;
                  color:#fff;
                  background-color: #4a58fb;
       `;
    c.appendChild(a);

    // create textarea container
    let tc = d.createElement('div');
    tc.style = `display: none; position:relative;`;

    let txt = d.createElement('textarea');
    txt.rows = 10;
    txt.style = `width:100%;`;
    let gt = query(d, '.Gallery-Title .row span')[0];
    let author = query(d, '.Info-Wrapper .author-name')[0];
    let json = {};
    if (gt && author) {
      Object.assign(json, {
        gallery_title: gt.textContent,
        gallery_url: location.href,
        author_name: author.textContent,
        author_url: author.href
      });
    }
    json.thumbs = {};
    for (let thumbSize in thumbSizes) {
      json.thumbs[thumbSize] = {
        url: `https://i.imgur.com/${imgId}${thumbSize}.jpg`,
        description: thumbSizes[thumbSize]
      };
    }
    txt.value = JSON.stringify(json, null, 2);
    a.addEventListener("click", (e) => {
      tc.style.display = tc.style.display == 'none' ? 'block' : 'none';
      e.preventDefault();
    });
    tc.appendChild(txt);

    let cbc = d.createElement('div');
    cbc.style = `position:absolute;
                   top:0; right:0;             
                   background-color: orange;`

    // create base64 attachment checkbox container
    let cb = d.createElement('input');
    cb.style = `margin: 0.4em;`;
    cb.type = 'checkbox';
    cb.addEventListener("change", (e) => {
      if (e.target.checked) {
        let loadImages = [];
        for (let thumbSize in json.thumbs) {
          loadImages.push(toDataURL(thumbSize, json.thumbs[thumbSize].url));
        }
        Promise.all(loadImages).then((images) => {
          let jsonNew = JSON.parse(JSON.stringify(json));
          for (const [thumbSize, imageData] of images) {
            jsonNew.thumbs[thumbSize].data = imageData;
          }
          txt.value = JSON.stringify(jsonNew, null, 2);
        });
      }
      else {
        txt.value = JSON.stringify(json, null, 2);
      }
      e.preventDefault();
    });
    cbc.appendChild(cb);
    let lb = d.createElement('label');
    lb.style = `font-size: 0.8em; color: #fff; padding: 0.4em;`;
    lb.textContent = 'Attach image files as base64';
    cbc.appendChild(lb);
    tc.appendChild(cbc);

    c.appendChild(tc);
    return c;
  };

  watchForQuerySelector(d, "img.image-placeholder", ({
    foundNodes,
    stop,
    restart
  }) => {
    foundNodes.forEach(img => {
      let matches = img.src.match(idRegex),
        imgId = matches[1],
        imgExt = matches[2];
      for (let thumbSize in thumbSizes) {
        let btnId = `btn-${imgId}${thumbSize}`,
          btn = query(img.parentNode, `button#${btnId}`)[0];
        if (btn == undefined) {
          stop();
          btn = renderClipboardButton(btnId, imgId, thumbSize, imgExt, true);
          img.parentNode.insertBefore(btn, img);
          restart();
        }
      }
      let aId = `json-${imgId}`;
      let a = query(img.parentNode, `a#${aId}`)[0];
      if (a == undefined) {
        stop();
        img.parentNode.insertBefore(renderJSONViewer(aId, imgId), img);
        restart();
      }
    });
  });

  //**********************************************************************************
  // DOM Utilities
  //**********************************************************************************

  function watchForQuerySelector(targetNode, selector, callback, options) {
    let obsCallback = (obs) => {
      let foundNodes = query(targetNode, selector);
      if (foundNodes.length > 0) {
        callback({
          foundNodes,
          ...obs
        });
      }
    };
    observeNode(targetNode, obsCallback, options);
  }

  function observeNode(targetNode, callback, options) {
    let meOptions = options || {
      childList: true,
      subtree: true,
    };
    let observer = new MutationObserver((mutations, me) => {
      let obs = {
        restart: () => me.observe(targetNode, meOptions),
        stop: () => me.disconnect(),
        get mutations() {
          return mutations;
        },
      };
      callback(obs);
    });
    observer.observe(targetNode, meOptions);
    return observer;
  }

  function query(startNode, selector) {
    try {
      var nodes = Array.from(startNode.querySelectorAll(selector));
      return nodes;
    }
    catch (e) {}
    return [];
  }

  function toDataURL(id, url, callback) {
    return new Promise((resolve, reject) => {
      var xhr = new XMLHttpRequest();
      xhr.onload = function () {
        var reader = new FileReader();
        reader.onloadend = function () {
          if (callback) {
            callback([id, reader.result]);
          }
          else {
            resolve([id, reader.result]);
          }
        }
        reader.readAsDataURL(xhr.response);
      };
      xhr.open('GET', url);
      xhr.responseType = 'blob';
      xhr.send();
    });
  }

  // Your code here...
})(document);