Advertisement
Inquisitor

Shimmie/Equibooru personal tag filter

Aug 28th, 2018
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // -- Required: Makaba.SyntaxSugar.js
  2. // window.onload = function()
  3. function TS() {
  4.     // Добавляем ссылку для отображения\скрытия GUI
  5.  
  6.     var Navigation = $id('Navigationleft');
  7.     var TS_NavBlock = $new('div', {'class': 'blockbody'});
  8.     var TS_NavBlockLink  = $new('a', {
  9.         'class': 'noselect',
  10.         'style': 'font-size: 1.2em; font-weight: bold; font-family: Verdana; text-decoration: none;',
  11.         'id': 'ts_togglelink"',
  12.         'text': 'TAG FILTER'
  13.     });
  14.     var TS_NavBlockDescription = $new('small', {'text': '(allows to hide unwanted content)'});
  15.     TS_NavBlock.appendChild(TS_NavBlockLink);
  16.     TS_NavBlock.appendChild($new('br'));
  17.     TS_NavBlock.appendChild(TS_NavBlockDescription);
  18.     Navigation.appendChild(TS_NavBlock);
  19.  
  20.     // Создаём интерфейс управления фильтром
  21.     // Контейнер
  22.     var TS_GUI = $new('div', {'id': 'tagfilter', 'style': 'display:none'});
  23.     // Кнопка - Отмена
  24.     var TS_GUI_Toggle = $new('button', {'id': 'ts_togglebutton', 'class': 'noselect', 'text': 'Cancel'});
  25.     TS_GUI.appendChild(TS_GUI_Toggle);
  26.     // Кнопка - Сохранить настройки
  27.     var TS_GUI_Apply = $new('button', {'id': 'ts_apply', 'class': 'noselect', 'text': 'Apply'});
  28.     TS_GUI.appendChild(TS_GUI_Apply);
  29.     // Режим NSFW
  30.     var TS_GUI_NSFW = $new('input', {'type': 'checkbox', 'id': 'ts_nsfw'});
  31.     TS_GUI_NSFW.checked = false;
  32.     var TS_GUI_NSFW_Label = $new('label', {'for': 'ts_nsfw'});
  33.     TS_GUI_NSFW_Label.appendChild(TS_GUI_NSFW);
  34.     TS_GUI_NSFW_Label.appendChild(document.createTextNode("spoiler all tags (NSFW Mode, Alt+S)"));
  35.     TS_GUI.appendChild(TS_GUI_NSFW_Label);
  36.     // Описание
  37.     var TS_GUI_Info = $new('div', {'id': 'ts_info', 'text': 'Spoilered tag list:'});
  38.     var TS_GUI_Info_Additional = $new('small', {'text': 'separated with comma and space, example: "tag1, tag2, tag3"'});
  39.     TS_GUI_Info.appendChild($new('br'));
  40.     TS_GUI_Info.appendChild(TS_GUI_Info_Additional);
  41.     TS_GUI.appendChild(TS_GUI_Info);
  42.     // Сообщение о недоступности localstorage
  43.     if(lsTest() === false){
  44.         var TS_LocalStorageWarn = document.createElement("span");
  45.         TS_LocalStorageWarn.id = "ts_warning";
  46.         TS_LocalStorageWarn.textContent = "Warning! Seems your browser do not support HTML5 LocalStorage.";
  47.         TS_GUI.className += " warnmessage";
  48.         TS_GUI.appendChild(TS_LocalStorageWarn);
  49.     }
  50.     // Редактор
  51.     var TS_GUI_Tags = $new('textarea',
  52.     {
  53.         'id': 'ts_tags',
  54.         'autocomplete': 'off',
  55.         'autocorrect': 'off',
  56.         'autocapitalize': 'off',
  57.         'spellcheck': 'false'
  58.     });
  59.     TS_GUI.appendChild(TS_GUI_Tags);
  60.     // Добавляем GUI к странице
  61.     document.body.appendChild(TS_GUI);
  62.  
  63.     // Добавляем svg-фильтр
  64.     var NS = "http://www.w3.org/2000/svg",
  65.         svg = document.createElementNS(NS, "svg"),
  66.         filter = document.createElementNS(NS, "filter"),
  67.         blur = document.createElementNS(NS, "feGaussianBlur");
  68.  
  69.     filter.setAttribute("id", "blur");
  70.     blur.setAttribute("stdDeviation", "12");
  71.     filter.appendChild(blur);
  72.     svg.appendChild(filter);
  73.     document.body.appendChild(svg);
  74.  
  75.     // Логика переключения видимости
  76.     function ToggleTagFilter() {
  77.         $disp(TS_GUI);
  78.         TS_GUI_Tags.focus();
  79.     };
  80.  
  81.     TS_NavBlockLink.onclick = function() { ToggleTagFilter(); };
  82.     TS_GUI_Toggle.onclick = function() { TS_GUI.style.display = "none"; };
  83.  
  84.     // Сохранение настроек в LocalStorage
  85.     function SaveTagFilter() {
  86.         var Tags =  TS_GUI_Tags.value.split(/[ ,\n]+/);
  87.         localStorage.setItem("TagFilter", JSON.stringify(Tags));
  88.         var NSFWMode = TS_GUI_NSFW.checked ? "enabled" : "disabled";
  89.         localStorage.setItem("NSFWMode", NSFWMode);
  90.         LoadTagFilter();
  91.     };
  92.     // Загрузка настроек из LocalStorage
  93.     function LoadTagFilter() {
  94.         var Tags = localStorage.getItem("TagFilter");
  95.         TS_GUI_Tags.value = JSON.parse(Tags);
  96.         TS_GUI_Tags.value = TS_GUI_Tags.value.replace(/,/g , ", ");
  97.         if (localStorage.getItem("NSFWMode") == "enabled") TS_GUI_NSFW.checked = true;
  98.         ApplySpoilers();
  99.     }
  100.    
  101.     // Применяем спойлеры
  102.     function ApplySpoilers() {
  103.         // Размываем изображение на странице просмотра
  104.         var image = $id('main_image');
  105.         if ((image) && (localStorage.getItem("NSFWMode") == "enabled")) {
  106.             var tags_header =  document.querySelectorAll("body > header > h1")[0];
  107.             tags_header.style.setProperty("filter","url(#blur)","");
  108.             tags_header.classList.add("blurred");
  109.             image.style.setProperty("filter","url(#blur)","");
  110.             image.classList.add("blurred");
  111.             // Снимаем размытие, если видео запущено
  112.             image.onplaying = function() { image.style.setProperty("filter","none",""); }
  113.         }
  114.         // Приводим к нижнему регистру, чтобы получить регистронезависимое скрытие
  115.         var HiddenTags = JSON.parse(
  116.             localStorage.getItem("TagFilter")).map(function (val) {
  117.                 return val.toLowerCase();
  118.             }
  119.         );
  120.         var Thumbs = document.getElementsByClassName("shm-thumb");
  121.         // Проходим по массиву превьюшек
  122.         var index;
  123.         for (index = Thumbs.length - 1; index >= 0; --index) {
  124.                 var DataTags = Thumbs[index].dataset.tags.split(" ").map(function (val) {
  125.                 return val.toLowerCase();
  126.             });
  127.             var SpoilerTags = _.intersection(DataTags, HiddenTags);
  128.             // Если включен режим NSFW, спойлерим все картинки
  129.             if (localStorage.getItem("NSFWMode") == "enabled") {
  130.                 SpoilerTags = new Array("NSFW Mode");
  131.             }
  132.             // Если массив с разницей между тэгами и заспойлеренными тэгами не пуст
  133.             // добавляем классы и инфу о скрытых тэгах
  134.             if (SpoilerTags[0] != null) {
  135.                 var TS_Tags = document.createElement("span");
  136.                 TS_Tags.setAttribute("class", "ts_spoiler_desc");
  137.                 TS_Tags.textContent = SpoilerTags;
  138.                 TS_Tags.textContent = TS_Tags.textContent.replace(/,/g , ", ");
  139.                 var TS_Spoiler = document.createElement("span");
  140.                 TS_Spoiler.setAttribute("class", "ts_spoiler");
  141.                 TS_Spoiler.textContent = "Spoiler";
  142.                 Thumbs[index].appendChild(TS_Tags);
  143.                 Thumbs[index].appendChild(TS_Spoiler);
  144.                 Thumbs[index].className += " spoilered";
  145.             }
  146.         }
  147.     };
  148.  
  149.     // Убираем старые спойлеры при применении конфига
  150.     function RemoveOldSpoilers() {
  151.         // Удаляем элементы
  152.         var ForDeletion = document.querySelectorAll('.ts_spoiler,.ts_spoiler_desc');
  153.         var index;
  154.         for (index = ForDeletion.length - 1; index >= 0; --index) {
  155.                 ForDeletion[index].parentNode.removeChild(ForDeletion[index]);
  156.         };
  157.         // Убираем класс
  158.         var SpoileredImages = document.getElementsByClassName("spoilered");
  159.         var index;
  160.         for (index = SpoileredImages.length - 1; index >= 0; --index) {
  161.                 SpoileredImages[index].classList.remove("spoilered");
  162.         };
  163.         var BlurredElements = document.getElementsByClassName("blurred");
  164.         var index;
  165.         for (index = BlurredElements.length - 1; index >= 0; --index) {
  166.                 BlurredElements[index].style.setProperty("filter","none","");
  167.             BlurredElements[index].classList.remove("blurred");
  168.         };
  169.     };
  170.  
  171.     // Обработчик формы
  172.     TS_GUI_Apply.onclick = function() {
  173.         RemoveOldSpoilers();
  174.         SaveTagFilter();
  175.         TS_GUI.style.display = "none";
  176.         $alert('Tag filter activated');
  177.         //location.reload();
  178.     };
  179.  
  180.     // Применяем спойлеры после загрузки страницы
  181.     LoadTagFilter();
  182.     window.TagFilterActive = true;
  183. }
  184.  
  185. document.addEventListener("DOMContentLoaded", TS);
  186.  
  187. $(document).keyup(function(evt) { // Хоткей для переключения NSFW, ёбаный стыд что по эмуляции клика, но делалось на коленке за минуту
  188.     if (evt.keyCode==83 && (evt.altKey)){ // Alt+S
  189.         document.getElementById("ts_nsfw").click();
  190.         document.getElementById("ts_apply").click();
  191.         $alert('NSFW mode changed');
  192.     }
  193. });
  194.  
  195. function lsTest(){
  196.     var test = 'test';
  197.     try {
  198.         localStorage.setItem(test, test);
  199.         localStorage.removeItem(test);
  200.         return true;
  201.     } catch(e) {
  202.         return false;
  203.     }
  204. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement