Encapsulating searchResults.js per feedback in #243

This commit is contained in:
derv82 2017-11-19 19:36:43 -08:00
parent 1da3027f8b
commit c0b48ab548
2 changed files with 202 additions and 173 deletions

View File

@ -101,7 +101,6 @@
<script src="js/prefs.js"></script> <script src="js/prefs.js"></script>
<script src="content/apply.js"></script> <script src="content/apply.js"></script>
<script src="popup/popup.js"></script> <script src="popup/popup.js"></script>
<script src="js/script-loader.js"></script>
<script src="popup/searchResults.js"></script> <script src="popup/searchResults.js"></script>
</head> </head>

View File

@ -1,140 +1,124 @@
'use strict'; 'use strict';
let currentPage = 1;
/** /**
* Fetches JSON object from userstyles.org API * Library for interacting with userstyles.org
* @param {string} path Path on userstyles.org (e.g. /api/v1/styles) * @returns {Object} Includes fetch() method which promises userstyles.org resources.
* @param {string} queryParams Query parameters to send in search request.
* @return {Object} API response object from userstyles.org
*/ */
function fetchUserstylesAPI(path, queryParams) { const UserStylesAPI = (() => {
return new Promise(function(resolve, reject) { return {fetch}
const TIMEOUT = 10000;
const headers = { /**
'Content-type': 'application/json', * Fetches (and JSON-parses) the result from a userstyles.org API
'Accept': '*/*' * @param {string} path Path on userstyles.org (e.g. "/api/v1/styles/search")
}; * @param {string} queryParams Query parameters to send in search request (e.g. "key=value&name=that)".
let url = 'https://userstyles.org' + path; * @return {Object} Response object from userstyles.org
if (queryParams) { */
url += "?" + queryParams; function fetch(path, queryParams) {
} return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest(); const TIMEOUT = 10000;
xhr.timeout = TIMEOUT; const headers = {
xhr.onload = () => { 'Content-type': 'application/json',
if (xhr.status === 200 || url.protocol === 'file:') { 'Accept': '*/*'
try { };
resolve(JSON.parse(xhr.responseText)); let url = 'https://userstyles.org' + path;
} catch (err) { if (queryParams) {
reject("Failed to parse JSON from " + url + "\nJSON Text: " + xhr.responseText); url += "?" + queryParams;
}
const xhr = new XMLHttpRequest();
xhr.timeout = TIMEOUT;
xhr.onload = () => {
if (xhr.status === 200 || url.protocol === 'file:') {
try {
resolve(JSON.parse(xhr.responseText));
} catch (err) {
reject("Failed to parse JSON from " + url + "\nJSON Text: " + xhr.responseText);
}
} else {
reject("Error code " + xhr.status);
} }
} else { };
reject("Error code " + xhr.status); xhr.onerror = reject;
xhr.open('GET', url, true);
for (const key of Object.keys(headers)) {
xhr.setRequestHeader(key, headers[key]);
} }
}; xhr.send();
xhr.onerror = reject; });
xhr.open('GET', url, true);
for (const key of Object.keys(headers)) { }
xhr.setRequestHeader(key, headers[key]); })();
}
xhr.send();
});
}
/** /**
* Adds an entry to the Search Results DOM * Represents the search results within the Stylus popup.
* @param {Object} searchResult The JSON object from userstyles.org representing a search result. * @returns {Object} Includes load(), next(), and prev() methods to alter the search results.
*/ */
function createSearchResultElement(searchResult) { const SearchResults = (() => {
/* let currentPage = 1;
searchResult format: {
id: 100835,
name: "Reddit Flat Dark",
screenshot_url: "19339_after.png",
description: "...",
user: {
id: 48470,
name: "holloh"
}
}
*/
const entry = template.searchResult.cloneNode(true);
Object.assign(entry, {
id: ENTRY_ID_PREFIX_RAW + searchResult.id,
styleId: searchResult.id
});
const title = $('.searchResult-title', entry); return {load, next, prev}
Object.assign(title, {
textContent: searchResult.name,
title: searchResult.name,
href: 'https://userstyles.org' + searchResult.url,
onclick: handleEvent.openURLandHide
});
const screenshot = $('.searchResult-screenshot', entry); /**
let ss_url = searchResult.screenshot_url; * Loads search result for the (page number is currentPage).
if (RegExp(/^[0-9]*_after.(jpe?g|png|gif)$/i).test(ss_url)) { * @param {Object} event The click event
ss_url = 'https://userstyles.org/style_screenshot_thumbnails/' + ss_url; */
} function load(event) {
Object.assign(screenshot, { if (event) event.preventDefault();
src: ss_url, // Clear search results
title: searchResult.name $('#searchResults-list').innerHTML = "";
}); // Find styles for the current active tab
getActiveTab().then(tab => {
$('#load-search-results').classList.add("hidden");
$('#searchResults').classList.remove("hidden");
// TODO: Expand/collapse description const hostname = new URL(tab.url).hostname.replace(/^(?:.*\.)?([^.]*\.(co\.)?[^.]*)$/i, "$1");
const description = $('.searchResult-description', entry); $('#searchResults-terms').textContent = hostname;
Object.assign(description, {
textContent: searchResult.description.replace(/<.*?>/g, ""),
title: searchResult.description.replace(/<.*?>/g, "")
});
const authorLink = $('.searchResult-authorLink', entry); const queryParams = [
Object.assign(authorLink, { 'search=' + encodeURIComponent(hostname),
textContent: searchResult.user.name, 'page=' + currentPage,
title: searchResult.user.name, 'per_page=3'
href: 'https://userstyles.org/users/' + searchResult.user.id, ].join('&');
onclick: handleEvent.openURLandHide UserStylesAPI.fetch("/api/v1/styles/search", queryParams)
}); .then(searchResults => {
// TODO: Total & Weekly Install Counts
// TODO: Rating
const install = $('.searchResult-install', entry);
const name = searchResult.name;
Object.assign(install, {
onclick: (event) => {
event.preventDefault();
// TODO: Install style
fetchUserstylesAPI("/api/v1/styles/" + searchResult.id)
.then(styleObject => {
console.log("TODO: Install style ID", searchResult.id);
console.log("Full styleObject:", styleObject);
/* /*
* Sample full styleObject: https://userstyles.org/api/v1/styles/70271 searchResults: {
* The "id" is the ID of the userstyles.org style (e.g. 70271 above) data: [...],
* saveStyleSafe({...}) expects an "id" referring to the Stylus ID (1-n) current_page: 1,
*/ per_page: 15;
delete styleObject.id; total_pages: 6,
Object.assign(styleObject, { total_entries: 85
enabled: true, }
reason: 'update', */
notify: true if (searchResults.data.length === 0) {
}); throw "No results found";
saveStyleSafe(styleObject); }
alert("TODO: Install style ID #" + searchResult.id + " name '" + searchResult.name + "'"); currentPage = searchResults.current_page;
updateSearchResultsNav(searchResults.current_page, searchResults.total_pages);
searchResults.data.forEach(createSearchResult);
}) })
.catch(reason => { .catch(reason => {
throw reason; $('#load-search-results').classList.remove("hidden");
$('#searchResults').classList.add("hidden");
alert("Error while loading search results: " + reason);
}); });
return true; });
} return true;
}); }
$('#searchResults-list').appendChild(entry); /** Increments currentPage and loads results. */
} function next(event) {
currentPage += 1;
return load(event);
}
function updateSearchResultsNav(currentPage, totalPages) { /** Decrements currentPage and loads results. */
function prev(event) {
currentPage = Math.max(1, currentPage - 1);
return load(event);
}
/** Updates prev/next buttons and currentPage/totalPage labels. */
function updateSearchResultsNav(currentPage, totalPages) {
// Update 'next' button // Update 'next' button
if (currentPage >= totalPages) { if (currentPage >= totalPages) {
currentPage = totalPages; currentPage = totalPages;
@ -154,68 +138,114 @@ function updateSearchResultsNav(currentPage, totalPages) {
// Update current/total counts // Update current/total counts
$('#searchResultsNav-currentPage').textContent = currentPage; $('#searchResultsNav-currentPage').textContent = currentPage;
$('#searchResultsNav-totalPages').textContent = totalPages; $('#searchResultsNav-totalPages').textContent = totalPages;
} }
function processSearchResults(searchResults) { /**
/* * Constructs and adds the given search result to the popup's Search Results container.
searchResults: { * @param {Object} userstyleSearchResult The SearchResult object from userstyles.org
data: [...], */
current_page: 1, function createSearchResult(userstyleSearchResult) {
per_page: 15; /*
total_pages: 6, userstyleSearchResult format: {
total_entries: 85 id: 100835,
name: "Reddit Flat Dark",
screenshot_url: "19339_after.png",
description: "...",
user: {
id: 48470,
name: "holloh"
}
}
*/
// TODO: Check if search result is already installed.
// If so hide it, or mark as installed with an "Uninstall" button.
const entry = template.searchResult.cloneNode(true);
Object.assign(entry, {
id: ENTRY_ID_PREFIX_RAW + userstyleSearchResult.id,
styleId: userstyleSearchResult.id
});
$('#searchResults-list').appendChild(entry);
const title = $('.searchResult-title', entry);
Object.assign(title, {
textContent: userstyleSearchResult.name,
title: userstyleSearchResult.name,
href: 'https://userstyles.org' + userstyleSearchResult.url,
onclick: handleEvent.openURLandHide
});
const screenshot = $('.searchResult-screenshot', entry);
let ss_url = userstyleSearchResult.screenshot_url;
if (RegExp(/^[0-9]*_after.(jpe?g|png|gif)$/i).test(ss_url)) {
ss_url = 'https://userstyles.org/style_screenshot_thumbnails/' + ss_url;
} }
*/ Object.assign(screenshot, {
currentPage = searchResults.current_page; src: ss_url,
updateSearchResultsNav(searchResults.current_page, searchResults.total_pages); title: userstyleSearchResult.name
searchResults.data.forEach(createSearchResultElement); });
}
function loadNextPage(event) { // TODO: Expand/collapse description
currentPage += 1; const description = $('.searchResult-description', entry);
loadSearchResults(event); Object.assign(description, {
} textContent: userstyleSearchResult.description.replace(/<.*?>/g, ""),
title: userstyleSearchResult.description.replace(/<.*?>/g, "")
});
function loadPrevPage(event) { const authorLink = $('.searchResult-authorLink', entry);
currentPage = Math.max(1, currentPage - 1); Object.assign(authorLink, {
loadSearchResults(event); textContent: userstyleSearchResult.user.name,
} title: userstyleSearchResult.user.name,
href: 'https://userstyles.org/users/' + userstyleSearchResult.user.id,
onclick: handleEvent.openURLandHide
});
function loadSearchResults(event) { // TODO: Total & Weekly Install Counts
event.preventDefault(); // TODO: Rating
// Clear search results
$('#searchResults-list').innerHTML = "";
// Find styles for the current active tab
getActiveTab().then(tab => {
const hostname = new URL(tab.url).hostname.replace(/^(?:.*\.)?([^.]*\.(co\.)?[^.]*)$/i, "$1");
const queryParams = [
'search=' + encodeURIComponent(hostname),
'page=' + currentPage,
'per_page=3'
].join('&');
// Hide load button const installButton = $('.searchResult-install', entry);
$('#load-search-results').classList.add("hidden"); const name = userstyleSearchResult.name;
Object.assign(installButton, {
onclick: install
});
// Display results container /** Installs the current userstyleSearchResult into stylus. */
$('#searchResults').classList.remove("hidden"); function install(event) {
$('#searchResults-terms').textContent = hostname; UserStylesAPI.fetch("/api/v1/styles/" + userstyleSearchResult.id)
.then(styleObject => {
console.log("TODO: Install style ID", userstyleSearchResult.id);
console.log("Full styleObject:", styleObject);
/*
* FIXME
* Sample full styleObject: https://userstyles.org/api/v1/styles/70271
* We need to convert this sytleObject into the format expected by saveStyleSafe
* I.e. styleObject.id is the ID of the userstyles.org style (e.g. 70271 above)
*/
fetchUserstylesAPI("/api/v1/styles/search", queryParams) // messaging.js#saveStyleSafe({...}) expects an "id" referring to the Stylus ID (1-n).
.then(code => { delete styleObject.id;
processSearchResults(code);
}) Object.assign(styleObject, {
.catch(reason => { // TODO: Massage styleObject into the format expected by saveStyleSafe
$('#load-search-results').classList.remove("hidden"); enabled: true,
$('#searchResults').classList.add("hidden"); reason: 'update',
alert("Error while loading search results: " + reason); notify: true
}); });
}); saveStyleSafe(styleObject);
return true; alert("TODO: Install style ID #" + userstyleSearchResult.id + " name '" + userstyleSearchResult.name + "'");
} })
.catch(reason => {
console.log("Error during installation:", reason);
alert("Error installing style: " + reason);
});
return true;
}
}
})();
onDOMready().then(() => { onDOMready().then(() => {
$('#load-search-results-link').onclick = loadSearchResults; $('#load-search-results-link').onclick = SearchResults.load;
$('#searchResultsNav-prev').onclick = loadPrevPage; $('#searchResultsNav-prev').onclick = SearchResults.prev;
$('#searchResultsNav-next').onclick = loadNextPage; $('#searchResultsNav-next').onclick = SearchResults.next;
}); });