absolutely massive refactor

This commit is contained in:
Cade Scroggins
2017-07-10 23:04:57 -07:00
parent 4db2b0030b
commit 96504778f4
+378 -292
View File
@@ -2,61 +2,63 @@
<script>
const CONFIG = {
categories: [
{ name: "Work", commands: [
{ key: 'g', name: 'GitHub', url: 'https://github.com', search: '/search?q={}' },
{ key: 'm', name: 'Inbox', url: 'https://inbox.google.com', search: '/search/{}' },
{ key: 'k', name: 'Keep', url: 'https://keep.google.com', search: '/#search/text={}' },
] },
{ name: "Lurk", commands: [
{ key: 'i', name: 'Instagram', url: 'https://www.instagram.com', search: false },
{ key: 'r', name: 'Reddit', url: 'https://www.reddit.com', search: '/search?q={}' },
{ key: 't', name: 'Twitter', url: 'https://twitter.com', search: '/search?q={}' },
] },
{ name: "Listen", commands: [
{ key: 'h', name: 'Hypem', url: 'http://hypem.com/popular', search: '/search/{}' },
{ key: 'l', name: 'Line Radio', url: 'https://linerad.io', search: '/#{}' },
{ key: 's', name: 'SoundCloud', url: 'https://soundcloud.com/discover', search: '/search?q={}' },
] },
{ name: "Watch", commands: [
{ key: 'n', name: 'Netflix', url: 'https://www.netflix.com/browse', search: '/search?q={}' },
{ key: 'w', name: 'Twitch', url: 'https://www.twitch.tv/directory/following', search: false },
{ key: 'y', name: 'YouTube', url: 'https://youtube.com/feed/subscriptions', search: '/results?search_query={}' },
] },
{ name: "Download", commands: [
{ key: 'T', name: 'TPB', url: 'https://thepiratebay.org', search: '/search/{}' },
{ key: 'Y', name: 'YIFY', url: 'https://yts.ag/browse-movies/0/1080p/all/7/latest', search: '/browse-movies/{}/1080p/all/0/rating' },
{ key: '7', name: '7digital', url: 'https://us.7digital.com', search: '/search?q={}' },
] },
// the key, name, redirect url and search path for your commands
commands: [
['7', '7digital', 'https://us.7digital.com', '/search?q={}'],
['g', 'GitHub', 'https://github.com', '/search?q={}'],
['h', 'Hypem', 'http://hypem.com/popular', '/search/{}'],
['m', 'Inbox', 'https://inbox.google.com', '/search/{}'],
['i', 'Instagram', 'https://www.instagram.com', false],
['k', 'Keep', 'https://keep.google.com', '/#search/text={}'],
['l', 'Line Radio', 'https://linerad.io', '/#{}'],
['n', 'Netflix', 'https://www.netflix.com/browse', '/search?q={}'],
['r', 'Reddit', 'https://www.reddit.com', '/search?q={}'],
['s', 'SoundCloud', 'https://soundcloud.com/discover', '/search?q={}'],
['T', 'TPB', 'https://thepiratebay.org', '/search/{}'],
['w', 'Twitch', 'https://www.twitch.tv/directory/following', false],
['t', 'Twitter', 'https://twitter.com', '/search?q={}'],
['Y', 'YIFY', 'https://yts.ag/browse-movies/0/1080p/all/7/latest', '/browse-movies/{}/1080p/all/0/rating'],
['y', 'YouTube', 'https://youtube.com/feed/subscriptions', '/results?search_query={}'],
],
// if none of the keys are matched, this is used for searching.
// the categories & commands that show up on the help overlay
// use the exact name of each command
categories: {
'Work': ['GitHub', 'Inbox', 'Keep'],
'Lurk': ['Instagram', 'Reddit', 'Twitter'],
'Listen': ['Hypem', 'Line Radio', 'SoundCloud'],
'Watch': ['Netflix', 'Twitch', 'YouTube'],
'Download': ['7digital', 'TPB', 'YIFY'],
},
// if none of the specified keys are matched, this is used for searching
defaultSearch: 'https://encrypted.google.com/search?q={}',
// the delimiter between the key and your search query.
// e.g. to search GitHub for potatoes you'd type "g:potatoes".
// the delimiter between the key and your search query
// e.g. to search GitHub for potatoes you'd type "g:potatoes"
searchDelimiter: ':',
// the delimiter between the key and a path.
// e.g. type "r/r/unixporn" to go to "reddit.com/r/unixporn".
// the delimiter between the key and a path
// e.g. type "r/r/unixporn" to go to "reddit.com/r/unixporn"
pathDelimiter: '/',
// instantly redirect when a key is matched.
// put a space before any other queries to prevent unwanted redirects.
// instantly redirect when a key is matched
// put a space before any other queries to prevent unwanted redirects
instantRedirect: false,
// give suggestions as you type.
// give suggestions as you type
suggestions: true,
// max amount of suggestions that will ever be displayed.
suggestionsLimit: 6,
// max amount of suggestions that will ever be displayed
suggestionsLimit: 4,
// the order and limit for each suggestion influencer.
// the following would give you 1 suggestion from your search history
// the order and limit for each suggestion influencer
// the following would give you 2 suggestion from your search history
// and 4 suggestions from Duck Duck Go.
influencers: [
{ name: 'History', limit: 1 },
{ name: 'DuckDuckGo', limit: 6 },
{ name: 'History', limit: 2 },
{ name: 'DuckDuckGo', limit: 4 },
],
// open queries in a new tab.
@@ -64,13 +66,6 @@
// the delimiter between the hours and minutes in the clock.
clockDelimiter: '&nbsp;',
// used for determining when to redirect directly to a url.
urlRegex: /^(?:(http|https)?:\/\/)?(?:[\w-]+\.)+([a-z]|[A-Z]|[0-9]){2,6}/i,
// if "urlRegex" matches but this doesn't, "http://" will be
// prepended to the beginning of the query before redirecting.
protocolRegex: /^[a-zA-Z]+:\/\//i
};
</script>
@@ -140,19 +135,19 @@
list-style: none;
}
.search-input,
.search-input:focus {
#search-input,
#search-input:focus {
padding: 12px;
border-radius: 2px;
background: #222;
font-size: 1.1rem;
}
.search-input.bottom-no-radius {
body.suggestions #search-input {
border-radius: 2px 2px 0 0;
}
.search-suggestions {
#search-suggestions {
display: none;
padding: 4px 0;
border-radius: 0 0 2px 2px;
@@ -160,7 +155,7 @@
overflow: hidden;
}
.search-suggestions.active {
body.suggestions #search-suggestions {
display: block;
}
@@ -178,7 +173,7 @@
background: #333;
}
.overlay {
#help {
position: fixed;
top: 0;
left: 0;
@@ -197,7 +192,7 @@
font-size: 1.2rem;
}
.overlay[data-toggled='true'] {
body.help #help {
visibility: visible;
transform: translateY(0);
opacity: 1;
@@ -261,7 +256,7 @@
}
@media (min-width: 1000px) {
.overlay {
#help {
display: flex;
justify-content: center;
align-items: center;
@@ -269,7 +264,7 @@
font-size: 1.3vw;
}
.lists {
#help>ul {
display: flex;
justify-content: space-around;
width: 100%;
@@ -283,23 +278,25 @@
</style>
<main>
<time id="js-clock"></time>
<form id="js-search-form" autocomplete="off">
<input id="js-search-input" class="search-input" type="text" autofocus>
<ul id="js-search-suggestions" class="search-suggestions"></ul>
<time id="clock"></time>
<form id="search-form" autocomplete="off">
<input id="search-input" type="text" autofocus>
<ul id="search-suggestions"></ul>
</form>
</main>
<aside id="js-overlay" class="overlay">
<ul id="js-lists" class="lists"></ul>
</aside>
<aside id="help"></aside>
<script>
const $ = {
bodyClassRemove: c => $.el('body').classList.remove(c),
bodyClassAdd: c => $.el('body').classList.add(c),
el: s => document.querySelector(s),
els: s => [].slice.call(document.querySelectorAll(s) || []),
isDown: e => ['c-n', 'down'].includes($.key(e)),
isUp: e => ['c-p', 'up'].includes($.key(e)),
escapeRegex: s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
isDown: e => ['c-n', 'down', 'tab'].includes($.key(e)),
isRemove: e => ['backspace', 'delete'].includes($.key(e)),
isUp: e => ['c-p', 'up', 's-tab'].includes($.key(e)),
jsonp: url => {
let script = document.createElement('script');
@@ -309,12 +306,16 @@
key: e => {
const ctrl = e.ctrlKey;
const shift = e.shiftKey;
switch (e.which) {
case 8: return 'backspace';
case 9: return shift ? 's-tab' : 'tab';
case 13: return 'enter';
case 27: return 'escape';
case 38: return 'up';
case 40: return 'down';
case 46: return 'delete';
case 78: return ctrl ? 'c-n' : 'n';
case 80: return ctrl ? 'c-p' : 'n';
}
@@ -322,21 +323,22 @@
};
class Clock {
constructor() {
this._clockEl = $.el('#js-clock');
constructor({ delimiter }) {
this._el = $.el('#clock');
this._delimiter = delimiter;
this._setTime = this._setTime.bind(this);
this._start();
}
_pad(num) {
return (`0${num.toString()}`).slice(-2);
return ('0' + num.toString()).slice(-2);
}
_setTime() {
const date = new Date();
const hours = this._pad(date.getHours());
const minutes = this._pad(date.getMinutes());
this._clockEl.innerHTML = `${hours}${CONFIG.clockDelimiter}${minutes}`;
this._el.innerHTML = hours + this._delimiter + minutes;
}
_start() {
@@ -346,42 +348,59 @@
}
class Help {
constructor() {
this._overlayEl = $.el('#js-overlay');
this._listsEl = $.el('#js-lists');
this._handleKeydown = this._handleKeydown.bind(this);
constructor({ commands, categories, newTab }) {
this._el = $.el('#help');
this._commands = commands;
this._categories = categories;
this._newTab = newTab;
this._toggled = false;
this._buildAndAppendLists();
this._bindMethods();
this._registerEvents();
}
toggle(show) {
const toggle = (typeof show !== 'undefined') ? show :
this._overlayEl.getAttribute('data-toggled') !== 'true';
this._toggled = (typeof show !== 'undefined') ? show : !this._toggled;
this._toggled ? $.bodyClassAdd('help') : $.bodyClassRemove('help');
}
this._overlayEl.setAttribute('data-toggled', toggle);
_bindMethods() {
this._handleKeydown = this._handleKeydown.bind(this);
}
_buildAndAppendLists() {
CONFIG.categories.forEach(category => {
this._listsEl.insertAdjacentHTML(
const lists = document.createElement('ul');
for (let name in this._categories) {
lists.insertAdjacentHTML(
'beforeend',
`<li class="category">
<h2 class="category-name">${category.name}</h2>
<ul>${this._buildListCommands(category)}</ul>
<h2 class="category-name">${name}</h2>
<ul>${this._buildListCommands(this._categories[name])}</ul>
</li>`
);
});
}
_buildListCommands(category) {
return category.commands.map(({ url, key, name }) => (
this._el.appendChild(lists);
}
_buildListCommands(commandNames) {
return commandNames.map(commandName => {
const [key, name, url] = this._getCommandFromName(commandName);
return (
`<li class="command">
<a href="${url}" target="${CONFIG.newTab ? '_blank' : '_self'}">
<a href="${url}" target="${this._newTab ? '_blank' : '_self'}">
<span class="command-key">${key}</span>
<span class="command-name">${name}</span>
</a>
</li>`
)).join('');
);
}).join('');
}
_getCommandFromName(commandName) {
return this._commands.filter(([key, name]) => name === commandName)[0];
}
_handleKeydown(e) {
@@ -393,147 +412,176 @@
}
}
class History {
constructor(suggestionsLimit = 0) {
this._suggestionsLimit = suggestionsLimit;
this._history = this._getFromStorage('history');
class Influencer {
constructor({ limit }) {
this._limit = limit;
}
addItem() {}
getSuggestions() {}
}
class History extends Influencer {
constructor() {
super(...arguments);
this._storeName = 'history';
}
addItem(query) {
if (query.length < 2) return;
this._updateHistory(query);
this._sortHistory();
this._saveToStorage('history', this._history);
let exists;
const history = this._getHistory().map(([item, count]) => {
const match = item === query;
if (match) exists = true;
return [item, match ? count + 1 : count];
});
if (!exists) history.push([query, 1]);
this._setHistory(this._sort(history));
}
getSuggestionsPromise(query) {
getSuggestions(query) {
return new Promise(resolve => {
const suggestions = this._history
.filter(item => this._itemContainsQuery(query, item[0]))
.slice(0, this._suggestionsLimit)
.map(item => item[0]);
const suggestions = this._getHistory()
.filter(([item]) => this._itemContainsQuery(query, item))
.slice(0, this._limit)
.map(([item]) => item);
resolve(suggestions);
});
}
_getFromStorage(name) {
return JSON.parse(localStorage.getItem(name)) || [];
_fetch() {
return JSON.parse(localStorage.getItem(this._storeName)) || [];
}
_getHistory() {
this._history = this._history || this._fetch();
return this._history;
}
_itemContainsQuery(query, item) {
return query && item.indexOf(query) !== -1;
}
_saveToStorage(name, data) {
localStorage.setItem(name, JSON.stringify(data));
_save(history) {
localStorage.setItem(this._storeName, JSON.stringify(history));
}
_sortHistory() {
this._history = this._history
.sort((current, next) => current[1] - next[1])
.reverse();
_setHistory(history) {
this._history = history;
this._save(history);
}
_updateHistory(query) {
let exists = false;
this._history = this._history.map(item => {
if (item[0] === query) {
item[1]++;
exists = true;
}
return item
});
if (!exists) this._history.push([query, 1]);
_sort(history) {
return history.sort((current, next) => current[1] - next[1]).reverse();
}
}
class DuckDuckGo {
constructor(suggestionsLimit = 0) {
this._endpoint = 'https://duckduckgo.com/ac/';
this._callback = 'autocompleteCallback';
this._suggestionsLimit = suggestionsLimit;
class DuckDuckGo extends Influencer {
constructor() {
super(...arguments);
}
addItem() {}
getSuggestionsPromise(query) {
getSuggestions(query) {
return new Promise(resolve => {
this._resolve = resolve;
window[this._callback] = this._handleResponse.bind(this);
$.jsonp(`${this._endpoint}?callback=${this._callback}&q=${query}`);
const endpoint = 'https://duckduckgo.com/ac/';
const callback = 'autocompleteCallback';
window[callback] = res => {
resolve(res.slice(0, this._limit).map(i => i.phrase));
};
$.jsonp(`${endpoint}?callback=${callback}&q=${query}`);
});
}
_handleResponse(res) {
const suggestions = res.slice(0, this._suggestionsLimit)
.map(i => i.phrase);
this._resolve(suggestions);
}
}
class Suggester {
constructor(influencers) {
this._inputEl = $.el('#js-search-input');
this._suggestionsEl = $.el('#js-search-suggestions');
this._totalSuggestions = 0;
this._suggestionEls = [];
constructor({ influencers, limit }) {
this._el = $.el('#search-suggestions');
this._influencers = influencers;
this._handleKeydown = this._handleKeydown.bind(this);
document.addEventListener('keydown', this._handleKeydown);
this._limit = limit;
this._suggestionEls = [];
this._bindMethods();
this._registerEvents();
}
add(query) {
setOnClick(callback) {
this._onClick = callback;
}
setOnHighlight(callback) {
this._onHighlight = callback;
}
setOnUnhighlight(callback) {
this._onUnhighlight = callback;
}
success(query) {
this._clearSuggestions();
this._influencers.forEach(i => i.addItem(query));
}
suggest(input, clickCallback = () => {}) {
if (!input) {
suggest(input) {
input = input.trim();
if (input === '') this._clearSuggestions();
Promise.all(this._getInfluencerPromises(input)).then(res => {
const suggestions = this._flattenAndUnique(res);
if (suggestions.length) {
this._clearSuggestions();
return;
this._appendSuggestions(suggestions, input);
this._registerSuggestionEvents();
$.bodyClassAdd('suggestions');
}
});
}
this._handleClick = clickCallback;
this._suggest(input);
}
_appendSuggestions(suggestions, input) {
suggestions.some((suggestion, i) => {
const match = new RegExp($.escapeRegex(input), 'g');
const suggestionHtml = suggestion.replace(match, `<b>${input}</b>`);
_appendSuggestion(suggestion, input) {
const suggestionHtml = suggestion
.replace(new RegExp(input, 'g'), `<b>${input}</b>`);
this._suggestionsEl.insertAdjacentHTML(
this._el.insertAdjacentHTML(
'beforeend',
`<li>
<button
type="button"
class="js-search-suggestion search-suggestion"
data-suggestion="${suggestion}"
tabindex="-1"
>
${suggestionHtml}
</button>
</li>`
);
this._showSuggestions();
return ++this._totalSuggestions === CONFIG.suggestionsLimit;
return i + 1 >= this._limit;
});
this._suggestionEls = $.els('.js-search-suggestion');
}
_bindMethods() {
this._handleKeydown = this._handleKeydown.bind(this);
}
_clearClickEvents() {
this._suggestionEls.forEach(el => {
const callback = this._handleClick.bind(null, el.value);
const callback = this._onClick.bind(null, el.value);
el.removeEventListener('click', callback);
});
}
_clearSuggestions() {
this._hideSuggestions();
$.bodyClassRemove('suggestions');
this._clearClickEvents();
this._suggestionsEl.innerHTML = '';
this._totalSuggestions = 0;
this._suggestionEls = [];
this._el.innerHTML = '';
}
// [[1, 2], [1, 2, 3, 4]] -> [1, 2, 3, 4]
@@ -541,113 +589,104 @@
return [...new Set([].concat.apply([], array))];
}
_focusNext() {
const active = $.el('.highlight');
if (active) {
this._suggestionEls.forEach((el, index) => {
const next = this._suggestionEls[index + 1];
if (el === active && next) this._highlight(next);
});
} else {
this._highlight(this._suggestionEls[0]);
}
}
_focusPrevious() {
const active = $.el('.highlight');
if (active) {
this._suggestionEls.forEach((el, index) => {
if (el === active) {
const previous = this._suggestionEls[index - 1];
this._noHighlight();
if (previous) this._highlight(previous);
_focusNext(e) {
const exists = this._suggestionEls.some((el, i) => {
if (el.classList.contains('highlight')) {
this._highlight(this._suggestionEls[i + 1], e);
return true;
}
});
}
if (!exists) this._highlight(this._suggestionEls[0], e);
}
_gatherInfluencers(input) {
_focusPrevious(e) {
const exists = this._suggestionEls.some((el, i) => {
if (el.classList.contains('highlight') && i) {
this._highlight(this._suggestionEls[i - 1], e);
return true;
}
});
if (!exists) this._unHighlight(e);
}
_getInfluencerPromises(input) {
return this._influencers
.map(influencer => influencer.getSuggestionsPromise(input));
.map(influencer => influencer.getSuggestions(input));
}
_handleKeydown(e) {
if ($.isDown(e) || $.isUp(e)) e.preventDefault();
if ($.isDown(e)) this._focusNext();
if ($.isUp(e)) this._focusPrevious();
if ($.isDown(e)) this._focusNext(e);
if ($.isUp(e)) this._focusPrevious(e);
}
_highlight(el) {
this._noHighlight();
_highlight(el, e) {
this._unHighlight();
if (el) {
this._onHighlight(el.getAttribute('data-suggestion'));
el.classList.add('highlight');
this._inputEl.value = el.getAttribute('data-suggestion');
this._inputEl.focus()
e.preventDefault();
}
_noHighlight() {
this._inputEl.value = this._originalValue;
this._suggestionEls.forEach(el => el.classList.remove('highlight'));
}
_showSuggestions() {
this._inputEl.classList.add('bottom-no-radius');
this._suggestionsEl.classList.add('active');
}
_hideSuggestions() {
this._inputEl.classList.remove('bottom-no-radius');
this._suggestionsEl.classList.remove('active');
}
_registerEvents() {
document.addEventListener('keydown', this._handleKeydown);
}
_registerSuggestionEvents() {
this._suggestionEls.forEach(el => {
const value = el.getAttribute('data-suggestion');
el.addEventListener('mouseover', this._highlight.bind(this, el));
el.addEventListener('mouseout', this._noHighlight.bind(this));
el.addEventListener('click', this._handleClick.bind(null, value));
el.addEventListener('mouseout', this._unHighlight.bind(this));
el.addEventListener('click', this._onClick.bind(null, value));
});
}
_suggest(input) {
this._originalValue = this._inputEl.value;
_unHighlight(e) {
const el = $.el('.highlight');
Promise.all(this._gatherInfluencers(input)).then(res => {
this._clearSuggestions();
this._flattenAndUnique(res)
.some(item => this._appendSuggestion(item, input));
this._suggestionEls = $.els('.js-search-suggestion');
this._registerEvents();
});
if (el) {
this._onUnhighlight();
el.classList.remove('highlight');
if (e) e.preventDefault();
}
}
}
class QueryParser {
constructor({ commands, defaultSearch, pathDelimiter, searchDelimiter }) {
this._commands = commands;
this._defaultSearch = defaultSearch;
this._searchDelimiter = searchDelimiter;
this._pathDelimiter = pathDelimiter;
this._protocolRegex = /^[a-zA-Z]+:\/\//i;
this._urlRegex = /^(?:(http|https)?:\/\/)?(?:[\w-]+\.)+([a-z]|[A-Z]|[0-9]){2,6}/i;
}
generateRedirect(query) {
const encodedQuery = encodeURIComponent(query);
let redirectUrl = CONFIG.defaultSearch.replace('{}', encodedQuery);
let redirectUrl = this._defaultSearch.replace('{}', encodedQuery);
if (query.match(CONFIG.urlRegex)) {
const hasProtocol = query.match(CONFIG.protocolRegex);
if (query.match(this._urlRegex)) {
const hasProtocol = query.match(this._protocolRegex);
redirectUrl = hasProtocol ? query : 'http://' + query;
} else {
const splitSearch = query.split(CONFIG.searchDelimiter);
const splitPath = query.split(CONFIG.pathDelimiter);
const splitSearch = query.split(this._searchDelimiter);
const splitPath = query.split(this._pathDelimiter);
this._loopThroughCommands(command => {
const isSearch = splitSearch[0] === command.key;
const isPath = splitPath[0] === command.key;
this._commands.some(([key, name, url, searchPath]) => {
const isSearch = splitSearch[0] === key;
const isPath = splitPath[0] === key;
if (isSearch || isPath) {
if (splitSearch[1] && command.search) {
redirectUrl = this._prepSearch(command, splitSearch);
if (splitSearch[1] && searchPath) {
redirectUrl = this._prepSearch(url, searchPath, splitSearch);
} else if (splitPath[1]) {
redirectUrl = this._prepPath(command, splitPath);
redirectUrl = this._prepPath(url, splitPath);
} else {
redirectUrl = command.url;
redirectUrl = url;
}
return true;
@@ -658,35 +697,31 @@
return redirectUrl;
}
instantRedirect(keypressEvent, query, callback) {
this._loopThroughCommands(command => {
if (command.key === query) {
keypressEvent.preventDefault();
callback(command.url);
instantRedirect(query, callback) {
let exists;
this._commands.forEach(([key, name, url]) => {
if (key === query) {
callback(url);
exists = true;
}
});
return exists;
}
_loopThroughCommands(callback) {
CONFIG.categories
.map(category => category.commands)
.forEach(commands => commands.forEach(command => {
if (callback(command)) return;
}));
_prepPath(url, splitPath) {
const path = this._shiftAndTrim(splitPath, this._pathDelimiter);
return this._stripUrlPath(url) + '/' + path;
}
_prepPath(command, query) {
const baseUrl = this._stripUrlPath(command.url);
const path = this._shiftAndTrim(query, CONFIG.pathDelimiter);
return `${baseUrl}/${path}`;
}
_prepSearch(command, query) {
if (!command.search) return command.url;
const baseUrl = this._stripUrlPath(command.url);
const search = this._shiftAndTrimAndEncode(query);
const searchPath = command.search.replace('{}', search);
return `${baseUrl}${searchPath}`;
_prepSearch(url, searchPath, splitSearch) {
if (!searchPath) return url;
const baseUrl = this._stripUrlPath(url);
const query = this._shiftAndTrim(splitSearch, this._searchDelimiter);
const urlQuery = encodeURIComponent(query);
searchPath = searchPath.replace('{}', urlQuery);
return baseUrl + searchPath;
}
_shiftAndTrim(arr, delimiter) {
@@ -694,11 +729,6 @@
return arr.join(delimiter).trim();
}
_shiftAndTrimAndEncode(arr) {
const clean = this._shiftAndTrim(arr, CONFIG.searchDelimiter);
return encodeURIComponent(clean);
}
_stripUrlPath(url) {
const parser = document.createElement('a');
parser.href = url;
@@ -707,73 +737,93 @@
}
class Form {
constructor(help, suggester, queryParser) {
constructor({ help, instantRedirect, newTab, suggester, queryParser }) {
this._formEl = $.el('#search-form');
this._inputEl = $.el('#search-input');
this._help = help;
this._suggester = suggester;
this._queryParser = queryParser;
this._formEl = $.el('#js-search-form');
this._inputEl = $.el('#js-search-input');
this._instantRedirect = instantRedirect;
this._newTab = newTab;
this._inputElVal = '';
this._bindMethods();
this._registerEvents();
}
_bindMethods() {
this._clearPreview = this._clearPreview.bind(this);
this._handleKeypress = this._handleKeypress.bind(this);
this._submitForm = this._submitForm.bind(this);
this._handleKeyup = this._handleKeyup.bind(this);
this._previewValue = this._previewValue.bind(this);
this._submitForm = this._submitForm.bind(this);
this._submitWithValue = this._submitWithValue.bind(this);
}
_clearInput() {
this._inputEl.value = '';
this._inputElVal = '';
}
_clearPreview() {
this._inputEl.value = this._inputElVal;
this._inputEl.focus();
}
_handleKeypress(e) {
const newChar = String.fromCharCode(e.which);
const newQuery = this._inputEl.value + newChar;
const isNotEmpty = newChar.length;
const validChar = newChar.length && $.key(e) !== 'enter';
const queryDiffers = this._inputElVal !== newQuery;
if (isNotEmpty && $.key(e) !== 'enter') {
this._help.toggle(false);
this._inputEl.focus();
}
if (validChar) this._help.toggle(false);
if (CONFIG.instantRedirect) {
this._queryParser
.instantRedirect(e, newQuery, this._submitWithValue);
if (
this._instantRedirect &&
this._queryParser.instantRedirect(newQuery, this._submitWithValue)
) {
e.preventDefault();
} else if (this._suggester && validChar && queryDiffers) {
this._suggester.suggest(newQuery);
this._inputElVal = newQuery;
}
}
_handleKeyup(e) {
const oldVal = this._inputElVal;
const newVal = this._inputEl.value.trim();
const ignored = $.isDown(e) || $.isUp(e);
this._inputElVal = newVal;
const newQuery = this._inputEl.value;
if (CONFIG.suggestions && oldVal !== newVal && !ignored) {
this._suggester.suggest(newVal, this._submitWithValue);
if (this._suggester && $.isRemove(e) && this._inputElVal !== newQuery) {
this._suggester.suggest(newQuery);
this._inputElVal = newQuery;
}
}
_previewValue(value) {
this._inputEl.value = value;
}
_redirect(redirect) {
if (CONFIG.newTab) window.open(redirect, '_blank');
if (this._newTab) window.open(redirect, '_blank');
else window.location.href = redirect;
}
_registerEvents() {
document.addEventListener('keypress', this._handleKeypress);
this._inputEl.addEventListener('keypress', this._handleKeypress);
this._inputEl.addEventListener('keyup', this._handleKeyup);
this._formEl.addEventListener('submit', this._submitForm, false);
this._suggester.setOnClick(this._submitWithValue);
this._suggester.setOnHighlight(this._previewValue);
this._suggester.setOnUnhighlight(this._clearPreview);
}
_submitForm(e) {
if (e) e.preventDefault();
const query = this._inputEl.value.trim();
this._clearInput();
if (!query || query === '?') {
this._inputEl.value = '';
this._help.toggle();
} else {
this._suggester.add(query);
this._suggester.suggest('');
this._inputEl.value = '';
this._suggester.success(query);
this._redirect(this._queryParser.generateRedirect(query));
}
}
@@ -786,14 +836,50 @@
</script>
<script>
const clock = new Clock();
const help = new Help();
const influencers = { History: History, DuckDuckGo: DuckDuckGo };
const getHelp = () => {
return new Help({
categories: CONFIG.categories,
commands: CONFIG.commands,
newTab: CONFIG.newTab,
});
};
const suggester = new Suggester(
CONFIG.influencers.map(i => new influencers[i.name](i.limit))
);
const getInfluencers = () => {
const availableInfluencers = {
DuckDuckGo: DuckDuckGo,
History: History,
};
const parser = new QueryParser();
const form = new Form(help, suggester, parser);
return CONFIG.influencers.map(i => {
return new availableInfluencers[i.name]({ limit: i.limit });
});
};
const getSuggester = () => {
return new Suggester({
influencers: getInfluencers(),
limit: CONFIG.suggestionsLimit,
});
};
const getQueryParser = () => {
return new QueryParser({
commands: CONFIG.commands,
defaultSearch: CONFIG.defaultSearch,
pathDelimiter: CONFIG.pathDelimiter,
searchDelimiter: CONFIG.searchDelimiter,
});
};
new Clock({
delimiter: CONFIG.clockDelimiter,
});
new Form({
help: getHelp(),
instantRedirect: CONFIG.instantRedirect,
newTab: CONFIG.newTab,
queryParser: getQueryParser(),
suggester: CONFIG.suggestions ? getSuggester() : false,
});
</script>