tilde/index.html
2017-07-10 23:04:57 -07:00

885 lines
22 KiB
HTML

<!doctype html>
<script>
const CONFIG = {
// 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={}'],
],
// 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"
searchDelimiter: ':',
// 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
instantRedirect: false,
// give suggestions as you type
suggestions: true,
// max amount of suggestions that will ever be displayed
suggestionsLimit: 4,
// 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: 2 },
{ name: 'DuckDuckGo', limit: 4 },
],
// open queries in a new tab.
newTab: true,
// the delimiter between the hours and minutes in the clock.
clockDelimiter: '&nbsp;',
};
</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>~</title>
<style type="text/css">
@font-face {
font-family: 'Lato';
src: url('https://fonts.gstatic.com/s/lato/v11/22JRxvfANxSmnAhzbFH8PgLUuEpTyoUstqEm5AMlJo4.woff2') format('woff2');
}
body {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
color: #333;
font-family: 'Lato', sans-serif;
}
main {
position: absolute;
top: 50%;
right: 0;
left: 0;
width: 90%;
max-width: 310px;
margin: 0 auto;
transform: translateY(-100px);
text-align: center;
}
time {
display: block;
margin-bottom: 20px;
font-size: 5rem;
letter-spacing: 6px;
}
input,
button,
input:focus,
button:focus {
display: block;
box-sizing: border-box;
width: 100%;
border: 0;
outline: 0;
background: transparent;
color: #fff;
font-family: 'Lato', sans-serif;
-webkit-appearance: none;
-moz-appearance: none;
}
ul,
li {
margin: 0;
padding: 0;
list-style: none;
}
#search-input,
#search-input:focus {
padding: 12px;
border-radius: 2px;
background: #222;
font-size: 1.1rem;
}
body.suggestions #search-input {
border-radius: 2px 2px 0 0;
}
#search-suggestions {
display: none;
padding: 4px 0;
border-radius: 0 0 2px 2px;
background: #111;
overflow: hidden;
}
body.suggestions #search-suggestions {
display: block;
}
.search-suggestion {
margin: -4px 0;
padding: 10px 12px;
transition: background .2s;
font-size: .8rem;
text-align: left;
cursor: pointer;
}
.search-suggestion:focus,
.search-suggestion.highlight {
background: #333;
}
#help {
position: fixed;
top: 0;
left: 0;
visibility: hidden;
overflow: auto;
box-sizing: border-box;
width: 100%;
height: 100%;
padding: 8vw;
transition: visibility .2s, opacity .2s, transform .4s;
transform: translateY(10px);
opacity: 0;
background: #606c88;
background: -webkit-linear-gradient(to right, #3f4c6b, #606c88);
background: linear-gradient(to right, #3f4c6b, #606c88);
font-size: 1.2rem;
}
body.help #help {
visibility: visible;
transform: translateY(0);
opacity: 1;
}
.category {
width: 100%;
margin-bottom: 3em;
}
.category-name {
margin: 0 0 2em;
color: rgba(255, 255, 255, .6);
font-size: .7em;
letter-spacing: .2em;
text-transform: uppercase;
}
.command a {
display: block;
position: relative;
padding: .5em 0;
color: #fff;
font-size: 1em;
line-height: 2em;
text-decoration: none;
}
.command-key {
display: block;
float: left;
width: 2.5em;
margin-right: 1em;
border-radius: 50%;
background-color: rgba(255, 255, 255, .1);
font-size: .8em;
text-align: center;
}
.command-name {
position: relative;
overflow: hidden;
}
.command-name::after {
content: ' ';
position: absolute;
right: 0;
bottom: -.35em;
left: 0;
height: 2px;
transition: .2s;
transform: translateX(-2em);
background-color: rgba(255, 255, 255, .2);
opacity: 0;
}
.command:hover .command-name::after {
transform: translateX(0);
opacity: 1;
}
@media (min-width: 1000px) {
#help {
display: flex;
justify-content: center;
align-items: center;
padding: 2em;
font-size: 1.3vw;
}
#help>ul {
display: flex;
justify-content: space-around;
width: 100%;
}
.category {
width: 10em;
margin-bottom: 0;
}
}
</style>
<main>
<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="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) || []),
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');
script.src = url;
$.el('head').appendChild(script);
},
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';
}
},
};
class 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);
}
_setTime() {
const date = new Date();
const hours = this._pad(date.getHours());
const minutes = this._pad(date.getMinutes());
this._el.innerHTML = hours + this._delimiter + minutes;
}
_start() {
this._setTime();
setInterval(this._setTime, 1000);
}
}
class Help {
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) {
this._toggled = (typeof show !== 'undefined') ? show : !this._toggled;
this._toggled ? $.bodyClassAdd('help') : $.bodyClassRemove('help');
}
_bindMethods() {
this._handleKeydown = this._handleKeydown.bind(this);
}
_buildAndAppendLists() {
const lists = document.createElement('ul');
for (let name in this._categories) {
lists.insertAdjacentHTML(
'beforeend',
`<li class="category">
<h2 class="category-name">${name}</h2>
<ul>${this._buildListCommands(this._categories[name])}</ul>
</li>`
);
}
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="${this._newTab ? '_blank' : '_self'}">
<span class="command-key">${key}</span>
<span class="command-name">${name}</span>
</a>
</li>`
);
}).join('');
}
_getCommandFromName(commandName) {
return this._commands.filter(([key, name]) => name === commandName)[0];
}
_handleKeydown(e) {
if ($.key(e) === 'escape') this.toggle(false);
}
_registerEvents() {
document.addEventListener('keydown', this._handleKeydown);
}
}
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;
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));
}
getSuggestions(query) {
return new Promise(resolve => {
const suggestions = this._getHistory()
.filter(([item]) => this._itemContainsQuery(query, item))
.slice(0, this._limit)
.map(([item]) => item);
resolve(suggestions);
});
}
_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;
}
_save(history) {
localStorage.setItem(this._storeName, JSON.stringify(history));
}
_setHistory(history) {
this._history = history;
this._save(history);
}
_sort(history) {
return history.sort((current, next) => current[1] - next[1]).reverse();
}
}
class DuckDuckGo extends Influencer {
constructor() {
super(...arguments);
}
getSuggestions(query) {
return new Promise(resolve => {
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}`);
});
}
}
class Suggester {
constructor({ influencers, limit }) {
this._el = $.el('#search-suggestions');
this._influencers = influencers;
this._limit = limit;
this._suggestionEls = [];
this._bindMethods();
this._registerEvents();
}
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) {
input = input.trim();
if (input === '') this._clearSuggestions();
Promise.all(this._getInfluencerPromises(input)).then(res => {
const suggestions = this._flattenAndUnique(res);
if (suggestions.length) {
this._clearSuggestions();
this._appendSuggestions(suggestions, input);
this._registerSuggestionEvents();
$.bodyClassAdd('suggestions');
}
});
}
_appendSuggestions(suggestions, input) {
suggestions.some((suggestion, i) => {
const match = new RegExp($.escapeRegex(input), 'g');
const suggestionHtml = suggestion.replace(match, `<b>${input}</b>`);
this._el.insertAdjacentHTML(
'beforeend',
`<li>
<button
type="button"
class="js-search-suggestion search-suggestion"
data-suggestion="${suggestion}"
tabindex="-1"
>
${suggestionHtml}
</button>
</li>`
);
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._onClick.bind(null, el.value);
el.removeEventListener('click', callback);
});
}
_clearSuggestions() {
$.bodyClassRemove('suggestions');
this._clearClickEvents();
this._suggestionEls = [];
this._el.innerHTML = '';
}
// [[1, 2], [1, 2, 3, 4]] -> [1, 2, 3, 4]
_flattenAndUnique(array) {
return [...new Set([].concat.apply([], array))];
}
_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);
}
_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.getSuggestions(input));
}
_handleKeydown(e) {
if ($.isDown(e)) this._focusNext(e);
if ($.isUp(e)) this._focusPrevious(e);
}
_highlight(el, e) {
this._unHighlight();
if (el) {
this._onHighlight(el.getAttribute('data-suggestion'));
el.classList.add('highlight');
e.preventDefault();
}
}
_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._unHighlight.bind(this));
el.addEventListener('click', this._onClick.bind(null, value));
});
}
_unHighlight(e) {
const el = $.el('.highlight');
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 = this._defaultSearch.replace('{}', encodedQuery);
if (query.match(this._urlRegex)) {
const hasProtocol = query.match(this._protocolRegex);
redirectUrl = hasProtocol ? query : 'http://' + query;
} else {
const splitSearch = query.split(this._searchDelimiter);
const splitPath = query.split(this._pathDelimiter);
this._commands.some(([key, name, url, searchPath]) => {
const isSearch = splitSearch[0] === key;
const isPath = splitPath[0] === key;
if (isSearch || isPath) {
if (splitSearch[1] && searchPath) {
redirectUrl = this._prepSearch(url, searchPath, splitSearch);
} else if (splitPath[1]) {
redirectUrl = this._prepPath(url, splitPath);
} else {
redirectUrl = url;
}
return true;
}
});
}
return redirectUrl;
}
instantRedirect(query, callback) {
let exists;
this._commands.forEach(([key, name, url]) => {
if (key === query) {
callback(url);
exists = true;
}
});
return exists;
}
_prepPath(url, splitPath) {
const path = this._shiftAndTrim(splitPath, this._pathDelimiter);
return this._stripUrlPath(url) + '/' + path;
}
_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) {
arr.shift();
return arr.join(delimiter).trim();
}
_stripUrlPath(url) {
const parser = document.createElement('a');
parser.href = url;
return `${parser.protocol}//${parser.hostname}`;
}
}
class Form {
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._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._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 validChar = newChar.length && $.key(e) !== 'enter';
const queryDiffers = this._inputElVal !== newQuery;
if (validChar) this._help.toggle(false);
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 newQuery = this._inputEl.value;
if (this._suggester && $.isRemove(e) && this._inputElVal !== newQuery) {
this._suggester.suggest(newQuery);
this._inputElVal = newQuery;
}
}
_previewValue(value) {
this._inputEl.value = value;
}
_redirect(redirect) {
if (this._newTab) window.open(redirect, '_blank');
else window.location.href = redirect;
}
_registerEvents() {
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._help.toggle();
} else {
this._suggester.success(query);
this._redirect(this._queryParser.generateRedirect(query));
}
}
_submitWithValue(value) {
this._inputEl.value = value;
this._submitForm();
}
}
</script>
<script>
const getHelp = () => {
return new Help({
categories: CONFIG.categories,
commands: CONFIG.commands,
newTab: CONFIG.newTab,
});
};
const getInfluencers = () => {
const availableInfluencers = {
DuckDuckGo: DuckDuckGo,
History: History,
};
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>