Styx / Flaticon SVG downloader

// ==UserScript==
// @name         Flaticon SVG downloader
// @namespace    https://openuserjs.org/users/Styx
// @version      0.3
// @description  Helps to download SVG icons from Flaticon
// @author       Styx
// @copyright    2022, Styx (https://github.com/StyxUA)
// @license      MIT; https://opensource.org/licenses/MIT
// @updateURL    https://openuserjs.org/meta/Styx/Flaticon_SVG_downloader.meta.js
// @include      https://www.flaticon.com/*
// @grant        none
// @noframes
// ==/UserScript==

// ==OpenUserJS==
// @author Styx
// ==/OpenUserJS==

/**
 Copyright 2022 Styx (https://github.com/StyxUA)

 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.
 */

/**
 * RELEASE NOTES:
 *
 * 0.3
 *   + Added download buttons to icons in search result
 * 0.2
 *   + Added download buttons to icons in pack view
 *   + Added ability to download edited SVG from icon editor
 * 0.1
 *   + Initial version
 */

/** HONOR TO UKRAINE! **/

const $btn = $('<a class="btn btn-warning fsd-dl-button" download><i class="icon icon--download"></i><span class="mg-left-lv2">Download SVG</span></a>');
const $btnPack = $('<li class="tooltip tooltip--left"><a download class="fsd-pdl-button bj-button bj-button--icon bj-button--sm bj-button--yellow tooltip__trigger tooltip__trigger--always">'
  + '<i class="icon icon--download"></i></a><div class="tooltip__content tooltip__content--permanent"><div class="content"><span>Download SVG</span></div></div></li>');
const $btnPrepare = $('<li class="tooltip tooltip--left"><button class="fsd-pdl-button bj-button bj-button--icon bj-button--sm bj-button--purple tooltip__trigger tooltip__trigger--always">'
  + '<i class="icon icon--clip"></i></button><div class="tooltip__content tooltip__content--permanent"><div class="content"><span>Prepare SVG</span></div></div></li>');
const $btnEdited = $('<button class="bj-button bj-button--yellow mg-right-lv1" id="save_into_active"><i class="icon icon--download"></i><span>Download SVG</span></button>');

function addCSS() {
  const CSS = `
    .fsd-dl-button {
      margin-left: auto;
      height: 36px;
      padding: 0 20px;
      display: flex;
      align-items: center;
    }
    .fsd-dl-button > i {
      color: inherit !important;
      display: inline;
    }
    .fsd-pdl-button {
      pointer-events: all !important;
    }
  `;

  const head = document.head || document.getElementsByTagName('head')[0];
  const style = document.createElement('style');
  style.type = 'text/css';
  if (style.styleSheet) {
    style.styleSheet.cssText = CSS;
  } else {
    style.appendChild(document.createTextNode(CSS));
  }
  head.appendChild(style);
}

function retrieveUrl(id) {
  if (Number.isNaN(id) || !id) return Promise.reject();
  return fetch(`/editor/icon/svg/${id}?type=standard`, { headers: { 'x-requested-with': 'XMLHttpRequest' } })
    .then(r => r.json())
    .then(({ url }) => url);
}

function attachDownloadToPacksAndSearch() {
  $(document).on('mouseenter', '.pack-view li.icon--item:not(.fsd-attached), .search-result li.icon--item:not(.fsd-attached)', function (ev) {
    const el = ev.currentTarget;
    const iconId = parseInt(el.getAttribute('data-id'), 10);
    el.classList.add('fsd-attached');
    const ctxm = $(el.querySelector('.icon--item__context-menu'));
    ctxm.children().last().remove();
    $btnPrepare.clone().find('button').click(() => {
      retrieveUrl(iconId)
        .then(url => {
          const btn = $btnPack.clone();
          btn.find('a').attr('href', url);
          ctxm.children().last().remove();
          btn.appendTo(ctxm);
        });
    }).end().appendTo(ctxm);
  });
}

function attachDownloadButtons() {
  $('.detail__icon__holder--header > .row:not(.fsd-attached)').each(function (idx, el) {
    const be = el.querySelector('button.btn-edit-icon');
    try {
      const iconId = parseInt(be.getAttribute('data-track-arguments').split(',').pop().trim(), 10);
      retrieveUrl(iconId)
        .then(url => $btn.clone().attr('href', url).insertBefore(be));
      el.classList.add('fsd-attached');
    } catch (e) {
      // do nothing
    }
  });

  $('.detail__editor__header .edit-icons-user-actions > .row:not(.fsd-attached)').each(function (idx, el) {
    const btn = $btnEdited.clone();
    btn.click((ev) => {
      const svg = document.querySelector('.detail__editor__icon-holder > svg').outerHTML;
      const iconId = document.querySelector('section#detail').getAttribute('data-elementid');
      const link = document.createElement('a');
      link.download = `${iconId}.svg`;
      link.href = `data:image/svg+xml;base64,${window.btoa(svg)}`;
      link.click();
    }).prependTo(el);
    let reenable;
    reenable = setInterval(() => {
      const el = btn.get(0);
      if (el) {
        el.disabled = false;
      } else {
        clearInterval(reenable);
      }
    }, 1000);
    el.classList.add('fsd-attached');
  });
}

function startObserver() {
  const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
  const observer = new MutationObserver(function (mutations) {
    mutations.filter(({ attributeName }) => attributeName === 'class').forEach(({ target }) => {
      if(target.classList.contains('ready')) {
        setTimeout(attachDownloadButtons, 250);
      }
    });
  });
  observer.observe(document.querySelector('#detail-overlay'), { attributes: true })
}

if (window.USER_REGISTERED) {
  addCSS();
  attachDownloadButtons();
  attachDownloadToPacksAndSearch();
  startObserver();
}