Address part of PR feedback.
Main diff: Wrapped onDOMready() & SearchResults() function in IIFE closure. * [X] const SearchResults = ... // should be inside a closure (IIFE @ Top) * [X] SearchUserstyles should be firstLetterLowercase * [X] Don't fetch category on load; use regexp to derive category. (left 'HEAD' code commented-out). * [X] Don't use XMLHttpRequest() anymore (used in 3 places?): Use download() which accepts custom request params. * [X] Remove unused getters ('getCurrentPage' & others?) * [X] const BASE_USO_URL = 'https://userstyles.org'; @ top of searchResults closure. Refer elsewhere. * [X] const searchUrl = new URL... should be a single multiline statement (new URL('...' +\ '...' * [X] .innerHTML = ... // use .textContent = ... instead * [X] Don't use `setAttribute` on 'disabled': $('..-prev').disabled = currentDisplayedPage <= 1 || loading * [X] Don't use .indexOf() on strings, use .includes() * [X] Move onDOMReady() code to top of file.
This commit is contained in:
parent
6cdc442986
commit
8d75042f02
|
@ -85,7 +85,7 @@
|
||||||
|
|
||||||
<template data-id="searchResult">
|
<template data-id="searchResult">
|
||||||
<div class="searchResult">
|
<div class="searchResult">
|
||||||
<img class="searchResult-screenshot no-screenshot" />
|
<img class="searchResult-screenshot" />
|
||||||
<a class="searchResult-title" target="_blank"></a>
|
<a class="searchResult-title" target="_blank"></a>
|
||||||
<div class="searchResult-description"></div>
|
<div class="searchResult-description"></div>
|
||||||
<div class="searchResult-author">
|
<div class="searchResult-author">
|
||||||
|
@ -151,6 +151,7 @@
|
||||||
<span i18n-text="searchResultsHeader"></span>
|
<span i18n-text="searchResultsHeader"></span>
|
||||||
<span id="searchResults-terms">...</span>
|
<span id="searchResults-terms">...</span>
|
||||||
</h3>
|
</h3>
|
||||||
|
<div id="searchResults-list"></div>
|
||||||
<div id="searchResultsNav">
|
<div id="searchResultsNav">
|
||||||
<button id="searchResultsNav-prev" title="Previous page" disabled>Prev</button>
|
<button id="searchResultsNav-prev" title="Previous page" disabled>Prev</button>
|
||||||
<label>
|
<label>
|
||||||
|
@ -160,7 +161,6 @@
|
||||||
</label>
|
</label>
|
||||||
<button id="searchResultsNav-next" title="Next page" disabled>Next</button>
|
<button id="searchResultsNav-next" title="Next page" disabled>Next</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="searchResults-list"></div>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="left-gutter"></div>
|
<div class="left-gutter"></div>
|
||||||
<div class="main-controls">
|
<div class="main-controls">
|
||||||
|
|
|
@ -1,170 +1,23 @@
|
||||||
/* global handleEvent tryJSONparse getStylesSafe BG */
|
/* global handleEvent tryJSONparse getStylesSafe BG */
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
/**
|
(() => {
|
||||||
* Library for interacting with userstyles.org
|
onDOMready().then(() => {
|
||||||
* @returns {Object} Exposed methods representing the search results on userstyles.org
|
const searchResults = searchResultsController();
|
||||||
*/
|
$('#find-styles-link').onclick = searchResults.load;
|
||||||
function SearchUserstyles() {
|
$('#searchResultsNav-prev').onclick = searchResults.prev;
|
||||||
let totalPages;
|
$('#searchResultsNav-next').onclick = searchResults.next;
|
||||||
let currentPage = 1;
|
|
||||||
let exhausted = false;
|
|
||||||
|
|
||||||
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 => {
|
|
||||||
const request = new XMLHttpRequest();
|
|
||||||
const browseURL = 'https://userstyles.org/styles/browse/all/' + encodeURIComponent(url);
|
|
||||||
request.open('HEAD', browseURL, true);
|
|
||||||
request.onreadystatechange = () => {
|
|
||||||
if (request.readyState === XMLHttpRequest.DONE) {
|
|
||||||
const responseURL = new URL(request.responseURL);
|
|
||||||
const category = responseURL.searchParams.get('category');
|
|
||||||
if (category !== null) {
|
|
||||||
resolve(category);
|
|
||||||
} else {
|
|
||||||
resolve(hostname);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
request.send(null);
|
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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 {Promise<Object>} The response as a JSON object.
|
|
||||||
*/
|
|
||||||
function fetchStyleJson(userstylesId) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const jsonUrl = 'https://userstyles.org/styles/chrome/' + userstylesId + '.json';
|
|
||||||
download(jsonUrl)
|
|
||||||
.then(responseText => {
|
|
||||||
resolve(tryJSONparse(responseText));
|
|
||||||
})
|
|
||||||
.catch(reject);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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.
|
|
||||||
* @param {string} category The usrestyles.org "category" (subcategory) OR a any search string.
|
|
||||||
* @return {Object} Response object from userstyles.org
|
|
||||||
*/
|
|
||||||
function search(category) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
if (totalPages !== undefined && currentPage > totalPages) {
|
|
||||||
resolve({'data':[]});
|
|
||||||
}
|
|
||||||
|
|
||||||
const TIMEOUT = 10000;
|
|
||||||
const headers = {
|
|
||||||
'Content-type': 'application/json',
|
|
||||||
'Accept': '*/*'
|
|
||||||
};
|
|
||||||
|
|
||||||
const searchUrl = new URL('https://userstyles.org/api/v1/styles/subcategory');
|
|
||||||
let queryParams = 'search=' + encodeURIComponent(category);
|
|
||||||
queryParams += '&page=' + currentPage;
|
|
||||||
queryParams += '&country=NA';
|
|
||||||
searchUrl.search = '?' + queryParams;
|
|
||||||
const xhr = new XMLHttpRequest();
|
|
||||||
xhr.timeout = TIMEOUT;
|
|
||||||
xhr.onload = () => {
|
|
||||||
if (xhr.status === 200) {
|
|
||||||
const responseJson = tryJSONparse(xhr.responseText);
|
|
||||||
currentPage = responseJson.current_page + 1;
|
|
||||||
totalPages = responseJson.total_pages;
|
|
||||||
exhausted = (currentPage > totalPages);
|
|
||||||
resolve(responseJson);
|
|
||||||
} else {
|
|
||||||
exhausted = true;
|
|
||||||
reject(xhr.status);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
xhr.onerror = reject;
|
|
||||||
xhr.open('GET', searchUrl, true);
|
|
||||||
for (const key of Object.keys(headers)) {
|
|
||||||
xhr.setRequestHeader(key, headers[key]);
|
|
||||||
}
|
|
||||||
xhr.send();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents the search results within the Stylus popup.
|
* Represents the search results within the Stylus popup.
|
||||||
* @returns {Object} Includes load(), next(), and prev() methods to alter the search results.
|
* @returns {Object} Includes load(), next(), and prev() methods to alter the search results.
|
||||||
*/
|
*/
|
||||||
const SearchResults = (() => {
|
function searchResultsController() {
|
||||||
const DISPLAYED_RESULTS_PER_PAGE = 3; // Number of results to display in popup.html
|
const DISPLAYED_RESULTS_PER_PAGE = 3; // Number of results to display in popup.html
|
||||||
const DELAY_AFTER_FETCHING_STYLES = 0; // Millisecs to wait before fetching next batch of search results.
|
const DELAY_AFTER_FETCHING_STYLES = 0; // Millisecs to wait before fetching next batch of search results.
|
||||||
const DELAY_BEFORE_SEARCHING_STYLES = 0; // Millisecs to wait before fetching .JSON for next search result.
|
const DELAY_BEFORE_SEARCHING_STYLES = 0; // Millisecs to wait before fetching .JSON for next search result.
|
||||||
const searchAPI = SearchUserstyles();
|
const searchAPI = searchUserstyles();
|
||||||
const unprocessedResults = []; // Search results not yet processed.
|
const unprocessedResults = []; // Search results not yet processed.
|
||||||
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' +
|
||||||
|
@ -174,20 +27,10 @@ const SearchResults = (() => {
|
||||||
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
|
||||||
|
|
||||||
// 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() {
|
||||||
$('#searchResults-list').innerHTML = ''; // Clear search results
|
$('#searchResults-list').textContent = ''; // Clear search results
|
||||||
|
|
||||||
const startIndex = (currentDisplayedPage - 1) * DISPLAYED_RESULTS_PER_PAGE;
|
const startIndex = (currentDisplayedPage - 1) * DISPLAYED_RESULTS_PER_PAGE;
|
||||||
const endIndex = currentDisplayedPage * DISPLAYED_RESULTS_PER_PAGE;
|
const endIndex = currentDisplayedPage * DISPLAYED_RESULTS_PER_PAGE;
|
||||||
|
@ -197,9 +40,9 @@ const SearchResults = (() => {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (currentDisplayedPage <= 1 || loading) {
|
if (currentDisplayedPage <= 1 || loading) {
|
||||||
$('#searchResultsNav-prev').setAttribute('disabled', 'disabled');
|
$('#searchResultsNav-prev').disabled = true;
|
||||||
} else {
|
} else {
|
||||||
$('#searchResultsNav-prev').removeAttribute('disabled');
|
$('#searchResultsNav-prev').disabled = false;
|
||||||
}
|
}
|
||||||
$('#searchResultsNav-currentPage').textContent = currentDisplayedPage;
|
$('#searchResultsNav-currentPage').textContent = currentDisplayedPage;
|
||||||
|
|
||||||
|
@ -210,9 +53,9 @@ const SearchResults = (() => {
|
||||||
}
|
}
|
||||||
const totalPageCount = Math.ceil(Math.max(1, totalResultsCount / DISPLAYED_RESULTS_PER_PAGE));
|
const totalPageCount = Math.ceil(Math.max(1, totalResultsCount / DISPLAYED_RESULTS_PER_PAGE));
|
||||||
if (currentDisplayedPage >= totalPageCount || loading) {
|
if (currentDisplayedPage >= totalPageCount || loading) {
|
||||||
$('#searchResultsNav-next').setAttribute('disabled', 'disabled');
|
$('#searchResultsNav-next').disabled = true;
|
||||||
} else {
|
} else {
|
||||||
$('#searchResultsNav-next').removeAttribute('disabled');
|
$('#searchResultsNav-next').disabled = false;
|
||||||
}
|
}
|
||||||
$('#searchResultsNav-totalPages').textContent = totalPageCount;
|
$('#searchResultsNav-totalPages').textContent = totalPageCount;
|
||||||
|
|
||||||
|
@ -274,7 +117,7 @@ const SearchResults = (() => {
|
||||||
message = 'Error loading search results: ' + reason;
|
message = 'Error loading search results: ' + reason;
|
||||||
}
|
}
|
||||||
$('#searchResults').classList.add('hidden');
|
$('#searchResults').classList.add('hidden');
|
||||||
$('#searchResults-error').innerHTML = message;
|
$('#searchResults-error').textContent = message;
|
||||||
$('#searchResults-error').classList.remove('hidden');
|
$('#searchResults-error').classList.remove('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -306,7 +149,11 @@ const SearchResults = (() => {
|
||||||
$('#searchResults').classList.remove('hidden');
|
$('#searchResults').classList.remove('hidden');
|
||||||
$('#searchResults-error').classList.add('hidden');
|
$('#searchResults-error').classList.add('hidden');
|
||||||
|
|
||||||
// Find styles for the current active tab
|
// Discover current tab's URL & the "category" for the URL, then search.
|
||||||
|
getActiveTab().then(tab => {
|
||||||
|
tabURL = tab.url;
|
||||||
|
category = searchAPI.getCategory(tabURL);
|
||||||
|
$('#searchResults-terms').textContent = category;
|
||||||
searchAPI.search(category)
|
searchAPI.search(category)
|
||||||
.then(searchResults => {
|
.then(searchResults => {
|
||||||
if (searchResults.data.length === 0) {
|
if (searchResults.data.length === 0) {
|
||||||
|
@ -316,6 +163,8 @@ const SearchResults = (() => {
|
||||||
processNextResult();
|
processNextResult();
|
||||||
})
|
})
|
||||||
.catch(error);
|
.catch(error);
|
||||||
|
});
|
||||||
|
// Find styles for the current active tab
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -396,7 +245,7 @@ const SearchResults = (() => {
|
||||||
let isMatch = installedStyle.name === userstyleSearchResult.name;
|
let isMatch = installedStyle.name === userstyleSearchResult.name;
|
||||||
// Compare if search result ID (userstyles ID) is mentioned in the installed updateUrl.
|
// Compare if search result ID (userstyles ID) is mentioned in the installed updateUrl.
|
||||||
if (installedStyle.updateUrl) {
|
if (installedStyle.updateUrl) {
|
||||||
isMatch &= installedStyle.updateUrl.indexOf('/' + userstyleSearchResult.id + '.json') >= 0;
|
isMatch &= installedStyle.updateUrl.includes('/' + userstyleSearchResult.id + '.json');
|
||||||
}
|
}
|
||||||
return isMatch;
|
return isMatch;
|
||||||
});
|
});
|
||||||
|
@ -437,9 +286,9 @@ const SearchResults = (() => {
|
||||||
const searchResultName = userstyleSearchResult.name;
|
const searchResultName = userstyleSearchResult.name;
|
||||||
const title = $('.searchResult-title', entry);
|
const title = $('.searchResult-title', entry);
|
||||||
Object.assign(title, {
|
Object.assign(title, {
|
||||||
textContent: searchResultName + ' (by ' + userstyleSearchResult.user.name + ')',
|
textContent: searchResultName,
|
||||||
title: searchResultName + ' by: ' + userstyleSearchResult.user.name,
|
title: searchResultName,
|
||||||
href: 'https://userstyles.org' + userstyleSearchResult.url,
|
href: searchAPI.BASE_URL + userstyleSearchResult.url,
|
||||||
onclick: handleEvent.openURLandHide
|
onclick: handleEvent.openURLandHide
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -447,15 +296,13 @@ const SearchResults = (() => {
|
||||||
let screenshotUrl = userstyleSearchResult.screenshot_url;
|
let screenshotUrl = userstyleSearchResult.screenshot_url;
|
||||||
if (screenshotUrl === null) {
|
if (screenshotUrl === null) {
|
||||||
screenshotUrl = BLANK_PIXEL_DATA;
|
screenshotUrl = BLANK_PIXEL_DATA;
|
||||||
|
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 = 'https://userstyles.org/style_screenshot_thumbnails/' + screenshotUrl;
|
screenshotUrl = searchAPI.BASE_URL + '/style_screenshot_thumbnails/' + screenshotUrl;
|
||||||
screenshot.classList.remove('no-screenshot');
|
|
||||||
} else {
|
|
||||||
screenshot.classList.remove('no-screenshot');
|
|
||||||
}
|
}
|
||||||
Object.assign(screenshot, {
|
Object.assign(screenshot, {
|
||||||
src: screenshotUrl,
|
src: screenshotUrl,
|
||||||
title: '"' + searchResultName + '" by ' + userstyleSearchResult.user.name
|
title: searchResultName
|
||||||
});
|
});
|
||||||
|
|
||||||
// TODO: Expand/collapse description
|
// TODO: Expand/collapse description
|
||||||
|
@ -469,7 +316,7 @@ const SearchResults = (() => {
|
||||||
Object.assign(authorLink, {
|
Object.assign(authorLink, {
|
||||||
textContent: userstyleSearchResult.user.name,
|
textContent: userstyleSearchResult.user.name,
|
||||||
title: userstyleSearchResult.user.name,
|
title: userstyleSearchResult.user.name,
|
||||||
href: 'https://userstyles.org/users/' + userstyleSearchResult.user.id,
|
href: searchAPI.BASE_URL + '/users/' + userstyleSearchResult.user.id,
|
||||||
onclick: handleEvent.openURLandHide
|
onclick: handleEvent.openURLandHide
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -507,7 +354,7 @@ const SearchResults = (() => {
|
||||||
installButton.classList.add('customize');
|
installButton.classList.add('customize');
|
||||||
const customizeButton = $('.searchResult-customize', entry);
|
const customizeButton = $('.searchResult-customize', entry);
|
||||||
customizeButton.classList.remove('hidden');
|
customizeButton.classList.remove('hidden');
|
||||||
customizeButton.href = 'https://userstyles.org' + userstyleSearchResult.url;
|
customizeButton.href = searchAPI.BASE_URL + userstyleSearchResult.url;
|
||||||
customizeButton.onclick = handleEvent.openURLandHide;
|
customizeButton.onclick = handleEvent.openURLandHide;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -516,7 +363,7 @@ const SearchResults = (() => {
|
||||||
entry.classList.add('loading');
|
entry.classList.add('loading');
|
||||||
|
|
||||||
const styleId = userstyleSearchResult.id;
|
const styleId = userstyleSearchResult.id;
|
||||||
const url = 'https://userstyles.org/styles/chrome/' + styleId + '.json';
|
const url = searchAPI.BASE_URL + '/styles/chrome/' + styleId + '.json';
|
||||||
saveStyleSafe(userstyleSearchResult.json)
|
saveStyleSafe(userstyleSearchResult.json)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
// Remove search result after installing
|
// Remove search result after installing
|
||||||
|
@ -538,10 +385,134 @@ const SearchResults = (() => {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
onDOMready().then(() => {
|
/**
|
||||||
$('#find-styles-link').onclick = SearchResults.load;
|
* Library for interacting with userstyles.org
|
||||||
$('#searchResultsNav-prev').onclick = SearchResults.prev;
|
* @returns {Object} Exposed methods representing the search results on userstyles.org
|
||||||
$('#searchResultsNav-next').onclick = SearchResults.next;
|
*/
|
||||||
|
function searchUserstyles() {
|
||||||
|
const BASE_URL = 'https://userstyles.org';
|
||||||
|
let totalPages;
|
||||||
|
let currentPage = 1;
|
||||||
|
let exhausted = false;
|
||||||
|
|
||||||
|
return {BASE_URL, getCategory, isExhausted, search, fetchStyleJson, fetchStyle};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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) {
|
||||||
|
let hostname = new URL(url).hostname;
|
||||||
|
// Strip "TLD" (including .com.TLD, .co.TLD, etc)
|
||||||
|
hostname = hostname.replace(/(\.com|\.co|\.org|\.net|\.gov)?\.[a-z0-9]+$/, '');
|
||||||
|
// Strip "subdomains"
|
||||||
|
hostname = hostname.split(/\./g).pop();
|
||||||
|
return hostname;
|
||||||
|
/*
|
||||||
|
// Resolve "category" using userstyles.org's /styles/browse/all/ endpoint:
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const request = new XMLHttpRequest();
|
||||||
|
const browseURL = BASE_URL + '/styles/browse/all/' + encodeURIComponent(url);
|
||||||
|
request.open('HEAD', browseURL, true);
|
||||||
|
request.onreadystatechange = () => {
|
||||||
|
if (request.readyState === XMLHttpRequest.DONE) {
|
||||||
|
const responseURL = new URL(request.responseURL);
|
||||||
|
const searchCategory = responseURL.searchParams.get('category');
|
||||||
|
if (searchCategory !== null) {
|
||||||
|
resolve(searchCategory);
|
||||||
|
} else {
|
||||||
|
resolve(hostname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
request.send(null);
|
||||||
});
|
});
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {Promise<Object>} The response as a JSON object.
|
||||||
|
*/
|
||||||
|
function fetchStyleJson(userstylesId) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const jsonUrl = BASE_URL + '/styles/chrome/' + userstylesId + '.json';
|
||||||
|
download(jsonUrl)
|
||||||
|
.then(responseText => {
|
||||||
|
resolve(tryJSONparse(responseText));
|
||||||
|
})
|
||||||
|
.catch(reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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) => {
|
||||||
|
download(BASE_URL + '/api/v1/styles/' + userstylesId, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'Content-type': 'application/json',
|
||||||
|
'Accept': '*/*'
|
||||||
|
},
|
||||||
|
body: null
|
||||||
|
}).then(responseText => {
|
||||||
|
resolve(tryJSONparse(responseText));
|
||||||
|
}).catch(reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches (and JSON-parses) search results from a userstyles.org search API.
|
||||||
|
* Automatically sets currentPage and totalPages.
|
||||||
|
* @param {string} category The usrestyles.org "category" (subcategory) OR a any search string.
|
||||||
|
* @return {Object} Response object from userstyles.org
|
||||||
|
*/
|
||||||
|
function search(category) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (totalPages !== undefined && currentPage > totalPages) {
|
||||||
|
resolve({'data':[]});
|
||||||
|
}
|
||||||
|
|
||||||
|
const searchURL = BASE_URL +
|
||||||
|
'/api/v1/styles/subcategory' +
|
||||||
|
'?search=' + encodeURIComponent(category) +
|
||||||
|
'&page=' + currentPage +
|
||||||
|
'&country=NA';
|
||||||
|
|
||||||
|
download(searchURL, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'Content-type': 'application/json',
|
||||||
|
'Accept': '*/*'
|
||||||
|
},
|
||||||
|
body: null
|
||||||
|
}).then(responseText => {
|
||||||
|
const responseJson = tryJSONparse(responseText);
|
||||||
|
currentPage = responseJson.current_page + 1;
|
||||||
|
totalPages = responseJson.total_pages;
|
||||||
|
exhausted = (currentPage > totalPages);
|
||||||
|
resolve(responseJson);
|
||||||
|
}).catch(reason => {
|
||||||
|
exhausted = true;
|
||||||
|
reject(reason);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user