basic tweaks/fixes for inline search

This commit is contained in:
tophf 2017-12-10 04:03:04 +03:00
parent ce61112020
commit 4b207f3dd4
7 changed files with 325 additions and 343 deletions

View File

@ -1,3 +1,7 @@
.hidden {
display: none !important;
}
button { button {
-webkit-appearance: none; -webkit-appearance: none;
-moz-appearance: none; -moz-appearance: none;

View File

@ -19,6 +19,7 @@ var prefs = new function Prefs() {
'popup.enabledFirst': true, // display enabled styles before disabled styles 'popup.enabledFirst': true, // display enabled styles before disabled styles
'popup.stylesFirst': true, // display enabled styles before disabled styles 'popup.stylesFirst': true, // display enabled styles before disabled styles
'popup.borders': false, // add white borders on the sides 'popup.borders': false, // add white borders on the sides
'popup.findStylesInline': true, // use the inline style search
'manage.onlyEnabled': false, // display only enabled styles 'manage.onlyEnabled': false, // display only enabled styles
'manage.onlyLocal': false, // display only styles created locally 'manage.onlyLocal': false, // display only styles created locally

View File

@ -87,7 +87,7 @@
<div class="search-result"> <div class="search-result">
<a class="search-result-title"></a> <a class="search-result-title"></a>
<div class="search-result-info"> <div class="search-result-info">
<img class="search-result-screenshot" /> <img class="search-result-screenshot">
<div class="actions"> <div class="actions">
<button class="search-result-install" i18n-text="installButton"></button> <button class="search-result-install" i18n-text="installButton"></button>
<button class="search-result-uninstall hidden" i18n-text="deleteStyleLabel"></button> <button class="search-result-uninstall hidden" i18n-text="deleteStyleLabel"></button>
@ -96,28 +96,23 @@
i18n-title="configureStyleOnHomepage"></button> i18n-title="configureStyleOnHomepage"></button>
</div> </div>
<div class="search-result-overlay"> <div class="search-result-overlay">
<div class="search-result-author">
<label i18n-text="author"></label>:
<a class="search-result-author-link" target="_blank"></a>
</div>
<div class="search-result-description-group">
<div class="search-result-description"></div>
<div class="search-result-description-info">
<svg class="svg-icon info" viewBox="0 0 14 16">
<path fill-rule="evenodd" d="M6.3 5.69a.942.942 0 0 1-.28-.7c0-.28.09-.52.28-.7.19-.18.42-.28.7-.28.28 0 .52.09.7.28.18.19.28.42.28.7 0 .28-.09.52-.28.7a1 1 0 0 1-.7.3c-.28 0-.52-.11-.7-.3zM8 7.99c-.02-.25-.11-.48-.31-.69-.2-.19-.42-.3-.69-.31H6c-.27.02-.48.13-.69.31-.2.2-.3.44-.31.69h1v3c.02.27.11.5.31.69.2.2.42.31.69.31h1c.27 0 .48-.11.69-.31.2-.19.3-.42.31-.69H8V7.98v.01zM7 2.3c-3.14 0-5.7 2.54-5.7 5.68 0 3.14 2.56 5.7 5.7 5.7s5.7-2.55 5.7-5.7c0-3.15-2.56-5.69-5.7-5.69v.01zM7 .98c3.86 0 7 3.14 7 7s-3.14 7-7 7-7-3.12-7-7 3.14-7 7-7z"></path>
</svg>
</div>
</div>
<div class="search-result-meta"> <div class="search-result-meta">
<div class="search-result-author">
<span i18n-text="author"></span>
<a class="search-result-author-link" target="_blank"></a>
</div>
<div class="search-result-meta-rating"> <div class="search-result-meta-rating">
<span i18n-text="searchResultRating"></span>: <span i18n-text="searchResultRating"></span>
<span class="search-result-rating"></span> <span class="search-result-rating"></span>
</div> </div>
<div class="search-result-meta-install-count"> <div class="search-result-meta-install-count">
<span i18n-text="searchResultInstallCount"></span>: <span i18n-text="searchResultInstallCount"></span>
<span class="search-result-install-count"></span> <span class="search-result-install-count"></span>
</div> </div>
</div> </div>
<div class="search-result-description-group">
<div class="search-result-description"></div>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -184,7 +179,7 @@
<a id="find-styles-link" i18n-text="findStyles" i18n-title="findStylesTooltip"></a> <a id="find-styles-link" i18n-text="findStyles" i18n-title="findStylesTooltip"></a>
<span id="find-styles-inline-group"> <span id="find-styles-inline-group">
<label i18n-title="findStylesInlineTooltip"> <label i18n-title="findStylesInlineTooltip">
<input id="find-styles-inline" class="checker" type="checkbox" checked /> <input id="popup.findStylesInline" class="checker" type="checkbox">
<svg class="svg-icon checked" viewBox="0 0 1000 1000"> <svg class="svg-icon checked" viewBox="0 0 1000 1000">
<path fill-rule="evenodd" d="M983.2,184.3L853,69.8c-4-3.5-9.3-5.3-14.5-5c-5.3,0.4-10.3,2.8-13.8,6.8L352.3,609.2L184.4,386.9c-3.2-4.2-8-7-13.2-7.8c-5.3-0.8-10.6,0.6-14.9,3.9L18,487.5c-8.8,6.7-10.6,19.3-3.9,28.1L325,927.2c3.6,4.8,9.3,7.7,15.3,8c0.2,0,0.5,0,0.7,0c5.8,0,11.3-2.5,15.1-6.8L985,212.6C992.3,204.3,991.5,191.6,983.2,184.3z"/> <path fill-rule="evenodd" d="M983.2,184.3L853,69.8c-4-3.5-9.3-5.3-14.5-5c-5.3,0.4-10.3,2.8-13.8,6.8L352.3,609.2L184.4,386.9c-3.2-4.2-8-7-13.2-7.8c-5.3-0.8-10.6,0.6-14.9,3.9L18,487.5c-8.8,6.7-10.6,19.3-3.9,28.1L325,927.2c3.6,4.8,9.3,7.7,15.3,8c0.2,0,0.5,0,0.7,0c5.8,0,11.3-2.5,15.1-6.8L985,212.6C992.3,204.3,991.5,191.6,983.2,184.3z"/>
</svg> </svg>
@ -207,18 +202,18 @@
i18n-text="shortcuts" i18n-text="shortcuts"
i18n-title="shortcutsNote"></button> i18n-title="shortcutsNote"></button>
</div> </div>
</div>
<div id="search-results" class="hidden"> <div id="search-results" class="hidden">
<div id="search-results-list"></div> <div id="search-results-list"></div>
<div id="search-results-nav"> <div id="search-results-nav">
<button id="search-results-nav-prev" i18n-title="paginationPrevious" disabled>&#8592;</button> <button id="search-results-nav-prev" i18n-title="paginationPrevious" disabled>&#8592;</button>
<label> <label>
<span id="search-results-nav-current-page" i18n-title="paginationCurrent">-</span> <span id="search-results-nav-current-page" i18n-title="paginationCurrent">-</span>
/ /
<span id="search-results-nav-total-pages" i18n-title="paginationTotal">-</span> <span id="search-results-nav-total-pages" i18n-title="paginationTotal">-</span>
</label> </label>
<button id="search-results-nav-next" i18n-title="paginationNext" disabled>&#8594;</button> <button id="search-results-nav-next" i18n-title="paginationNext" disabled>&#8594;</button>
</div>
</div> </div>
</div> </div>
@ -238,6 +233,11 @@
<symbol id="svg-icon-config-uso" viewBox="0 0 14 14"> <symbol id="svg-icon-config-uso" viewBox="0 0 14 14">
<path d="M2,3h4v2H4v6h6V9h2v4H2V3z M8,1h6v6l-2.2-2.2l-4,4L6.2,7.2l4-4L8,1z"/> <path d="M2,3h4v2H4v6h6V9h2v4H2V3z M8,1h6v6l-2.2-2.2l-4,4L6.2,7.2l4-4L8,1z"/>
</symbol> </symbol>
<symbol id="svg-icon-help" viewBox="0 0 14 16">
<title i18n-text="helpAlt"></title>
<path fill-rule="evenodd" d="M6.3 5.69a.942.942 0 0 1-.28-.7c0-.28.09-.52.28-.7.19-.18.42-.28.7-.28.28 0 .52.09.7.28.18.19.28.42.28.7 0 .28-.09.52-.28.7a1 1 0 0 1-.7.3c-.28 0-.52-.11-.7-.3zM8 7.99c-.02-.25-.11-.48-.31-.69-.2-.19-.42-.3-.69-.31H6c-.27.02-.48.13-.69.31-.2.2-.3.44-.31.69h1v3c.02.27.11.5.31.69.2.2.42.31.69.31h1c.27 0 .48-.11.69-.31.2-.19.3-.42.31-.69H8V7.98v.01zM7 2.3c-3.14 0-5.7 2.54-5.7 5.68 0 3.14 2.56 5.7 5.7 5.7s5.7-2.55 5.7-5.7c0-3.15-2.56-5.69-5.7-5.69v.01zM7 .98c3.86 0 7 3.14 7 7s-3.14 7-7 7-7-3.12-7-7 3.14-7 7-7z"></path>
</symbol>
</svg> </svg>
</body> </body>

View File

@ -104,6 +104,11 @@ body > div:not(#installed):not(#message-box):not(.colorpicker-popup) {
font-style: italic; font-style: italic;
} }
#find-styles-link {
cursor: pointer;
margin-right: .5em;
}
.checker { .checker {
display: inline; display: inline;
} }

View File

@ -53,6 +53,7 @@ function onRuntimeMessage(msg) {
} }
break; break;
} }
dispatchEvent(new CustomEvent(msg.method, {detail: msg}));
} }
@ -195,6 +196,7 @@ function showStyles(styles) {
if (!styles.length) { if (!styles.length) {
installed.textContent = ''; installed.textContent = '';
installed.appendChild(template.noStyles.cloneNode(true)); installed.appendChild(template.noStyles.cloneNode(true));
window.dispatchEvent(new Event('showStyles:done'));
return; return;
} }

View File

@ -3,13 +3,8 @@ body.search-results-shown {
overflow-x: hidden; overflow-x: hidden;
} }
#disable-all-wrapper { #search-results {
border-bottom: solid 1px #000; position: relative;
margin-bottom: 5px;
}
.hidden {
display: none !important;
} }
#search-results-error { #search-results-error {
@ -27,19 +22,23 @@ body.search-results-shown {
.search-result, .search-result-empty { .search-result, .search-result-empty {
position: relative; position: relative;
min-height: 170px; padding: .75rem;
padding: 5px; min-height: 160px;
} }
.search-result-empty { .search-result {
position: relative; box-shadow: 1px 1px 10px rgba(0, 0, 0, .5);
border-radius: 3px;
border: 1px solid transparent;
margin-bottom: 1rem;
}
.search-result:hover {
border-color: #888;
} }
.search-result .lds-spinner, .search-result-empty .lds-spinner { .search-result .lds-spinner, .search-result-empty .lds-spinner {
opacity: 1; transform: scale(.75);
top: 0;
width: 150px;
height: 150px;
} }
.search-result-screenshot { .search-result-screenshot {
@ -49,114 +48,131 @@ body.search-results-shown {
} }
.search-result-title { .search-result-title {
padding: 3px;
font-size: 1.2em; font-size: 1.2em;
font-weight: 600; font-weight: 600;
margin-bottom: .5em;
display: block;
color: #666;
}
.search-result:hover .search-result-title {
color: initial;
} }
.search-result-info { .search-result-info {
position: relative; position: relative;
} }
.search-result-info > div { .search-result-info > div {
opacity: 0; opacity: 0;
position: absolute; position: absolute;
width: 100%; width: 100%;
transition: opacity linear 0.2s; transition: opacity .2s;
overflow: hidden;
text-align: center;
} }
.search-result-info:hover > div {
.search-result:hover .search-result-info > div {
opacity: 1; opacity: 1;
} }
.search-result-overlay { .search-result-overlay {
height: 55px; bottom: 0;
top: 85px;
background-color: rgba(255, 255, 255, 0.6);
} }
.search-result-info > .actions { .search-result-info > .actions {
top: 30px; bottom: 70px;
text-align: center;
} }
.search-result-info > .actions > button { .search-result-info > .actions > button {
background-color: #fff; background-color: #fff;
box-shadow: 2px 2px 20px #000;
white-space: nowrap;
} }
.search-result-info > .actions > button:hover { .search-result-info > .actions > button:hover {
background-color: #ccc; background-color: #ccc;
} }
.search-result-overlay > * { .search-result-overlay > * {
text-align: center; display: flex;
padding: .25rem .5rem;
} }
.search-result-overlay > * { .search-result-author {
margin: 2px 10px 0px 10px; max-width: 50%;
} }
.search-result-author-link { .search-result-author-link {
margin-left: 3px; color: inherit;
} font-weight: bold;
.search-result-description {
width: 90%;
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
display: inline-block;
}
.search-result-description.expanded {
width: 100%;
max-height: 100%;
white-space: pre-wrap;
overflow-x: auto;
overflow-y: hidden;
text-overflow: unset;
display: block; display: block;
} }
.search-result-description-info { .search-result-author-link:hover {
display: inline-block; color: #fff;
cursor: pointer; }
width: 16px;
height: 14px; .search-result-description-group {
background-color: rgba(255, 255, 255, 0.8);
align-items: center;
padding-right: .25rem;
}
.search-result-description {
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
} }
.search-result-meta { .search-result-meta {
display: table; background-color: hsla(180, 27%, 37%, 0.85);
width: 100%; color: hsl(180, 27%, 80%);
justify-content: space-between;
} }
.search-result-meta-rating, .search-result-meta-install-count { .search-result-meta > * > :first-child {
display: table-cell; display: block;
opacity: .75;
}
.search-result-meta-rating {
text-align: center; text-align: center;
} }
.search-result-meta-install-count {
text-align: right;
}
.search-result-rating { .search-result-rating {
font-weight: 600; font-weight: 600;
padding: 1px 2px 1px 2px; padding: 1px 2px 1px 2px;
color: #fff; color: #fff;
} }
.search-result-rating.good { .search-result-rating.good {
background-color: darkgreen; background-color: darkgreen;
} }
.search-result-rating.okay { .search-result-rating.okay {
background-color: darkorange; background-color: darkorange;
} }
.search-result-rating.bad { .search-result-rating.bad {
background-color: darkred; background-color: darkred;
} }
.search-result-rating.none { .search-result-rating.none {
background-color: #333;
} }
.search-result-install-count { .search-result-install-count {
font-weight: 600; font-weight: 600;
} }
.search-result-install, .search-result-install, .search-result-customize, .search-result-uninstall {
.search-result-customize,
.search-result-uninstall {
width: 40%; width: 40%;
margin: 3px; margin: 3px;
} }
@ -185,7 +201,6 @@ body.search-results-shown {
} }
/* spinner: https://github.com/loadingio/css-spinner */ /* spinner: https://github.com/loadingio/css-spinner */
.lds-spinner { .lds-spinner {
-webkit-user-select: none; -webkit-user-select: none;
-moz-user-select: none; -moz-user-select: none;
@ -193,117 +208,95 @@ body.search-results-shown {
user-select: none; user-select: none;
pointer-events: none; pointer-events: none;
opacity: 0; opacity: 0;
position: absolute;
top: 0;
left: 0;
right: 0;
width: 200px; /* don't change! use "transform: scale(.75)" */
height: 200px; /* don't change! use "transform: scale(.75)" */
margin: auto;
animation: fadein 1s;
} }
@keyframes lds-spinner { @keyframes lds-spinner {
0% { 0% {
opacity: 1; opacity: .5;
} }
100% { 100% {
opacity: 0; opacity: 0;
} }
} }
@-webkit-keyframes lds-spinner {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.lds-spinner {
position: absolute;
width: 200px;
height: 200px;
top: 100px;
left: 0;
right: 0;
margin: auto;
opacity: .2;
transition: opacity .5s;
}
.lds-spinner div { .lds-spinner div {
left: 94px; left: 94px;
top: 23px; top: 23px;
position: absolute; position: absolute;
-webkit-animation: lds-spinner linear 1s infinite;
animation: lds-spinner linear 1s infinite; animation: lds-spinner linear 1s infinite;
animation-direction: reverse;
background: currentColor; background: currentColor;
width: 12px; width: 12px;
height: 34px; height: 34px;
border-radius: 20%; border-radius: 20%;
-webkit-transform-origin: 6px 77px;
transform-origin: 6px 77px; transform-origin: 6px 77px;
} }
.lds-spinner div:nth-child(1) { .lds-spinner div:nth-child(1) {
-webkit-transform: rotate(0deg);
transform: rotate(0deg); transform: rotate(0deg);
-webkit-animation-delay: -0.916666666666667s;
animation-delay: -0.916666666666667s; animation-delay: -0.916666666666667s;
} }
.lds-spinner div:nth-child(2) { .lds-spinner div:nth-child(2) {
-webkit-transform: rotate(30deg);
transform: rotate(30deg); transform: rotate(30deg);
-webkit-animation-delay: -0.833333333333333s;
animation-delay: -0.833333333333333s; animation-delay: -0.833333333333333s;
} }
.lds-spinner div:nth-child(3) { .lds-spinner div:nth-child(3) {
-webkit-transform: rotate(60deg);
transform: rotate(60deg); transform: rotate(60deg);
-webkit-animation-delay: -0.75s;
animation-delay: -0.75s; animation-delay: -0.75s;
} }
.lds-spinner div:nth-child(4) { .lds-spinner div:nth-child(4) {
-webkit-transform: rotate(90deg);
transform: rotate(90deg); transform: rotate(90deg);
-webkit-animation-delay: -0.666666666666667s;
animation-delay: -0.666666666666667s; animation-delay: -0.666666666666667s;
} }
.lds-spinner div:nth-child(5) { .lds-spinner div:nth-child(5) {
-webkit-transform: rotate(120deg);
transform: rotate(120deg); transform: rotate(120deg);
-webkit-animation-delay: -0.583333333333333s;
animation-delay: -0.583333333333333s; animation-delay: -0.583333333333333s;
} }
.lds-spinner div:nth-child(6) { .lds-spinner div:nth-child(6) {
-webkit-transform: rotate(150deg);
transform: rotate(150deg); transform: rotate(150deg);
-webkit-animation-delay: -0.5s;
animation-delay: -0.5s; animation-delay: -0.5s;
} }
.lds-spinner div:nth-child(7) { .lds-spinner div:nth-child(7) {
-webkit-transform: rotate(180deg);
transform: rotate(180deg); transform: rotate(180deg);
-webkit-animation-delay: -0.416666666666667s;
animation-delay: -0.416666666666667s; animation-delay: -0.416666666666667s;
} }
.lds-spinner div:nth-child(8) { .lds-spinner div:nth-child(8) {
-webkit-transform: rotate(210deg);
transform: rotate(210deg); transform: rotate(210deg);
-webkit-animation-delay: -0.333333333333333s;
animation-delay: -0.333333333333333s; animation-delay: -0.333333333333333s;
} }
.lds-spinner div:nth-child(9) { .lds-spinner div:nth-child(9) {
-webkit-transform: rotate(240deg);
transform: rotate(240deg); transform: rotate(240deg);
-webkit-animation-delay: -0.25s;
animation-delay: -0.25s; animation-delay: -0.25s;
} }
.lds-spinner div:nth-child(10) { .lds-spinner div:nth-child(10) {
-webkit-transform: rotate(270deg);
transform: rotate(270deg); transform: rotate(270deg);
-webkit-animation-delay: -0.166666666666667s;
animation-delay: -0.166666666666667s; animation-delay: -0.166666666666667s;
} }
.lds-spinner div:nth-child(11) { .lds-spinner div:nth-child(11) {
-webkit-transform: rotate(300deg);
transform: rotate(300deg); transform: rotate(300deg);
-webkit-animation-delay: -0.083333333333333s;
animation-delay: -0.083333333333333s; animation-delay: -0.083333333333333s;
} }
.lds-spinner div:nth-child(12) { .lds-spinner div:nth-child(12) {
-webkit-transform: rotate(330deg);
transform: rotate(330deg); transform: rotate(330deg);
-webkit-animation-delay: 0s;
animation-delay: 0s; animation-delay: 0s;
} }

View File

@ -1,31 +1,30 @@
/* global handleEvent tryJSONparse getStylesSafe BG */ /* global tabURL handleEvent */
'use strict'; 'use strict';
(() => { window.addEventListener('showStyles:done', function _() {
Promise.all([getActiveTab(), onDOMready()]) window.removeEventListener('showStyles:done', _);
.then(([tab]) => {
$('#find-styles-link').href = searchUserstyles().getSearchPageURL(tab.url);
$('#find-styles-link').onclick = event => { if (!tabURL) {
// Only load search results inline if option is selected. return;
if ($('#find-styles-inline').checked) { }
// Hide 'inline' checkbox.
$('#find-styles-inline-group').classList.add('hidden');
$('#find-styles-inline').checked = false;
const searchResults = searchResultsController(); Object.assign($('#find-styles-link'), {
searchResults.init(); href: searchUserstyles().getSearchPageURL(tabURL),
searchResults.load(); onclick(event) {
if (!prefs.get('popup.findStylesInline')) {
handleEvent.openURLandHide.call(this, event);
return;
}
// Avoid propagating click to anchor/href $('#find-styles-inline-group').classList.add('hidden');
event.preventDefault();
return false; const searchResults = searchResultsController();
} else { searchResults.init();
// Open anchor href in new tab. searchResults.load();
handleEvent.openURLandHide.call($('#find-styles-link'), event);
} event.preventDefault();
}; },
}); });
/** /**
* Represents the search results within the Stylus popup. * Represents the search results within the Stylus popup.
@ -40,6 +39,10 @@
const processedResults = []; // Search results that are not installed and apply ot the page (includes 'json' field with full style). const processedResults = []; // Search results that are not installed and apply ot the page (includes 'json' field with full style).
const BLANK_PIXEL_DATA = 'data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAA' + const BLANK_PIXEL_DATA = 'data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAA' +
'C1HAwCAAAAC0lEQVR42mOcXQ8AAbsBHLLDr5MAAAAASUVORK5CYII='; 'C1HAwCAAAAC0lEQVR42mOcXQ8AAbsBHLLDr5MAAAAASUVORK5CYII=';
const UPDATE_URL = 'https://update.userstyles.org/%.md5';
const ENTRY_ID_PREFIX = 'search-result-';
let scrollToFirstResult = true;
let loading = false; let loading = false;
let category; // Category for the active tab's URL. let category; // Category for the active tab's URL.
let currentDisplayedPage = 1; // Current page number in popup.html let currentDisplayedPage = 1; // Current page number in popup.html
@ -50,7 +53,14 @@
$('#search-results-nav-prev').onclick = prev; $('#search-results-nav-prev').onclick = prev;
$('#search-results-nav-next').onclick = next; $('#search-results-nav-next').onclick = next;
document.body.classList.add('search-results-shown'); document.body.classList.add('search-results-shown');
window.scrollTo(0, 0); addEventListener('styleDeleted', ({detail}) => {
const entries = [...$('#search-results-list').children];
const entry = entries.find(el => el._result.installedStyleId === detail.id);
if (entry) {
entry._result.installed = false;
renderActionButtons(entry);
}
});
} }
/** /**
@ -64,28 +74,41 @@
render(); // Refresh elements that depend on `loading` state. render(); // Refresh elements that depend on `loading` state.
if (isLoading) { if (isLoading) {
// Show spinner showSpinner('#search-results');
$('#search-results').appendChild(
$create(
'.lds-spinner',
new Array(12).fill($create('div')).map(e => e.cloneNode()))
);
} else { } else {
// Hide spinner
$.remove('#search-results > .lds-spinner'); $.remove('#search-results > .lds-spinner');
} }
} }
} }
function render() { function showSpinner(parent) {
$('#search-results-list').textContent = ''; // Clear search results parent = parent instanceof Node ? parent : $(parent);
parent.appendChild($create('.lds-spinner',
new Array(12).fill($create('div')).map(e => e.cloneNode())));
}
const startIndex = (currentDisplayedPage - 1) * DISPLAYED_RESULTS_PER_PAGE; function render() {
let startIndex = (currentDisplayedPage - 1) * DISPLAYED_RESULTS_PER_PAGE;
const endIndex = currentDisplayedPage * DISPLAYED_RESULTS_PER_PAGE; const endIndex = currentDisplayedPage * DISPLAYED_RESULTS_PER_PAGE;
const list = $('#search-results-list');
// keep rendered elements with ids in the range of interest
for (let i = 0; i < DISPLAYED_RESULTS_PER_PAGE;) {
const el = list.children[i];
if (!el) {
break;
}
if (el.id === 'search-result-' + (processedResults[startIndex] || {}).id) {
startIndex++;
i++;
} else {
el.remove();
}
}
const displayedResults = processedResults.slice(startIndex, endIndex); const displayedResults = processedResults.slice(startIndex, endIndex);
displayedResults.forEach(resultToDisplay => { displayedResults.forEach(createSearchResultNode);
createSearchResultNode(resultToDisplay);
});
$('#search-results-nav-prev').disabled = (currentDisplayedPage <= 1 || loading); $('#search-results-nav-prev').disabled = (currentDisplayedPage <= 1 || loading);
$('#search-results-nav-current-page').textContent = currentDisplayedPage; $('#search-results-nav-current-page').textContent = currentDisplayedPage;
@ -103,8 +126,15 @@
const maxResults = currentDisplayedPage < totalPageCount const maxResults = currentDisplayedPage < totalPageCount
? DISPLAYED_RESULTS_PER_PAGE ? DISPLAYED_RESULTS_PER_PAGE
: displayedResults.length + unprocessedResults.length; : displayedResults.length + unprocessedResults.length;
for (let i = displayedResults.length; i < maxResults; i++) { for (let i = list.children.length; i < maxResults; i++) {
createLoadingSearchResultNode(); const entry = template.emptySearchResult.cloneNode(true);
list.appendChild(entry);
showSpinner(entry);
}
if (scrollToFirstResult && list.children[0]) {
scrollToFirstResult = false;
list.children[0].scrollIntoView({behavior: 'smooth', block: 'start'});
} }
} }
@ -124,15 +154,15 @@
/** Increments currentDisplayedPage and loads results. */ /** Increments currentDisplayedPage and loads results. */
function next() { function next() {
currentDisplayedPage += 1; currentDisplayedPage += 1;
scrollToFirstResult = true;
render(); render();
window.scrollTo(0, 0);
loadMoreIfNeeded(); loadMoreIfNeeded();
} }
/** Decrements currentPage and loads results. */ /** Decrements currentPage and loads results. */
function prev() { function prev() {
currentDisplayedPage = Math.max(1, currentDisplayedPage - 1); currentDisplayedPage = Math.max(1, currentDisplayedPage - 1);
window.scrollTo(0, 0); scrollToFirstResult = true;
render(); render();
} }
@ -172,20 +202,18 @@
$('#search-results').classList.remove('hidden'); $('#search-results').classList.remove('hidden');
$('#search-results-error').classList.add('hidden'); $('#search-results-error').classList.add('hidden');
// Discover current tab's URL & the "category" for the URL, then search. // Discover "category" for the URL, then search.
getActiveTab().then(tab => { category = searchAPI.getCategory(tabURL);
category = searchAPI.getCategory(tab.url); searchAPI.search(category)
searchAPI.search(category) .then(searchResults => {
.then(searchResults => { setLoading(false);
setLoading(false); if (searchResults.data.length === 0) {
if (searchResults.data.length === 0) { throw 404;
throw 404; }
} unprocessedResults.push.apply(unprocessedResults, searchResults.data);
unprocessedResults.push.apply(unprocessedResults, searchResults.data); processNextResult();
processNextResult(); })
}) .catch(error);
.catch(error);
});
} }
} }
@ -208,72 +236,38 @@
// Process the next result in the queue. // Process the next result in the queue.
const nextResult = unprocessedResults.shift(); const nextResult = unprocessedResults.shift();
isStyleInstalled(nextResult) getStylesSafe({md5Url: UPDATE_URL.replace('%', nextResult.id)})
.then(isInstalled => { .then(([installedStyle]) => {
if (isInstalled) { if (installedStyle) {
// Style already installed, skip it. setTimeout(processNextResult);
setTimeout(processNextResult, 0); // Keep processing return;
} else if (nextResult.category !== 'site') {
// Style is not for a website, skip it.
setTimeout(processNextResult, 0); // Keep processing
} else {
// Style not installed.
searchAPI.fetchStyle(nextResult.id) // for "style_settings" (customizations)
.then(userstyleObject => {
// Store style settings for detecting customization later.
nextResult.style_settings = userstyleObject.style_settings;
processedResults.push(nextResult);
render();
setTimeout(processNextResult, DELAY_AFTER_FETCHING_STYLES); // Keep processing
})
.catch(reason => {
console.log('processNextResult(', nextResult.id, ') => [ERROR]: ', reason);
setTimeout(processNextResult, DELAY_AFTER_FETCHING_STYLES); // Keep processing
});
} }
if (nextResult.category !== 'site') {
setTimeout(processNextResult);
return;
}
// Style not installed.
// Get "style_settings" (customizations)
searchAPI.fetchStyle(nextResult.id)
.then(userstyleObject => {
// Store style settings for detecting customization later.
nextResult.style_settings = userstyleObject.style_settings;
processedResults.push(nextResult);
render();
setTimeout(processNextResult, DELAY_AFTER_FETCHING_STYLES);
})
.catch(reason => {
console.log('processNextResult(', nextResult.id, ') => [ERROR]: ', reason);
setTimeout(processNextResult, DELAY_AFTER_FETCHING_STYLES);
});
}); });
} }
/**
* Promises if the given searchResult matches an already-installed style.
* @param {Object} userstyleSearchResult Search result object from userstyles.org
* @returns {Promise<boolean>} Resolves if the style is installed.
*/
function isStyleInstalled(userstyleSearchResult) {
return new Promise(function (resolve, reject) {
getStylesSafe()
.then(installedStyles => {
const matchingStyles = installedStyles.filter(installedStyle => {
// Compare installed name to search result name.
let isMatch = installedStyle.name === userstyleSearchResult.name;
// Compare if search result ID (userstyles ID) is mentioned in the installed updateUrl.
if (installedStyle.updateUrl) {
isMatch &= installedStyle.updateUrl.includes('/' + userstyleSearchResult.id + '.json');
}
return isMatch;
});
resolve(matchingStyles.length > 0);
})
.catch(reject);
});
}
function createLoadingSearchResultNode() {
const entry = template.emptySearchResult.cloneNode(true);
entry.appendChild(
$create(
'.lds-spinner',
new Array(12).fill($create('div')).map(e => e.cloneNode()))
);
$('#search-results-list').appendChild(entry);
}
/** /**
* Constructs and adds the given search result to the popup's Search Results container. * Constructs and adds the given search result to the popup's Search Results container.
* @param {Object} userstyleSearchResult The SearchResult object from userstyles.org * @param {Object} result The SearchResult object from userstyles.org
*/ */
function createSearchResultNode(userstyleSearchResult) { function createSearchResultNode(result) {
/* /*
userstyleSearchResult format: { userstyleSearchResult format: {
id: 100835, id: 100835,
@ -290,60 +284,46 @@
const entry = template.searchResult.cloneNode(true); const entry = template.searchResult.cloneNode(true);
Object.assign(entry, { Object.assign(entry, {
id: 'search-result-' + userstyleSearchResult.id, _result: result,
onclick: handleEvent.openURLandHide id: ENTRY_ID_PREFIX + result.id,
}); });
$('#search-results-list').appendChild(entry);
const searchResultName = userstyleSearchResult.name; Object.assign($('.search-result-title', entry), {
const title = $('.search-result-title', entry); textContent: result.name,
Object.assign(title, {
textContent: searchResultName,
onclick: handleEvent.openURLandHide, onclick: handleEvent.openURLandHide,
href: searchAPI.BASE_URL + userstyleSearchResult.url href: searchAPI.BASE_URL + result.url
}); });
const screenshot = $('.search-result-screenshot', entry); const screenshot = $('.search-result-screenshot', entry);
let screenshotUrl = userstyleSearchResult.screenshot_url; let screenshotUrl = result.screenshot_url;
if (screenshotUrl === null) { if (screenshotUrl === null) {
screenshotUrl = BLANK_PIXEL_DATA; screenshotUrl = BLANK_PIXEL_DATA;
screenshot.classList.add('no-screenshot'); screenshot.classList.add('no-screenshot');
} else if (RegExp(/^[0-9]*_after.(jpe?g|png|gif)$/i).test(screenshotUrl)) { } else if (RegExp(/^[0-9]*_after.(jpe?g|png|gif)$/i).test(screenshotUrl)) {
screenshotUrl = searchAPI.BASE_URL + '/style_screenshot_thumbnails/' + screenshotUrl; screenshotUrl = searchAPI.BASE_URL + '/style_screenshot_thumbnails/' + screenshotUrl;
} }
Object.assign(screenshot, { screenshot.src = screenshotUrl;
src: screenshotUrl
const description = result.description
.replace(/<.*?>/g, '')
.replace(/[\r\n]{3,}/g, '\n\n');
Object.assign($('.search-result-description', entry), {
textContent: description,
title: description,
}); });
const searchResultOverlay = $('.search-result-overlay', entry); Object.assign($('.search-result-author-link', entry), {
textContent: result.user.name,
const description = $('.search-result-description', entry); title: result.user.name,
Object.assign(description, { href: searchAPI.BASE_URL + '/users/' + result.user.id,
textContent: userstyleSearchResult.description.replace(/<.*?>/g, '').replace(/(\r\n?)\r\n?/g, '$1') onclick(event) {
});
const descriptionExpand = $('.search-result-description-info', entry);
Object.assign(descriptionExpand, {
onclick: e => {
e.stopPropagation();
descriptionExpand.classList.add('hidden');
description.classList.add('expanded');
}
});
const authorLink = $('.search-result-author-link', entry);
Object.assign(authorLink, {
textContent: userstyleSearchResult.user.name,
title: userstyleSearchResult.user.name,
href: searchAPI.BASE_URL + '/users/' + userstyleSearchResult.user.id,
onclick: event => {
event.stopPropagation(); event.stopPropagation();
handleEvent.openURLandHide.call(authorLink, event); handleEvent.openURLandHide.call(this, event);
} }
}); });
const rating = $('.search-result-rating', entry);
let ratingClass; let ratingClass;
let ratingValue = userstyleSearchResult.rating; let ratingValue = result.rating;
if (ratingValue === null) { if (ratingValue === null) {
ratingClass = 'none'; ratingClass = 'none';
ratingValue = 'n/a'; ratingValue = 'n/a';
@ -357,99 +337,96 @@
ratingClass = 'bad'; ratingClass = 'bad';
ratingValue = ratingValue.toFixed(1); ratingValue = ratingValue.toFixed(1);
} }
Object.assign(rating, { Object.assign($('.search-result-rating', entry), {
textContent: ratingValue, textContent: ratingValue,
className: 'search-result-rating ' + ratingClass className: 'search-result-rating ' + ratingClass
}); });
const installCount = $('.search-result-install-count', entry); Object.assign($('.search-result-install-count', entry), {
Object.assign(installCount, { textContent: result.total_install_count.toLocaleString()
textContent: userstyleSearchResult.total_install_count.toLocaleString()
}); });
renderActionButtons(entry);
$('#search-results-list').appendChild(entry);
return entry;
}
function renderActionButtons(entry) {
const uninstallButton = $('.search-result-uninstall', entry); const uninstallButton = $('.search-result-uninstall', entry);
uninstallButton.onclick = uninstall; uninstallButton.onclick = onUninstallClicked;
const installButton = $('.search-result-install', entry); const installButton = $('.search-result-install', entry);
installButton.onclick = install; installButton.onclick = onInstallClicked;
if (userstyleSearchResult.style_settings.length > 0) { const result = entry._result;
if (result.style_settings.length > 0) {
// Style has customizations // Style has customizations
installButton.classList.add('customize'); installButton.classList.add('customize');
uninstallButton.classList.add('customize'); uninstallButton.classList.add('customize');
const customizeButton = $('.search-result-customize', entry); const customizeButton = $('.search-result-customize', entry);
customizeButton.dataset.href = searchAPI.BASE_URL + userstyleSearchResult.url; customizeButton.dataset.href = searchAPI.BASE_URL + result.url;
customizeButton.classList.remove('hidden'); customizeButton.classList.remove('hidden');
customizeButton.onclick = event => { customizeButton.onclick = function (event) {
event.stopPropagation(); event.stopPropagation();
handleEvent.openURLandHide.call(customizeButton, event); handleEvent.openURLandHide.call(this, event);
}; };
} }
if (userstyleSearchResult.installed) { installButton.classList.toggle('hidden', Boolean(result.installed));
screenshot.onclick = uninstall; uninstallButton.classList.toggle('hidden', !result.installed);
searchResultOverlay.onclick = uninstall; }
installButton.classList.add('hidden');
uninstallButton.classList.remove('hidden');
} else {
screenshot.onclick = install;
searchResultOverlay.onclick = install;
}
/** Uninstalls the current userstyleSearchResult from Stylus. */ function onUninstallClicked(event) {
function uninstall(event) { event.stopPropagation();
event.stopPropagation(); const entry = this.closest('.search-result');
deleteStyleSafe({id: userstyleSearchResult.installedStyleId}) const result = entry._result;
.then(() => { deleteStyleSafe({id: result.installedStyleId})
userstyleSearchResult.installed = false; .then(() => {
render(); entry._result.installed = false;
}); renderActionButtons(entry);
} });
}
/** Installs the current userstyleSearchResult into Stylus. */ /** Installs the current userstyleSearchResult into Stylus. */
function install(event) { function onInstallClicked(event) {
if (event) { event.stopPropagation();
event.stopPropagation();
}
// Spinner while installing const entry = this.closest('.search-result');
entry.appendChild( const result = entry._result;
$create( const installButton = $('.search-result-install', entry);
'.lds-spinner',
new Array(12).fill($create('div')).map(e => e.cloneNode()))
);
installButton.disabled = true;
// Fetch .JSON style showSpinner(entry);
searchAPI.fetchStyleJson(userstyleSearchResult) installButton.disabled = true;
.then(userstyleJson => {
// Install style
saveStyleSafe(userstyleJson)
.then(savedStyle => {
// Success: Store installed styleId, mark as installed.
userstyleSearchResult.installed = true;
userstyleSearchResult.installedStyleId = savedStyle.id;
render(); // Hides install button, shows uninstall button.
$.remove('.lds-spinner', entry); // Fetch .JSON style
installButton.disabled = false; searchAPI.fetchStyleJson(result)
}); .then(userstyleJson => {
}) // Install style
.catch(reason => { saveStyleSafe(userstyleJson)
const usoId = userstyleSearchResult.id; .then(savedStyle => {
console.log('install:saveStyleSafe(usoID:', usoId, ') => [ERROR]: ', reason); // Success: Store installed styleId, mark as installed.
alert('Error while downloading usoID:' + usoId + '\nReason: ' + reason); result.installed = true;
result.installedStyleId = savedStyle.id;
renderActionButtons(entry);
$.remove('.lds-spinner', entry); $.remove('.lds-spinner', entry);
installButton.disabled = false; installButton.disabled = false;
}); });
return true; })
} .catch(reason => {
const usoId = result.id;
console.log('install:saveStyleSafe(usoID:', usoId, ') => [ERROR]: ', reason);
alert('Error while downloading usoID:' + usoId + '\nReason: ' + reason);
$.remove('.lds-spinner', entry);
installButton.disabled = false;
});
return true;
}
} // End of createSearchResultNode
} // End of searchResultsController } // End of searchResultsController
})(); });
/** /**
* Library for interacting with userstyles.org * Library for interacting with userstyles.org