elwm / gfy-tools

(function () {
// ASSET: actions\gfy2cb.ts
// ASSET: util.ts
var $BHXf$var$_temp;

function $BHXf$export$compareLists(a, b) {
  var alist = a.split(/(\d+)/),
      // split text on change from anything to digit and digit to anything
  blist = b.split(/(\d+)/); // split text on change from anything to digit and digit to anything

  alist.slice(-1) === '' ? alist.pop() : null; // remove the last element if empty

  blist.slice(-1) === '' ? blist.pop() : null; // remove the last element if empty

  for (var i = 0, len = alist.length; i < len; i++) {
    if (alist[i] != blist[i]) {
      // find the first non-equal part
      if (alist[i].match(/\d/)) {
        // if numeric
        return +alist[i] - +blist[i]; // compare as number
      } else {
        return alist[i].localeCompare(blist[i]); // compare as string
      }
    }
  }

  return true;
}

function $BHXf$export$scaleRes(width, height, targetWidth = 560) {
  let widthScale = targetWidth / width;
  let targetHeight = Math.round(height * widthScale);
  return {
    width: targetWidth,
    height: targetHeight
  };
}

function $BHXf$export$copyToClipboard(str) {
  const el = document.createElement('textarea');
  el.value = str;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
}

function $BHXf$export$injectCSS(css, id) {
  const style = document.createElement('style');
  style.setAttribute('id', id);
  style.innerHTML = css;
  document.body.appendChild(style);
  return style;
}

function $BHXf$export$deleteElement(elem) {
  if (elem && elem.parentElement) {
    elem.parentElement.removeChild(elem);
  }
}

function $BHXf$export$htmlToElement(html) {
  const template = document.createElement('template');
  html = html.trim(); // Never return a text node of whitespace as the result

  template.innerHTML = html;
  return template.content.firstChild;
}

var $BHXf$export$VideoPlatforms;

(function (VideoPlatforms) {
  VideoPlatforms["youtube"] = "youtube";
  VideoPlatforms["vlive"] = "vlive";
})($BHXf$export$VideoPlatforms || ($BHXf$var$_temp = $BHXf$export$VideoPlatforms = {}, $BHXf$var$_temp));

function $BHXf$export$getPlatformVideoUrl(platform, videoID) {
  if (platform === $BHXf$export$VideoPlatforms.youtube) {
    return "https://www.youtube.com/watch?v=".concat(videoID);
  } else if ($BHXf$export$VideoPlatforms.vlive) {
    return "https://www.vlive.tv/video/".concat(videoID);
  }
}

function $ZFp6$export$gfy2cb(page = 'any', format = 'md') {
  const formats = format.split('+');
  let urls = Array.from(document.getElementsByClassName('copy-input-text'));
  urls = urls.map(input => {
    return input.value;
  });
  let titleInputs = Array.from(document.querySelectorAll('div.titleinput-container > div > div > input'));

  if (!titleInputs.length) {
    titleInputs = Array.from(document.querySelectorAll('.gfycat-list-feed-item__title'));
  }

  titleInputs = titleInputs.map(input => {
    var _a;

    return (_a = input.value) !== null && _a !== void 0 ? _a : input.textContent;
  });
  let imgs = Array.from(document.querySelectorAll('.list-feed-item-image img'));
  imgs = imgs.map(gfy => {
    return $BHXf$export$scaleRes(gfy.naturalWidth, gfy.naturalHeight + 51);
  });
  let gfys = titleInputs.map((title, i) => {
    return {
      title: title,
      link: urls[i],
      img: imgs[i]
    };
  });
  gfys = gfys.sort((a, b) => {
    return $BHXf$export$compareLists(a.title, b.title);
  });
  let md = '';

  if (formats.includes('plain')) {
    gfys.forEach((link, num) => {
      md += "".concat(formats.includes('numbered') ? num + 1 + ': ' : '').concat(formats.includes('titles') ? link.title + ' ' : '').concat(link.link, "\n");
    });
    $BHXf$export$copyToClipboard(md);
    return;
  }

  if (gfys.length > 0) {}

  let mdSections = [];
  let currSection = -1;
  const sources = [];
  gfys.forEach(gfy => {
    const {
      newSource
    } = $ZFp6$var$getSource(gfy, sources);

    if (newSource) {
      mdSections.push([]);
      currSection++;
    }

    const gfyElement = $ZFp6$var$getGfyElement(gfy, formats);
    mdSections[currSection].push(gfyElement);
  });
  mdSections.forEach((section, i) => {
    if (sources[i]) section.push($ZFp6$var$getSourceElement(sources[i], i, formats));
  });

  if (page === 'album' && location.href.includes('collection')) {
    const album = location.href.replace('manage/', '');

    if (formats.includes('md')) {
      mdSections[mdSections.length - 1].push("[Album](".concat(album, ")"));
    } else if (formats.includes('iframe')) {
      mdSections[mdSections.length - 1].push("<a href='".concat(album, "'>Album</a>"));
    }
  }

  mdSections = mdSections.map(section => {
    if (formats.includes('md')) {
      return section.join('\n\n');
    } else if (formats.includes('iframe')) {
      return section.join('<br><br>\n\n');
    }
  });

  if (formats.includes('md')) {
    md = mdSections.join('\n\n---\n\n');
  } else if (formats.includes('iframe')) {
    md = mdSections.join('<br><hr><br>\n\n\n');
  }

  $BHXf$export$copyToClipboard(md);
}

function $ZFp6$var$getGfyElement(gfy, formats) {
  if (formats.includes('md')) {
    return "[".concat(gfy.title, "](").concat(gfy.link, ")");
  } else if (formats.includes('iframe')) {
    gfy.link = gfy.link.replace('gfycat.com/', 'gfycat.com/ifr/');
    console.log(gfy);
    return "<iframe src='".concat(gfy.link, "' frameborder='0' scrolling='no' allowfullscreen width='").concat(gfy.img.width, "' height='").concat(gfy.img.height, "'></iframe>");
  }
}

function $ZFp6$var$getSourceElement(source, index, formats) {
  if (formats.includes('md')) {
    return "[Source ".concat(index + 1, "](").concat(source, ")");
  } else if (formats.includes('iframe')) {
    return "<a href='".concat(source, "'>Source ").concat(index + 1, "</a>\n");
  }
}

function $ZFp6$var$getSource(gfy, sources) {
  const platformRegex = "(?:(.*)@)?";
  const youtubeVideoIDRegex = "(?:[-_ \\d\\w]{11})";
  const vliveVideoIDRegex = "(?:\\d{3,8})";
  const videoIDRegex = "(".concat(youtubeVideoIDRegex, "|").concat(vliveVideoIDRegex, ")");
  const sourceRegex = "\\[".concat(platformRegex).concat(videoIDRegex, "\\]");
  const matches = gfy.title.match(sourceRegex);
  let platform, videoID;
  let newSource = true;

  if (matches != null) {
    if (matches[1] != null) {
      platform = matches[1];
    } else {
      platform = $BHXf$export$VideoPlatforms.youtube;
    }

    videoID = matches[2].replace(' ', '_');
    const source = $BHXf$export$getPlatformVideoUrl(platform, videoID);
    newSource = !sources.includes(source);
    if (newSource) sources.push(source);
  } else {
    sources.push('');
  }

  return {
    newSource,
    platform,
    videoID
  };
}

const $VtGo$var$paginateCSS = ".m-grid-container {\n  display: none !important;\n}\n.grid-item {\n  width: 300px;\n  height: fit-content;\n  margin-bottom: 3px;\n}\n.paginate-grid {\n  position: relative;\n  margin: 0 auto;\n  max-width: 100%;\n  margin-top: 10px;\n  width: 310px;\n}\n\n@media (min-width: 630px) {\n  .paginate-grid {\n    width: 620px;\n  }\n}\n@media (min-width: 938px) {\n  .paginate-grid {\n    width: 930px;\n  }\n}\n@media (min-width: 1247px) {\n  .paginate-grid {\n    width: 1240px;\n  }\n}\n\n.page-navigator .page .page-input {\n  position: relative;\n  width: 36px;\n  height: 36px;\n  border: 1px solid hsla(0, 0%, 100%, 0.3);\n  border-radius: 0;\n  outline: none;\n  font-size: 1.3rem;\n  text-align: center;\n  text-transform: none;\n  color: #fff;\n  background-color: transparent;\n  padding: 0;\n}\n\n#searchBarContainer {\n  margin-left: 10px;\n}\n\n#searchBar {\n  width: 300px;\n  border: 1px solid rgb(45, 131, 199);\n}\n\n.textOverlaysContainer {\n  display: none;\n  position: absolute;\n  padding: 1px;\n  top: -8px;\n  left: 0px;\n  z-index: 2;\n  user-select: none;\n}\n\n.textOverlay {\n  display: inline-block;\n  font-size: 9pt;\n  color: white;\n  font-weight: 600;\n  opacity: 0.6;\n  -webkit-filter: grayscale(100%);\n  filter: grayscale(100%);\n  user-select: none;\n  text-shadow: -1px -1px 0 black, 1px -1px black, -1px 1px 0 black, 1px 1px 0 black,\n    -1px 0px 0px black, 0px -1px 0px black, 1px 0px 0px black, 0px 1px 0px black;\n}\n.emojiOverlay {\n  text-shadow: none;\n}\n.likes.emojiOverlay {\n  -webkit-filter: grayscale(100%) brightness(3.5);\n  filter: grayscale(100%) brightness(3.5);\n}\n\n.grid-item:hover > .textOverlaysContainer {\n  display: block;\n}\n";
let $VtGo$var$gfysPerPage = 20;
let $VtGo$var$nPages = 0;
let $VtGo$var$nGfys = 0;
let $VtGo$var$gfysContainer;
let $VtGo$var$currPage = 0;
let $VtGo$var$pageInput;
let $VtGo$var$searchBar;
const $VtGo$var$userIdRegex = "gfycat.com/@([\\d\\w._-]*)$";

async function $VtGo$export$paginate() {
  if ($VtGo$var$gfysContainer) return;
  const isProfilePage = location.href.match($VtGo$var$userIdRegex);

  if (!isProfilePage) {}

  window.addEventListener('scroll', function (event) {
    event.stopImmediatePropagation();
  }, true);
  const profileContent = document.getElementsByClassName('profile-content')[0];
  $VtGo$var$nGfys = await $VtGo$var$getNumPublishedGfys();
  $VtGo$var$nPages = $VtGo$var$nGfys / $VtGo$var$gfysPerPage;
  profileContent.appendChild($VtGo$var$getPaginatorBar(1));
  profileContent.appendChild($VtGo$var$getMenuBar());
  let currentSort = 'Date▼';
  const sortByDateButton = document.getElementById('sortGfysByDate');
  const sortByViewsButton = document.getElementById('sortGfysByViews');
  const sortByLikesButton = document.getElementById('sortGfysByLikes');

  const gfyDateComparator = (gfyA, gfyB) => gfyB.createDate - gfyA.createDate;

  const gfyLikesComparator = (gfyA, gfyB) => parseInt(gfyB.likes, 10) - parseInt(gfyA.likes, 10);

  const gfyViewsComparator = (gfyA, gfyB) => gfyB.views - gfyA.views;

  const reverse = f => (gfyA, gfyB) => -f(gfyA, gfyB);

  sortByDateButton.addEventListener('click', () => {
    if (currentSort === 'Date▼') {
      currentSort = 'Date▲';
      $VtGo$var$sortGfysBy(reverse(gfyDateComparator));
    } else {
      currentSort = 'Date▼';
      $VtGo$var$sortGfysBy(gfyDateComparator);
    }

    sortByDateButton.textContent = currentSort;
    sortByViewsButton.textContent = 'Views';
    sortByLikesButton.textContent = 'Likes';
  });
  sortByViewsButton.addEventListener('click', () => {
    if (currentSort === 'Views▼') {
      currentSort = 'Views▲';
      $VtGo$var$sortGfysBy(reverse(gfyViewsComparator));
    } else {
      currentSort = 'Views▼';
      $VtGo$var$sortGfysBy(gfyViewsComparator);
    }

    sortByDateButton.textContent = 'Date';
    sortByViewsButton.textContent = currentSort;
    sortByLikesButton.textContent = 'Likes';
  });
  sortByLikesButton.addEventListener('click', () => {
    if (currentSort === 'Likes▼') {
      currentSort = 'Likes▲';
      $VtGo$var$sortGfysBy(reverse(gfyLikesComparator));
    } else {
      currentSort = 'Likes▼';
      $VtGo$var$sortGfysBy(gfyLikesComparator);
    }

    sortByDateButton.textContent = 'Date';
    sortByViewsButton.textContent = 'Views';
    sortByLikesButton.textContent = currentSort;
  });
  const copyGfyLinksButton = document.getElementById('copyGfyLinks');
  copyGfyLinksButton.addEventListener('click', () => {
    $VtGo$var$copyGfyLinks();
  });
  const copyGfyGiantLinksButton = document.getElementById('copyGfyGiantLinks');
  copyGfyGiantLinksButton.addEventListener('click', () => {
    $VtGo$var$copyGfyGiantLinks();
  });
  $VtGo$var$searchBar = document.getElementById('searchBar');
  $VtGo$var$searchBar.addEventListener('change', $VtGo$var$searchBarHandler);
  $VtGo$var$gfysContainer = profileContent.getElementsByClassName('m-grid-container')[0];
  $BHXf$export$injectCSS($VtGo$var$paginateCSS, 'paginateCSS');
  $VtGo$var$gfysContainer = document.createElement('div');
  $VtGo$var$gfysContainer.className = 'paginate-grid';
  profileContent.appendChild($VtGo$var$gfysContainer);
  const pageNavigator = document.getElementsByClassName('page-navigator')[0];
  const nextButton = pageNavigator.getElementsByClassName('next')[0];
  const prevButton = pageNavigator.getElementsByClassName('previous')[0];
  $VtGo$var$pageInput = pageNavigator.getElementsByClassName('page-input')[0];
  $VtGo$var$nextPage();
  nextButton.addEventListener('click', $VtGo$var$nextPage);
  prevButton.addEventListener('click', $VtGo$var$prevPage);
  $VtGo$var$pageInput.addEventListener('change', $VtGo$var$pageInputHandler);
}

function $VtGo$var$getPaginatorBar(page) {
  const paginatorBar = "\n    <div class=\"paginator-bar-container bottom-bar\">\n      <div class=\"left\">\n        <span id=\"gfyPageStats\" class=\"text\"\n          ><strong>".concat((page - 1) * $VtGo$var$gfysPerPage, "</strong>-<strong\n            >").concat(Math.min(page * $VtGo$var$gfysPerPage, $VtGo$var$nGfys), "</strong\n          >\n          OF <strong>").concat($VtGo$var$nGfys, "</strong></span\n        >\n      </div>\n      <div class=\"right\">\n        <div class=\"page-navigator\">\n          <div class=\"page-control previous\">\n            <span class=\"SVGInline ic ic-chevron\"\n              ><svg\n                class=\"SVGInline-svg ic-svg ic-chevron-svg\"\n                viewBox=\"0 0 6 10\"\n                xmlns=\"http://www.w3.org/2000/svg\"\n                fill-rule=\"evenodd\"\n                clip-rule=\"evenodd\"\n                stroke-miterlimit=\"10\"\n              >\n                <path\n                  d=\"M1.13 8.854a.546.546 0 0 1 0-.707L3.927 5 1.13 1.854a.546.546 0 0 1 0-.707.41.41 0 0 1 .629 0l3.111 3.5a.546.546 0 0 1 0 .707l-3.111 3.5A.422.422 0 0 1 1.445 9a.423.423 0 0 1-.315-.146z\"\n                ></path></svg\n            ></span>\n          </div>\n          <div class=\"page\">\n            <input\n              id=\"pageInput\"\n              autocomplete=\"off\"\n              class=\"page-input\"\n              name=\"currentPage\"\n              value=\"").concat(page, "\"\n            />\n            <span class=\"divider\">/</span><span id=\"maxPageCount\" class=\"max-page-count\">").concat($VtGo$var$nPages, "</span>\n          </div>\n          <div class=\"page-control next\">\n            <span class=\"SVGInline ic ic-chevron\"\n              ><svg\n                class=\"SVGInline-svg ic-svg ic-chevron-svg\"\n                viewBox=\"0 0 6 10\"\n                xmlns=\"http://www.w3.org/2000/svg\"\n                fill-rule=\"evenodd\"\n                clip-rule=\"evenodd\"\n                stroke-miterlimit=\"10\"\n              >\n                <path\n                  d=\"M1.13 8.854a.546.546 0 0 1 0-.707L3.927 5 1.13 1.854a.546.546 0 0 1 0-.707.41.41 0 0 1 .629 0l3.111 3.5a.546.546 0 0 1 0 .707l-3.111 3.5A.422.422 0 0 1 1.445 9a.423.423 0 0 1-.315-.146z\"\n                ></path></svg\n            ></span>\n          </div>\n        </div>\n      </div>\n    </div>\n  ");
  return $BHXf$export$htmlToElement(paginatorBar);
}

function $VtGo$var$updatePaginatorBar(page) {
  const gfyPageStats = document.getElementById('gfyPageStats');
  const pageInput = document.getElementById('pageInput');
  const maxPageCount = document.getElementById('maxPageCount');
  gfyPageStats.innerHTML = "\n    <strong>".concat((page - 1) * $VtGo$var$gfysPerPage, "</strong>-<strong\n      >").concat(Math.min(page * $VtGo$var$gfysPerPage, $VtGo$var$nGfys), "</strong\n    >\n    OF <strong>").concat($VtGo$var$nGfys, "</strong>\n  ");
  pageInput.value = page;
  maxPageCount.innerText = $VtGo$var$nPages;
}

function $VtGo$var$getMenuBar() {
  const menuBar = "\n    <div id=\"searchBarContainer\" class=\"search-bar\">\n      <input id=\"searchBar\" class=\"search-input\" name=\"searchText\" placeholder=\"Fuzzy search library\"/>\n      <button class=\"search-button\">\n        <span class=\"SVGInline ic ic-search\"\n          ><svg\n            class=\"SVGInline-svg ic-svg ic-search-svg\"\n            fill=\"#ffffff\"\n            viewBox=\"0 0 20 20\"\n            xmlns=\"http://www.w3.org/2000/svg\"\n            fill-rule=\"evenodd\"\n            clip-rule=\"evenodd\"\n            stroke-linejoin=\"round\"\n            stroke-miterlimit=\"1.414\"\n          >\n            <path\n              d=\"M2.476 14.445a8.675 8.675 0 0 0 2.692 1.809 8.268 8.268 0 0 0 3.293.667 8.275 8.275 0 0 0 4.8-1.485l4.112 4.111c.301.301.646.453 1.076.453.43 0 .776-.152 1.098-.453.301-.323.453-.667.453-1.098 0-.408-.152-.775-.453-1.076l-4.111-4.112a8.275 8.275 0 0 0 1.485-4.8c0-1.141-.215-2.24-.667-3.294a8.696 8.696 0 0 0-1.808-2.69 8.715 8.715 0 0 0-2.691-1.81A8.275 8.275 0 0 0 8.46 0C7.32 0 6.221.216 5.168.668a8.696 8.696 0 0 0-2.692 1.808 8.71 8.71 0 0 0-1.808 2.69A8.276 8.276 0 0 0 0 8.462c0 1.14.216 2.239.668 3.294a8.699 8.699 0 0 0 1.808 2.69zM8.461 3.079c1.485 0 2.756.517 3.81 1.572 1.055 1.055 1.572 2.324 1.572 3.81 0 1.485-.517 2.756-1.571 3.81-1.055 1.055-2.326 1.572-3.81 1.572-1.487 0-2.756-.517-3.811-1.571-1.055-1.055-1.572-2.326-1.572-3.81 0-1.487.517-2.756 1.572-3.811 1.055-1.055 2.324-1.572 3.81-1.572z\"\n            ></path></svg\n        ></span>\n      </button>\n      <span style=\"white-space:pre;color:white\">    Actions: </span>\n        <a id=\"copyGfyLinks\" class=\"outlined-button\"\">Copy Links</a>\n        <a id=\"copyGfyGiantLinks\" class=\"outlined-button\"\">Copy Giant Links</a>\n      <span style=\"white-space:pre;color:white\">    Sort Gfys: </span>\n        <a id=\"sortGfysByDate\" class=\"outlined-button\">Date\u25BC</a>\n        <a id=\"sortGfysByViews\" class=\"outlined-button\">Views</a>\n        <a id=\"sortGfysByLikes\" class=\"outlined-button\">Likes</a>\n    </div>\n  ";
  return $BHXf$export$htmlToElement(menuBar);
}

async function $VtGo$var$nextPage() {
  if ($VtGo$var$currPage < $VtGo$var$nPages) {
    $VtGo$var$currPage++;
    $VtGo$var$pageInput.value = $VtGo$var$currPage;
    await $VtGo$var$changePage($VtGo$var$currPage);
  }
}

async function $VtGo$var$prevPage() {
  if ($VtGo$var$currPage > 1) {
    $VtGo$var$currPage--;
    $VtGo$var$pageInput.value = $VtGo$var$currPage;
    await $VtGo$var$changePage($VtGo$var$currPage);
  }
}

async function $VtGo$var$pageInputHandler(e) {
  const prevPage = $VtGo$var$currPage;
  $VtGo$var$currPage = e.target.value;

  if ($VtGo$var$currPage >= $VtGo$var$nPages) {
    $VtGo$var$currPage = prevPage;
    e.target.value = prevPage;
  } else {
    await $VtGo$var$changePage($VtGo$var$currPage);
  }
}

let $VtGo$var$cursor = '';
let $VtGo$var$iso;
let $VtGo$var$gfysUnfiltered = [];

async function $VtGo$var$changePage(page) {
  if (!$VtGo$var$iso) {
    $VtGo$var$iso = new Isotope($VtGo$var$gfysContainer, {
      itemSelector: '.grid-item',
      layoutMode: 'masonry',
      masonry: {
        columnWidth: 300,
        gutter: 5
      }
    });
  }

  const startGfyIndex = $VtGo$var$gfysPerPage * (page - 1);
  const endGfyIndex = $VtGo$var$gfysPerPage * page;
  $VtGo$var$iso.remove($VtGo$var$gfysContainer.children);
  const gfys = $VtGo$var$isFiltered ? $VtGo$var$gfysFiltered : $VtGo$var$gfysUnfiltered;
  const searchBarContainer = document.getElementById('searchBarContainer');
  const loadingSpinner = $VtGo$var$getLoadingSpinner();
  searchBarContainer.insertAdjacentElement('afterend', loadingSpinner);

  if (!$VtGo$var$isFiltered) {
    while (endGfyIndex >= $VtGo$var$gfysUnfiltered.length) {
      const gfyPage = await $VtGo$var$fetchGfyPage($VtGo$var$cursor);
      $VtGo$var$cursor = gfyPage.cursor;
      $VtGo$var$gfysUnfiltered.push(...gfyPage.gfycats);
    }
  }

  $BHXf$export$deleteElement(loadingSpinner);
  const newPage = [];
  gfys.slice(startGfyIndex, endGfyIndex).forEach(gfy => {
    const {
      width,
      height
    } = $BHXf$export$scaleRes(gfy.width, gfy.height, 300);
    const gfyItem = $BHXf$export$htmlToElement("\n      <div class=\"grid-item\">\n        <a href=\"/".concat(gfy.gfyId, "\">\n          <picture>\n            <source srcset=\"").concat(gfy.webpUrl, "\" type=\"image/webp\" />\n            <source srcset=\"").concat(gfy.max2mbGif, "\" type=\"image/gif\" />\n            <img src=\"").concat(gfy.max1mbGif, "\" width=\"").concat(width, "px\" height=\"").concat(height, "\"/>\n          </picture>\n          </a>\n        <div class=\"textOverlaysContainer\">\n        <p class=\"views emojiOverlay textOverlay\">\uD83D\uDC41\uFE0F</p><p class=\"views textOverlay\">").concat(gfy.views, "</p>\n        <p class=\"likes emojiOverlay textOverlay\">\u2764\uFE0F</p><p class=\"likes textOverlay\">").concat(gfy.likes, "</p>\n        </div>\n      </div>\n    "));
    newPage.push(gfyItem);
  });
  $VtGo$var$iso.insert(newPage);
  window.dispatchEvent(new Event('resize'));
  $VtGo$var$iso.layout();
  $VtGo$var$currPage = page;
  $VtGo$var$updatePaginatorBar(page);
}

let $VtGo$var$gfysFiltered = [];
let $VtGo$var$isFiltered = false;
let $VtGo$var$search = '';
const $VtGo$var$fuseOptions = {
  tokenize: true,
  findAllMatches: true,
  includeScore: true,
  threshold: 0.1,
  location: 0,
  distance: Infinity,
  maxPatternLength: 128,
  minMatchCharLength: 0,
  keys: ['title', 'tags']
};
let $VtGo$var$fuse;

async function $VtGo$var$searchBarHandler(e) {
  $VtGo$var$search = e.target.value;

  if ($VtGo$var$search === '') {
    $VtGo$var$gfysFiltered = [];
    $VtGo$var$isFiltered = false;
    $VtGo$var$nGfys = $VtGo$var$gfysUnfiltered.length;
    $VtGo$var$nPages = $VtGo$var$nGfys / $VtGo$var$gfysPerPage;
  } else {
    await $VtGo$var$fetchAllGfys();
    if (!$VtGo$var$fuse) $VtGo$var$fuse = new Fuse($VtGo$var$gfysUnfiltered, $VtGo$var$fuseOptions); // "list" is the item array

    $VtGo$var$gfysFiltered = $VtGo$var$fuse.search($VtGo$var$search).map(searchResult => {
      return searchResult.item;
    }); // console.log(gfysFiltered);
    // gfysFiltered = gfysUnfiltered.filter((gfy) => {
    //   return gfy.title.match(search);
    // });

    $VtGo$var$isFiltered = true;
    $VtGo$var$nGfys = $VtGo$var$gfysFiltered.length;
    $VtGo$var$nPages = $VtGo$var$nGfys / $VtGo$var$gfysPerPage;
  }

  $VtGo$var$changePage(1);
}

const $VtGo$var$loadingSpinnerCSS = "\n  .lds-ring { display: inline-block; position: relative; width: 200px; height: 200px; margin: 10px; margin-left: 45% }\n  .lds-ring div { box-sizing: border-box; display: block; position: absolute; width: 200px;\n  height: 200px; margin: 8px; border: 8px solid #cef; border-radius: 50%; animation:\n  lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite; border-color: #cef transparent\n  transparent transparent; } .lds-ring div:nth-child(1) { animation-delay: -0.45s; }\n  .lds-ring div:nth-child(2) { animation-delay: -0.3s; } .lds-ring div:nth-child(3) {\n  animation-delay: -0.15s; } @keyframes lds-ring { 0% { transform: rotate(0deg); } 100% {\n  transform: rotate(360deg); } }\n\n  #loadPercent {\n    color: white;\n    position: absolute;\n    left: 42%;\n    top: 48%;\n  }\n";
const $VtGo$var$loadingSpinnerHTML = "\n<div class=\"lds-ring\">\n  <div></div><div></div><div></div><div></div>\n  <span id=\"loadPercent\">0%</span>\n</div>\n";

function $VtGo$var$getLoadingSpinner() {
  const loadingSpinnerStyle = $BHXf$export$injectCSS($VtGo$var$loadingSpinnerCSS, 'loading-spinner-css');
  const loadingSpinner = $BHXf$export$htmlToElement($VtGo$var$loadingSpinnerHTML);
  return loadingSpinner;
}

async function $VtGo$var$fetchAllGfys() {
  const searchBarContainer = document.getElementById('searchBarContainer');
  const loadingSpinner = $VtGo$var$getLoadingSpinner();
  searchBarContainer.insertAdjacentElement('afterend', loadingSpinner);
  const loadPercentSpan = document.getElementById('loadPercent');
  let loadPercent = ($VtGo$var$gfysUnfiltered.length / $VtGo$var$nGfys * 100).toFixed(2);
  loadPercentSpan.textContent = "".concat(loadPercent, "%");

  while ($VtGo$var$cursor) {
    console.log($VtGo$var$cursor);
    const gfyPage = await $VtGo$var$fetchGfyPage($VtGo$var$cursor);
    $VtGo$var$cursor = gfyPage.cursor;
    $VtGo$var$gfysUnfiltered.push(...gfyPage.gfycats);
    loadPercent = ($VtGo$var$gfysUnfiltered.length / $VtGo$var$nGfys * 100).toFixed(2);
    loadPercentSpan.textContent = "".concat(loadPercent, "%");
  }

  $BHXf$export$deleteElement(loadingSpinner);
}

async function $VtGo$var$copyGfyLinks() {
  await $VtGo$var$fetchAllGfys();
  let gfys = $VtGo$var$isFiltered ? $VtGo$var$gfysFiltered : $VtGo$var$gfysUnfiltered;
  gfys = gfys.map(gfy => {
    return "https://gfycat.com/".concat(gfy.gfyId);
  });
  $BHXf$export$copyToClipboard(gfys.join('\n'));
}

async function $VtGo$var$copyGfyGiantLinks() {
  await $VtGo$var$fetchAllGfys();
  let gfys = $VtGo$var$isFiltered ? $VtGo$var$gfysFiltered : $VtGo$var$gfysUnfiltered;
  gfys = gfys.map(gfy => {
    // console.log(gfy);
    return gfy.webmUrl;
  });
  $BHXf$export$copyToClipboard(gfys.join('\n'));
}

async function $VtGo$var$sortGfysBy(gfyComparator) {
  await $VtGo$var$fetchAllGfys();
  const gfys = $VtGo$var$isFiltered ? $VtGo$var$gfysFiltered : $VtGo$var$gfysUnfiltered;
  const gfysSorted = [...gfys];
  gfysSorted.sort(gfyComparator);
  $VtGo$var$isFiltered ? $VtGo$var$gfysFiltered = gfysSorted : $VtGo$var$gfysUnfiltered = gfysSorted;
  $VtGo$var$changePage($VtGo$var$currPage);
  return gfysSorted;
}

async function $VtGo$var$fetchGfyPage(cursor, count = 100) {
  const userId = location.href.match($VtGo$var$userIdRegex)[1];
  let url = "https://api.gfycat.com/v1/users/".concat(userId, "/gfycats?count=").concat(count);
  if (cursor) url += "&cursor=".concat(cursor);

  try {
    const data = await fetch(url).then(res => res.json());
    console.log(data);
    return data;
  } catch (error) {
    console.error(error);
  }
}

async function $VtGo$var$getNumPublishedGfys() {
  const userId = location.href.match($VtGo$var$userIdRegex)[1];
  let url = "https://api.gfycat.com/v1/users/".concat(userId);

  try {
    const data = await fetch(url).then(res => res.json());
    return data.publishedGfycats;
  } catch (error) {
    console.error(error);
  }
}

function $PbQt$export$quicktag() {
  const tagsContainers = Array.from(document.getElementsByClassName('tagsinput-container'));
  const tagsInputs = Array.from(document.getElementsByClassName('react-tagsinput-input'));

  if (tagsContainers.length > 1) {
    const firstTagsWrapper = tagsContainers.shift();
    const firstGfyTags = Array.from(firstTagsWrapper.getElementsByClassName('react-tagsinput-tag')).map(span => span.textContent);
    const firstTagsInput = tagsInputs.shift();
    firstGfyTags.push(firstTagsInput.value);

    for (let tagsWrapper of tagsContainers) {
      //   const tagsReactInput = tagsWrapper.getElementsByClassName('react-tagsinput')[0];
      const tagsInput = tagsWrapper.getElementsByClassName('react-tagsinput-input')[0];

      for (let tag of firstGfyTags) {
        $PbQt$var$addTag(tagsInput, tag);
      }
    }
  }
}

function $PbQt$var$addTag(input, tag) {
  let lastValue = input.value;
  input.value = tag;
  let inputEvent = new Event('input', {
    bubbles: true
  }); // React15 compatibility

  inputEvent.simulated = true; // React16 compatibility

  let tracker = input._valueTracker;

  if (tracker) {
    tracker.setValue(lastValue);
  }

  input.dispatchEvent(inputEvent);
  let focusOutEvent = new Event('focusout', {
    bubbles: true
  });
  input.dispatchEvent(focusOutEvent);
}

function $PbQt$export$deleteTags() {
  const tagsWrappers = Array.from(document.getElementsByClassName('scrollable-tags-wrapper'));

  if (tagsWrappers.length > 1) {
    for (let tagsWrapper of tagsWrappers) {
      const removeButtons = tagsWrapper.getElementsByClassName('react-tagsinput-remove');

      if (removeButtons.length >= 1) {
        removeButtons[removeButtons.length - 1].click();
      }
    }
  }
}

// BANNER GUARD
// ==UserScript==
// @locale       english
// @name         gfy-tools
// @namespace    https://github.com/exwm
// @version      1.1.0
// @description  Tools for automating tasks on gfycat.com
// @run-at       document-end
// @license      ISC
// @author       exwm
// @match        *://*gfycat.com/*
// @match        *://*gfycat.com/@*
// @require      https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.4.5/fuse.min.js
// @grant        none
// ==/UserScript==
document.addEventListener('keydown', $b7zt$var$hotkeys, false);

async function $b7zt$var$hotkeys(e) {
  switch (e.code) {
    case 'KeyA':
      if (e.ctrlKey && e.shiftKey && !e.altKey) {
        $b7zt$var$prep(e, 'gfy2cb');
        $ZFp6$export$gfy2cb('album', 'md');
      } else if (e.ctrlKey && e.shiftKey && e.altKey) {
        $b7zt$var$prep(e, 'gfy2cb');
        $ZFp6$export$gfy2cb('album', 'iframe');
      }

      break;

    case 'KeyX':
      if (e.ctrlKey && e.shiftKey && !e.altKey) {
        $b7zt$var$prep(e, "quicktag");
        $PbQt$export$quicktag();
      } else if (e.ctrlKey && e.shiftKey && e.altKey) {
        $b7zt$var$prep(e, "deleteTags");
        $PbQt$export$deleteTags();
      }

      break;

    case 'KeyQ':
      if (e.ctrlKey && !e.shiftKey && !e.altKey) {
        $b7zt$var$prep(e, "gfy2cb");
        $ZFp6$export$gfy2cb('any', 'plain');
        break;
      } else if (e.ctrlKey && e.shiftKey && !e.altKey) {
        $b7zt$var$prep(e, "gfy2cb");
        $ZFp6$export$gfy2cb('any', 'plain+numbered');
        break;
      } else if (e.ctrlKey && e.shiftKey && e.altKey) {
        $b7zt$var$prep(e, "gfy2cb");
        $ZFp6$export$gfy2cb('any', 'plain+numbered+titles');
        break;
      }

    case 'KeyS':
      if (e.ctrlKey && e.shiftKey && !e.altKey) {
        $b7zt$var$prep(e, "gfy2cb");
        await $VtGo$export$paginate();
        break;
      }

  }
}

function $b7zt$var$prep(e, fname) {
  console.log("Executing function ".concat(fname, " for hotkey ").concat(e.code), e);
  e.preventDefault();
  e.stopImmediatePropagation();
}
})();