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,14 +1,19 @@
'use strict'; 'use strict';
let currentPage = 1; /**
* Library for interacting with userstyles.org
* @returns {Object} Includes fetch() method which promises userstyles.org resources.
*/
const UserStylesAPI = (() => {
return {fetch}
/** /**
* Fetches JSON object from userstyles.org API * Fetches (and JSON-parses) the result from a userstyles.org API
* @param {string} path Path on userstyles.org (e.g. /api/v1/styles) * @param {string} path Path on userstyles.org (e.g. "/api/v1/styles/search")
* @param {string} queryParams Query parameters to send in search request. * @param {string} queryParams Query parameters to send in search request (e.g. "key=value&name=that)".
* @return {Object} API response object from userstyles.org * @return {Object} Response object from userstyles.org
*/ */
function fetchUserstylesAPI(path, queryParams) { function fetch(path, queryParams) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
const TIMEOUT = 10000; const TIMEOUT = 10000;
const headers = { const headers = {
@ -39,101 +44,80 @@ function fetchUserstylesAPI(path, queryParams) {
} }
xhr.send(); 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;
return {load, next, prev}
/**
* Loads search result for the (page number is currentPage).
* @param {Object} event The click event
*/
function load(event) {
if (event) event.preventDefault();
// Clear search results
$('#searchResults-list').innerHTML = "";
// Find styles for the current active tab
getActiveTab().then(tab => {
$('#load-search-results').classList.add("hidden");
$('#searchResults').classList.remove("hidden");
const hostname = new URL(tab.url).hostname.replace(/^(?:.*\.)?([^.]*\.(co\.)?[^.]*)$/i, "$1");
$('#searchResults-terms').textContent = hostname;
const queryParams = [
'search=' + encodeURIComponent(hostname),
'page=' + currentPage,
'per_page=3'
].join('&');
UserStylesAPI.fetch("/api/v1/styles/search", queryParams)
.then(searchResults => {
/* /*
searchResult format: { searchResults: {
id: 100835, data: [...],
name: "Reddit Flat Dark", current_page: 1,
screenshot_url: "19339_after.png", per_page: 15;
description: "...", total_pages: 6,
user: { total_entries: 85
id: 48470,
name: "holloh"
}
} }
*/ */
const entry = template.searchResult.cloneNode(true); if (searchResults.data.length === 0) {
Object.assign(entry, { throw "No results found";
id: ENTRY_ID_PREFIX_RAW + searchResult.id,
styleId: searchResult.id
});
const title = $('.searchResult-title', entry);
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;
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: searchResult.name searchResults.data.forEach(createSearchResult);
});
// TODO: Expand/collapse description
const description = $('.searchResult-description', entry);
Object.assign(description, {
textContent: searchResult.description.replace(/<.*?>/g, ""),
title: searchResult.description.replace(/<.*?>/g, "")
});
const authorLink = $('.searchResult-authorLink', entry);
Object.assign(authorLink, {
textContent: searchResult.user.name,
title: searchResult.user.name,
href: 'https://userstyles.org/users/' + searchResult.user.id,
onclick: handleEvent.openURLandHide
});
// 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
* The "id" is the ID of the userstyles.org style (e.g. 70271 above)
* saveStyleSafe({...}) expects an "id" referring to the Stylus ID (1-n)
*/
delete styleObject.id;
Object.assign(styleObject, {
enabled: true,
reason: 'update',
notify: true
});
saveStyleSafe(styleObject);
alert("TODO: Install style ID #" + searchResult.id + " name '" + searchResult.name + "'");
}) })
.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);
} }
/** 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) { function updateSearchResultsNav(currentPage, totalPages) {
// Update 'next' button // Update 'next' button
if (currentPage >= totalPages) { if (currentPage >= totalPages) {
@ -156,66 +140,112 @@ function updateSearchResultsNav(currentPage, totalPages) {
$('#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.
* @param {Object} userstyleSearchResult The SearchResult object from userstyles.org
*/
function createSearchResult(userstyleSearchResult) {
/* /*
searchResults: { userstyleSearchResult format: {
data: [...], id: 100835,
current_page: 1, name: "Reddit Flat Dark",
per_page: 15; screenshot_url: "19339_after.png",
total_pages: 6, description: "...",
total_entries: 85 user: {
id: 48470,
name: "holloh"
}
} }
*/ */
currentPage = searchResults.current_page;
updateSearchResultsNav(searchResults.current_page, searchResults.total_pages); // TODO: Check if search result is already installed.
searchResults.data.forEach(createSearchResultElement); // 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, {
src: ss_url,
title: userstyleSearchResult.name
});
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, {
// TODO: Massage styleObject into the format expected by saveStyleSafe
enabled: true,
reason: 'update',
notify: true
});
saveStyleSafe(styleObject);
alert("TODO: Install style ID #" + userstyleSearchResult.id + " name '" + userstyleSearchResult.name + "'");
}) })
.catch(reason => { .catch(reason => {
$('#load-search-results').classList.remove("hidden"); console.log("Error during installation:", reason);
$('#searchResults').classList.add("hidden"); alert("Error installing style: " + reason);
alert("Error while loading search results: " + reason);
});
}); });
return true; 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;
}); });