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:
parent
4c5b858f08
commit
8ae669bd12
|
@ -373,6 +373,14 @@
|
||||||
"message": "Install this search result",
|
"message": "Install this search result",
|
||||||
"description": "Tooltip for a button that installs a 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": {
|
"findStylesForSite": {
|
||||||
"message": "Find more styles for this site",
|
"message": "Find more styles for this site",
|
||||||
"description": "Text for a link that gets a list of styles for the current site"
|
"description": "Text for a link that gets a list of styles for the current site"
|
||||||
|
|
|
@ -104,6 +104,7 @@
|
||||||
</div>
|
</div>
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="searchResult-install" i18n-text="searchResultInstall" i18n-title="searchResultInstallTooltip"></button>
|
<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>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
@ -11,7 +11,8 @@
|
||||||
#searchResults.hidden,
|
#searchResults.hidden,
|
||||||
#searchResults-error.hidden,
|
#searchResults-error.hidden,
|
||||||
#find-styles.hidden,
|
#find-styles.hidden,
|
||||||
#open-search.hidden {
|
#open-search.hidden,
|
||||||
|
.searchResult-customize.hidden {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -97,6 +98,9 @@
|
||||||
.searchResult-install {
|
.searchResult-install {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
.searchResult-install.customize, .searchResult-customize {
|
||||||
|
width: 50%;
|
||||||
|
}
|
||||||
|
|
||||||
#searchResultsNav {
|
#searchResultsNav {
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
|
|
|
@ -10,20 +10,34 @@ function SearchUserstyles() {
|
||||||
let currentPage = 1;
|
let currentPage = 1;
|
||||||
let exhausted = false;
|
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() {
|
function getCurrentPage() {
|
||||||
return currentPage;
|
return currentPage;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @returns {Number} The total number of search result pages.
|
||||||
|
*/
|
||||||
function getTotalPages() {
|
function getTotalPages() {
|
||||||
return totalPages;
|
return totalPages;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @returns {Boolean} If there are no more results to fetch from userstyles.org
|
||||||
|
*/
|
||||||
function isExhausted() {
|
function isExhausted() {
|
||||||
return exhausted;
|
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) {
|
function getCategory(url) {
|
||||||
const hostname = new URL(url).hostname;
|
const hostname = new URL(url).hostname;
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
|
@ -49,7 +63,7 @@ function SearchUserstyles() {
|
||||||
* Fetches the JSON style object from userstyles.org (containing code, sections, updateUrl, etc).
|
* Fetches the JSON style object from userstyles.org (containing code, sections, updateUrl, etc).
|
||||||
* This is fetched from the /styles/chrome/ID.json endpoint.
|
* This is fetched from the /styles/chrome/ID.json endpoint.
|
||||||
* @param {number} userstylesId The internal "ID" for a style on userstyles.org
|
* @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) {
|
function fetchStyleJson(userstylesId) {
|
||||||
return new Promise((resolve, reject) => {
|
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.
|
* Fetches (and JSON-parses) search results from a userstyles.org search API.
|
||||||
* Automatically sets currentPage and totalPages.
|
* Automatically sets currentPage and totalPages.
|
||||||
|
@ -70,7 +117,6 @@ function SearchUserstyles() {
|
||||||
*/
|
*/
|
||||||
function search(category) {
|
function search(category) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
console.log('search(' + category + ') currentPage:' + currentPage + ' totalPages:' + totalPages);
|
|
||||||
if (totalPages !== undefined && currentPage > totalPages) {
|
if (totalPages !== undefined && currentPage > totalPages) {
|
||||||
resolve({'data':[]});
|
resolve({'data':[]});
|
||||||
}
|
}
|
||||||
|
@ -125,8 +171,19 @@ const SearchResults = (() => {
|
||||||
'C1HAwCAAAAC0lEQVR42mOcXQ8AAbsBHLLDr5MAAAAASUVORK5CYII=';
|
'C1HAwCAAAAC0lEQVR42mOcXQ8AAbsBHLLDr5MAAAAASUVORK5CYII=';
|
||||||
let loading = false;
|
let loading = false;
|
||||||
let tabURL; // The active tab's URL.
|
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
|
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};
|
return {load, next, prev};
|
||||||
|
|
||||||
function render() {
|
function render() {
|
||||||
|
@ -171,23 +228,15 @@ const SearchResults = (() => {
|
||||||
* @returns {Boolean} If we should process more results.
|
* @returns {Boolean} If we should process more results.
|
||||||
*/
|
*/
|
||||||
function shouldLoadMore() {
|
function shouldLoadMore() {
|
||||||
const result = (processedResults.length < currentDisplayedPage * DISPLAYED_RESULTS_PER_PAGE);
|
return (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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadMoreIfNeeded() {
|
function loadMoreIfNeeded() {
|
||||||
if (shouldLoadMore()) {
|
if (shouldLoadMore()) {
|
||||||
console.log('loadMoreIfNeeded: YES.');
|
|
||||||
loading = true;
|
loading = true;
|
||||||
render();
|
render();
|
||||||
setTimeout(load, DELAY_BEFORE_SEARCHING_STYLES);
|
setTimeout(load, DELAY_BEFORE_SEARCHING_STYLES);
|
||||||
} else {
|
} else {
|
||||||
console.log('loadMoreIfNeeded: NO.');
|
|
||||||
loading = false;
|
loading = false;
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
@ -222,7 +271,6 @@ const SearchResults = (() => {
|
||||||
// TODO: i18n message
|
// TODO: i18n message
|
||||||
message = 'No results found';
|
message = 'No results found';
|
||||||
} else {
|
} else {
|
||||||
console.log('Error loading search results: ' + reason);
|
|
||||||
message = 'Error loading search results: ' + reason;
|
message = 'Error loading search results: ' + reason;
|
||||||
}
|
}
|
||||||
$('#searchResults').classList.add('hidden');
|
$('#searchResults').classList.add('hidden');
|
||||||
|
@ -248,7 +296,6 @@ const SearchResults = (() => {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (searchAPI.isExhausted()) {
|
if (searchAPI.isExhausted()) {
|
||||||
console.log('searchAPI is exhausted');
|
|
||||||
loading = false;
|
loading = false;
|
||||||
render();
|
render();
|
||||||
return true;
|
return true;
|
||||||
|
@ -260,26 +307,15 @@ const SearchResults = (() => {
|
||||||
$('#searchResults-error').classList.add('hidden');
|
$('#searchResults-error').classList.add('hidden');
|
||||||
|
|
||||||
// Find styles for the current active tab
|
// Find styles for the current active tab
|
||||||
getActiveTab().then(tab => {
|
searchAPI.search(category)
|
||||||
tabURL = tab.url;
|
.then(searchResults => {
|
||||||
searchAPI.getCategory(tabURL)
|
if (searchResults.data.length === 0) {
|
||||||
.then(category => {
|
throw 404;
|
||||||
console.log('userstyles.org "category" for URL ' + tabURL + ' is ' + category);
|
}
|
||||||
$('#searchResults-terms').textContent = category;
|
unprocessedResults.push.apply(unprocessedResults, searchResults.data);
|
||||||
|
processNextResult();
|
||||||
searchAPI.search(category)
|
})
|
||||||
.then(searchResults => {
|
.catch(error);
|
||||||
console.log('load#searchAPI.search(', category, ') => ',
|
|
||||||
searchResults.data.length, 'results');
|
|
||||||
if (searchResults.data.length === 0) {
|
|
||||||
throw 404;
|
|
||||||
}
|
|
||||||
unprocessedResults.push.apply(unprocessedResults, searchResults.data);
|
|
||||||
processNextResult();
|
|
||||||
})
|
|
||||||
.catch(error);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -291,12 +327,9 @@ const SearchResults = (() => {
|
||||||
*/
|
*/
|
||||||
function processNextResult() {
|
function processNextResult() {
|
||||||
if (!shouldLoadMore()) {
|
if (!shouldLoadMore()) {
|
||||||
console.log('[' + unprocessedResults.length + '] search results remain to be processed: STOPPED');
|
|
||||||
loading = false;
|
loading = false;
|
||||||
render();
|
render();
|
||||||
return;
|
return;
|
||||||
} else {
|
|
||||||
console.log('[' + unprocessedResults.length + '] search results remain to be processed: PROCESSING');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (unprocessedResults.length === 0) {
|
if (unprocessedResults.length === 0) {
|
||||||
|
@ -311,41 +344,39 @@ const SearchResults = (() => {
|
||||||
if (isInstalled) {
|
if (isInstalled) {
|
||||||
// Style already installed, skip it.
|
// Style already installed, skip it.
|
||||||
// TODO: Include the style anyway with option to "Uninstall" (?)
|
// TODO: Include the style anyway with option to "Uninstall" (?)
|
||||||
console.log('[' + unprocessedResults.length + '] style "' + nextResult.name +
|
|
||||||
'" already installed: CONTINUING');
|
|
||||||
setTimeout(processNextResult, 0); // Keep processing
|
setTimeout(processNextResult, 0); // Keep processing
|
||||||
} else if (nextResult.category !== 'site') {
|
} else if (nextResult.category !== 'site') {
|
||||||
// Style is not for a website, skip it.
|
// 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
|
setTimeout(processNextResult, 0); // Keep processing
|
||||||
} else {
|
} else {
|
||||||
// Style not installed, fetch full style to see if it applies to this site.
|
// Style not installed.
|
||||||
console.log('[' + unprocessedResults.length + '] fetching "' + nextResult.name + '": CONTINUING');
|
// 1: Fetch full style (.JSON) to see if it applies to this site.
|
||||||
searchAPI.fetchStyleJson(nextResult.id)
|
// 2: Fetch full style info to see if it has customizations.
|
||||||
.then(userstyleJson => {
|
Promise.all([
|
||||||
// Extract applicable sections (i.e. styles that apply to the current site)
|
searchAPI.fetchStyleJson(nextResult.id), // for "sections" (applicable URLs)
|
||||||
const applicableSections = BG.getApplicableSections({
|
searchAPI.fetchStyle(nextResult.id) // for "style_settings" (customizations)
|
||||||
style: userstyleJson,
|
]).then(([userstyleJson, userstyleObject]) => {
|
||||||
matchUrl: tabURL,
|
// Extract applicable sections (i.e. styles that apply to the current site)
|
||||||
stopOnFirst: true
|
const applicableSections = BG.getApplicableSections({
|
||||||
});
|
style: userstyleJson,
|
||||||
if (applicableSections.length > 0) {
|
matchUrl: tabURL,
|
||||||
// Style is valid (can apply to this site).
|
stopOnFirst: true
|
||||||
nextResult.json = userstyleJson; // Store Style JSON for easy installing later.
|
|
||||||
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
|
|
||||||
});
|
});
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
setTimeout(processNextResult, DELAY_AFTER_FETCHING_STYLES); // Keep processing
|
||||||
|
})
|
||||||
|
.catch(reason => {
|
||||||
|
setTimeout(processNextResult, DELAY_AFTER_FETCHING_STYLES); // Keep processing
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -359,7 +390,6 @@ const SearchResults = (() => {
|
||||||
return new Promise(function (resolve, reject) {
|
return new Promise(function (resolve, reject) {
|
||||||
getStylesSafe()
|
getStylesSafe()
|
||||||
.then(installedStyles => {
|
.then(installedStyles => {
|
||||||
console.log('Seeing if searchResult(', userstyleSearchResult.name, ') is in matchingStyles');
|
|
||||||
const matchingStyles = installedStyles.filter(installedStyle => {
|
const matchingStyles = installedStyles.filter(installedStyle => {
|
||||||
// Compare installed name to search result name.
|
// Compare installed name to search result name.
|
||||||
let isMatch = installedStyle.name === userstyleSearchResult.name;
|
let isMatch = installedStyle.name === userstyleSearchResult.name;
|
||||||
|
@ -389,11 +419,10 @@ const SearchResults = (() => {
|
||||||
user: {
|
user: {
|
||||||
id: 48470,
|
id: 48470,
|
||||||
name: "holloh"
|
name: "holloh"
|
||||||
}
|
},
|
||||||
|
style_settings: [...]
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
console.log('createSearchResultNode(', userstyleSearchResult.name, ')');
|
|
||||||
|
|
||||||
if (userstyleSearchResult.installed) {
|
if (userstyleSearchResult.installed) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -469,17 +498,22 @@ const SearchResults = (() => {
|
||||||
textContent: userstyleSearchResult.total_install_count.toLocaleString()
|
textContent: userstyleSearchResult.total_install_count.toLocaleString()
|
||||||
});
|
});
|
||||||
|
|
||||||
// TODO: Total & Weekly Install Counts
|
|
||||||
// TODO: Rating
|
|
||||||
|
|
||||||
const installButton = $('.searchResult-install', entry);
|
const installButton = $('.searchResult-install', entry);
|
||||||
installButton.onclick = install;
|
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. */
|
/** Installs the current userstyleSearchResult into stylus. */
|
||||||
function install() {
|
function install() {
|
||||||
entry.classList.add('loading');
|
entry.classList.add('loading');
|
||||||
|
|
||||||
// TODO on Install: Promise.all([fetchJSON, fetchHTML]) -> popup if customization is present, install otheriwse.
|
|
||||||
const styleId = userstyleSearchResult.id;
|
const styleId = userstyleSearchResult.id;
|
||||||
const url = 'https://userstyles.org/styles/chrome/' + styleId + '.json';
|
const url = 'https://userstyles.org/styles/chrome/' + styleId + '.json';
|
||||||
saveStyleSafe(userstyleSearchResult.json)
|
saveStyleSafe(userstyleSearchResult.json)
|
||||||
|
@ -487,22 +521,17 @@ const SearchResults = (() => {
|
||||||
// Remove search result after installing
|
// Remove search result after installing
|
||||||
let matchingIndex = -1;
|
let matchingIndex = -1;
|
||||||
processedResults.forEach((processedResult, index) => {
|
processedResults.forEach((processedResult, index) => {
|
||||||
console.log('processedResult[' + index + '].id =', processedResult.id,
|
|
||||||
'userstyleSearchResult.id =', userstyleSearchResult.id);
|
|
||||||
if (processedResult.id === userstyleSearchResult.id) {
|
if (processedResult.id === userstyleSearchResult.id) {
|
||||||
matchingIndex = index;
|
matchingIndex = index;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
console.log('matchingIndex =', matchingIndex);
|
|
||||||
if (matchingIndex >= 0) {
|
if (matchingIndex >= 0) {
|
||||||
console.log('processedResults.length before', processedResults.length);
|
|
||||||
processedResults.splice(matchingIndex, 1);
|
processedResults.splice(matchingIndex, 1);
|
||||||
console.log('processedResults.length after', processedResults.length);
|
|
||||||
}
|
}
|
||||||
processNextResult();
|
processNextResult();
|
||||||
})
|
})
|
||||||
.catch(reason => {
|
.catch(reason => {
|
||||||
console.log('install:download(', url, ') => [ERROR]: ', reason);
|
console.log('install:saveStyleSafe(', url, ') => [ERROR]: ', reason);
|
||||||
alert('Error while downloading ' + url + '\nReason: ' + reason);
|
alert('Error while downloading ' + url + '\nReason: ' + reason);
|
||||||
});
|
});
|
||||||
return true;
|
return true;
|
||||||
|
|
Loading…
Reference in New Issue
Block a user