Detects Customization. Prefetches "category" when popup is loaded.

* Fetches 'category' for the current URL when popup is first loaded.
* Customizable styles have "Customize" button next to "Install"
* "Customize" button opens a new tab to the style page.
* Removed all console.log() statements (except when `catch()`ing errors).
This commit is contained in:
derv82 2017-12-02 23:12:27 -08:00
parent 4c5b858f08
commit 8ae669bd12
4 changed files with 123 additions and 81 deletions

View File

@ -373,6 +373,14 @@
"message": "Install this search result",
"description": "Tooltip for a button that installs a search result"
},
"searchResultCustomize": {
"message": "Customize",
"description": "Text for a button that customizes a search result before installing"
},
"searchResultCustomizeTooltip": {
"message": "Customize this style on userstyles.org",
"description": "Tooltip for a button that customizes a search result before installing"
},
"findStylesForSite": {
"message": "Find more styles for this site",
"description": "Text for a link that gets a list of styles for the current site"

View File

@ -104,6 +104,7 @@
</div>
<div class="actions">
<button class="searchResult-install" i18n-text="searchResultInstall" i18n-title="searchResultInstallTooltip"></button>
<button class="searchResult-customize hidden" i18n-text="searchResultCustomize" i18n-title="searchResultCustomizeTooltip"></button>
</div>
</div>
</template>

View File

@ -11,7 +11,8 @@
#searchResults.hidden,
#searchResults-error.hidden,
#find-styles.hidden,
#open-search.hidden {
#open-search.hidden,
.searchResult-customize.hidden {
display: none;
}
@ -97,6 +98,9 @@
.searchResult-install {
width: 100%;
}
.searchResult-install.customize, .searchResult-customize {
width: 50%;
}
#searchResultsNav {
flex-direction: row;

View File

@ -10,20 +10,34 @@ function SearchUserstyles() {
let currentPage = 1;
let exhausted = false;
return {getCurrentPage, getTotalPages, getCategory, isExhausted, search, fetchStyleJson};
return {getCurrentPage, getTotalPages, getCategory, isExhausted, search, fetchStyleJson, fetchStyle};
/**
* @returns {Number} The *Next* page to fetch for styles. Auto-incremented after each search.
*/
function getCurrentPage() {
return currentPage;
}
/**
* @returns {Number} The total number of search result pages.
*/
function getTotalPages() {
return totalPages;
}
/**
* @returns {Boolean} If there are no more results to fetch from userstyles.org
*/
function isExhausted() {
return exhausted;
}
/**
* Resolves the Userstyles.org "category" for a given URL.
* @param {String} url The URL to a webpage.
* @returns {Promise<String>} The category for a URL, or the hostname if category is not found.
*/
function getCategory(url) {
const hostname = new URL(url).hostname;
return new Promise(resolve => {
@ -49,7 +63,7 @@ function SearchUserstyles() {
* Fetches the JSON style object from userstyles.org (containing code, sections, updateUrl, etc).
* This is fetched from the /styles/chrome/ID.json endpoint.
* @param {number} userstylesId The internal "ID" for a style on userstyles.org
* @returns {Object} The response as a JSON object.
* @returns {Promise<Object>} The response as a JSON object.
*/
function fetchStyleJson(userstylesId) {
return new Promise((resolve, reject) => {
@ -62,6 +76,39 @@ function SearchUserstyles() {
});
}
/**
* Fetches style information from userstyles.org's /api/v1/styles/{ID} API.
* @param {number} userstylesId The internal "ID" for a style on userstyles.org
* @returns {Promise<Object>} An object containing info about the style, e.g. name, author, etc.
*/
function fetchStyle(userstylesId) {
return new Promise((resolve, reject) => {
const TIMEOUT = 10000;
const headers = {
'Content-type': 'application/json',
'Accept': '*/*'
};
const styleUrl = new URL('https://userstyles.org/api/v1/styles/' + userstylesId);
const xhr = new XMLHttpRequest();
xhr.timeout = TIMEOUT;
xhr.onload = () => {
if (xhr.status === 200) {
resolve(tryJSONparse(xhr.responseText));
} else {
console.log('fetch(' + userstylesId + ') [ERROR] ', xhr);
reject(xhr.status);
}
};
xhr.onerror = reject;
xhr.open('GET', styleUrl, true);
for (const key of Object.keys(headers)) {
xhr.setRequestHeader(key, headers[key]);
}
xhr.send();
});
}
/**
* Fetches (and JSON-parses) search results from a userstyles.org search API.
* Automatically sets currentPage and totalPages.
@ -70,7 +117,6 @@ function SearchUserstyles() {
*/
function search(category) {
return new Promise((resolve, reject) => {
console.log('search(' + category + ') currentPage:' + currentPage + ' totalPages:' + totalPages);
if (totalPages !== undefined && currentPage > totalPages) {
resolve({'data':[]});
}
@ -125,8 +171,19 @@ const SearchResults = (() => {
'C1HAwCAAAAC0lEQVR42mOcXQ8AAbsBHLLDr5MAAAAASUVORK5CYII=';
let loading = false;
let tabURL; // The active tab's URL.
let category; // Category for the active tab's URL.
let currentDisplayedPage = 1; // Current page number in popup.html
// Discovery current tab's URL & USO "category" for the URL.
getActiveTab().then(tab => {
tabURL = tab.url;
searchAPI.getCategory(tabURL)
.then(resolvedCategory => {
category = resolvedCategory;
$('#searchResults-terms').textContent = category;
});
});
return {load, next, prev};
function render() {
@ -171,23 +228,15 @@ const SearchResults = (() => {
* @returns {Boolean} If we should process more results.
*/
function shouldLoadMore() {
const result = (processedResults.length < currentDisplayedPage * DISPLAYED_RESULTS_PER_PAGE);
console.log('shouldLoadMore:',
result === true ? 'YES' : 'NO',
' processedResults.length(' + processedResults.length + ')',
'< currentDisplayedPage(' + currentDisplayedPage + ')',
'* DISPLAYED_RESULTS_PER_PAGE(' + DISPLAYED_RESULTS_PER_PAGE + ')');
return result;
return (processedResults.length < currentDisplayedPage * DISPLAYED_RESULTS_PER_PAGE);
}
function loadMoreIfNeeded() {
if (shouldLoadMore()) {
console.log('loadMoreIfNeeded: YES.');
loading = true;
render();
setTimeout(load, DELAY_BEFORE_SEARCHING_STYLES);
} else {
console.log('loadMoreIfNeeded: NO.');
loading = false;
render();
}
@ -222,7 +271,6 @@ const SearchResults = (() => {
// TODO: i18n message
message = 'No results found';
} else {
console.log('Error loading search results: ' + reason);
message = 'Error loading search results: ' + reason;
}
$('#searchResults').classList.add('hidden');
@ -248,7 +296,6 @@ const SearchResults = (() => {
}
if (searchAPI.isExhausted()) {
console.log('searchAPI is exhausted');
loading = false;
render();
return true;
@ -260,17 +307,8 @@ const SearchResults = (() => {
$('#searchResults-error').classList.add('hidden');
// Find styles for the current active tab
getActiveTab().then(tab => {
tabURL = tab.url;
searchAPI.getCategory(tabURL)
.then(category => {
console.log('userstyles.org "category" for URL ' + tabURL + ' is ' + category);
$('#searchResults-terms').textContent = category;
searchAPI.search(category)
.then(searchResults => {
console.log('load#searchAPI.search(', category, ') => ',
searchResults.data.length, 'results');
if (searchResults.data.length === 0) {
throw 404;
}
@ -278,8 +316,6 @@ const SearchResults = (() => {
processNextResult();
})
.catch(error);
});
});
return true;
}
@ -291,12 +327,9 @@ const SearchResults = (() => {
*/
function processNextResult() {
if (!shouldLoadMore()) {
console.log('[' + unprocessedResults.length + '] search results remain to be processed: STOPPED');
loading = false;
render();
return;
} else {
console.log('[' + unprocessedResults.length + '] search results remain to be processed: PROCESSING');
}
if (unprocessedResults.length === 0) {
@ -311,19 +344,18 @@ const SearchResults = (() => {
if (isInstalled) {
// Style already installed, skip it.
// TODO: Include the style anyway with option to "Uninstall" (?)
console.log('[' + unprocessedResults.length + '] style "' + nextResult.name +
'" already installed: CONTINUING');
setTimeout(processNextResult, 0); // Keep processing
} else if (nextResult.category !== 'site') {
// Style is not for a website, skip it.
console.log('[' + unprocessedResults.length + '] style "' + nextResult.name +
'" category is for "' + nextResult.category + '", not "site": CONTINUING');
setTimeout(processNextResult, 0); // Keep processing
} else {
// Style not installed, fetch full style to see if it applies to this site.
console.log('[' + unprocessedResults.length + '] fetching "' + nextResult.name + '": CONTINUING');
searchAPI.fetchStyleJson(nextResult.id)
.then(userstyleJson => {
// Style not installed.
// 1: Fetch full style (.JSON) to see if it applies to this site.
// 2: Fetch full style info to see if it has customizations.
Promise.all([
searchAPI.fetchStyleJson(nextResult.id), // for "sections" (applicable URLs)
searchAPI.fetchStyle(nextResult.id) // for "style_settings" (customizations)
]).then(([userstyleJson, userstyleObject]) => {
// Extract applicable sections (i.e. styles that apply to the current site)
const applicableSections = BG.getApplicableSections({
style: userstyleJson,
@ -333,17 +365,16 @@ const SearchResults = (() => {
if (applicableSections.length > 0) {
// Style is valid (can apply to this site).
nextResult.json = userstyleJson; // Store Style JSON for easy installing later.
// Store style settings for detecting customization later.
nextResult.style_settings = userstyleObject.style_settings;
processedResults.push(nextResult);
render();
}
console.log('[' + unprocessedResults.length + '] Processed "' + nextResult.name + '"',
'processedResults=' + processedResults.length,
'CONTINUING @ sleep=' + DELAY_AFTER_FETCHING_STYLES);
setTimeout(processNextResult, DELAY_AFTER_FETCHING_STYLES); // Keep processing
})
.catch(reason => {
console.log('[' + unprocessedResults.length + '] Error while loading style ID ' +
nextResult.id + ': ' + reason);
setTimeout(processNextResult, DELAY_AFTER_FETCHING_STYLES); // Keep processing
});
}
@ -359,7 +390,6 @@ const SearchResults = (() => {
return new Promise(function (resolve, reject) {
getStylesSafe()
.then(installedStyles => {
console.log('Seeing if searchResult(', userstyleSearchResult.name, ') is in matchingStyles');
const matchingStyles = installedStyles.filter(installedStyle => {
// Compare installed name to search result name.
let isMatch = installedStyle.name === userstyleSearchResult.name;
@ -389,11 +419,10 @@ const SearchResults = (() => {
user: {
id: 48470,
name: "holloh"
}
},
style_settings: [...]
}
*/
console.log('createSearchResultNode(', userstyleSearchResult.name, ')');
if (userstyleSearchResult.installed) {
return;
}
@ -469,17 +498,22 @@ const SearchResults = (() => {
textContent: userstyleSearchResult.total_install_count.toLocaleString()
});
// TODO: Total & Weekly Install Counts
// TODO: Rating
const installButton = $('.searchResult-install', entry);
installButton.onclick = install;
if (userstyleSearchResult.style_settings.length > 0) {
// Style has customizations
installButton.classList.add('customize');
const customizeButton = $('.searchResult-customize', entry);
customizeButton.classList.remove('hidden');
customizeButton.href = 'https://userstyles.org' + userstyleSearchResult.url;
customizeButton.onclick = handleEvent.openURLandHide;
}
/** Installs the current userstyleSearchResult into stylus. */
function install() {
entry.classList.add('loading');
// TODO on Install: Promise.all([fetchJSON, fetchHTML]) -> popup if customization is present, install otheriwse.
const styleId = userstyleSearchResult.id;
const url = 'https://userstyles.org/styles/chrome/' + styleId + '.json';
saveStyleSafe(userstyleSearchResult.json)
@ -487,22 +521,17 @@ const SearchResults = (() => {
// Remove search result after installing
let matchingIndex = -1;
processedResults.forEach((processedResult, index) => {
console.log('processedResult[' + index + '].id =', processedResult.id,
'userstyleSearchResult.id =', userstyleSearchResult.id);
if (processedResult.id === userstyleSearchResult.id) {
matchingIndex = index;
}
});
console.log('matchingIndex =', matchingIndex);
if (matchingIndex >= 0) {
console.log('processedResults.length before', processedResults.length);
processedResults.splice(matchingIndex, 1);
console.log('processedResults.length after', processedResults.length);
}
processNextResult();
})
.catch(reason => {
console.log('install:download(', url, ') => [ERROR]: ', reason);
console.log('install:saveStyleSafe(', url, ') => [ERROR]: ', reason);
alert('Error while downloading ' + url + '\nReason: ' + reason);
});
return true;