tilde/index.html
2021-01-08 16:22:55 +05:30

1416 lines
35 KiB
HTML

<!DOCTYPE html>
<script>
const CONFIG = {
/**
* The category, name, key, url, search path and color for your commands.
* If none of the specified keys are matched, the '*' key is used.
* Commands without a category don't show up in the help menu.
*/
commands: [
{
name: 'DuckDuckGo',
key: '*',
url: 'https://duckduckgo.com',
search: '?q={}',
color: '#222328',
},
{
category: 'Google',
name: 'Mail',
key: 'm',
url: 'https://mail.google.com/mail/u/0',
search: '/mail/u/0/?q={}#search/{}',
color: 'linear-gradient(135deg, #4249f4, #4289f4)',
},
{
category: 'Google',
name: 'Drive',
key: 'd',
url: 'https://drive.google.com/drive/u/0/my-drive',
search: '/drive/u/0/search?q={}',
color: 'linear-gradient(135deg, #34a853, #34a893)',
},
{
category: 'Google',
name: 'Keep',
key: 'k',
url: 'https://keep.google.com/u/0',
search: '/u/0/#search/text={}',
color: 'linear-gradient(135deg, #ec9540, #ecc040)',
},
{
category: 'Google',
name: 'Cal',
key: 'c',
url: 'https://calendar.google.com/calendar/u/0/r',
search: '/calendar/u/0/r/search?q={}',
color: 'linear-gradient(135deg, #E44134, #E48134)',
},
{
category: 'Work',
name: 'Slack',
key: 's',
url: 'https://app.slack.com/client/T09M5UWSV',
color: 'linear-gradient(135deg, #6e7adc, #6ebadc)',
},
{
category: 'Work',
name: 'AND.CO',
key: '.',
url: 'https://app.and.co/timers',
color: 'linear-gradient(135deg, #1773aa, #17b3aa)',
},
{
category: 'Work',
name: 'Notion',
key: 'n',
url: 'https://www.notion.so',
color: 'linear-gradient(135deg, #E16259, #E1a259)',
},
{
category: 'Work',
name: 'Asana',
key: 'a',
url: 'https://app.asana.com/0/inbox/490539250066176',
color: 'linear-gradient(135deg, #0a9fc0, #0adfc0)',
},
{
category: 'Design',
name: 'Figma',
key: 'f',
url: 'https://www.figma.com/files/recent',
color: 'linear-gradient(135deg, #9762F6, #97a2F6)',
},
{
category: 'Design',
name: 'Dribbble',
key: 'b',
url: 'https://dribbble.com/shots/recent',
search: '/search/{}',
color: 'linear-gradient(135deg, #f042ac, #f082ac)',
},
{
category: 'Design',
name: 'UXDB',
key: 'ux',
url: 'https://www.uxdatabase.io/product-database',
color: '#000',
},
{
category: 'Code',
name: 'AWS',
key: 'A',
url: 'https://console.aws.amazon.com',
color: 'linear-gradient(135deg, #ff6400, #ffa400)',
},
{
category: 'Code',
name: 'GitHub',
key: 'g',
url: 'https://github.com',
search: '/search?q={}',
color: 'linear-gradient(135deg, #478B47, #478B87)',
},
{
category: 'Code',
name: 'MDN',
key: 'M',
url: 'https://developer.mozilla.org/en-US',
search: '/en-US/search?q={}',
color: 'linear-gradient(135deg, #5987a6, #59c7a6)',
},
{
category: 'Code',
name: 'Local',
key: '0',
url: 'http://localhost:3000',
search: ':{}',
},
{
category: 'Lurk',
name: 'Reddit',
key: 'r',
url: 'https://www.reddit.com',
search: '/search?q={}',
color: 'linear-gradient(135deg, #5f3dcf, #5f7dcf)',
},
{
category: 'Lurk',
name: 'Unsplash',
key: 'u',
url: 'https://unsplash.com/images',
search: '/search/{}',
color: '#000',
},
{
category: 'Lurk',
name: 'Hunt',
key: 'p',
url: 'https://www.producthunt.com',
search: '/search?q={}',
color: 'linear-gradient(135deg, #da552f, #da952f)',
},
{
category: 'Listen',
name: 'Spotify',
key: 'sp',
url: 'https://open.spotify.com',
search: '/search/{}',
color: 'linear-gradient(135deg, #1DB954, #1DB994)',
},
{
category: 'Listen',
name: 'SoundCloud',
key: 'sc',
url: 'https://soundcloud.com/discover',
search: '/search?q={}',
color: 'linear-gradient(135deg, #ff8800, #ffc800)',
},
{
category: 'Listen',
name: 'Hypem',
key: 'hy',
url: 'https://hypem.com/popular',
search: '/search/{}',
color: 'linear-gradient(135deg, #628441, #628481)',
},
{
category: 'Watch',
name: 'Netflix',
key: 'ne',
url: 'https://www.netflix.com/browse',
search: '/search?q={}',
color: 'linear-gradient(135deg, #e50914, #fe3914)',
},
{
category: 'Watch',
name: 'YouTube',
key: 'yo',
url: 'https://youtube.com/feed/subscriptions',
search: '/results?search_query={}',
color: 'linear-gradient(135deg, #fd201f, #cd301f)',
},
{
category: 'Watch',
name: 'Twitch',
key: 'tw',
url: 'https://www.twitch.tv/directory/following',
color: 'linear-gradient(135deg, #6441a5, #6461c5)',
},
],
/**
* Get suggestions as you type.
*/
suggestions: true,
suggestionsLimit: 4,
/**
* The order and limit for each suggestion influencer. An "influencer" is
* just a suggestion source. The following influencers are available:
*
* - "Default" suggestions come from CONFIG.defaultSuggestions (sync)
* - "History" suggestions come from your previously entered queries (sync)
* - "DuckDuckGo" suggestions come from the duck duck go search api (async)
*/
influencers: [
{ name: 'Default', limit: 4 },
{ name: 'DuckDuckGo', limit: 4 },
],
/**
* If true, suggestions aren't updated until all async influencers resolve.
* If false, synchronous suggestions display immediately, and async
* suggestions are appended. This is useful on high-latency networks.
*/
asyncInfluencersAreBlocking: false,
/**
* Default search suggestions for the specified queries.
*/
defaultSuggestions: {
'.': ['./inout/in/invoices/create'],
0: ['0:8000', '0:8080'],
b: ['b/shots/popular'],
c: ['c/calendar/u/1/r', 'c/calendar/u/2/r'],
d: ['d/drive/u/1/my-drive', 'd/drive/u/2/my-drive'],
g: ['g/ossu'],
k: ['k/u/1', 'k/u/2'],
m: ['m/mail/u/1', 'm/mail/u/2'],
r: ['r/r/startpages', 'r/r/listentothis'],
s: ['s/client/T7K3RFA1M', 's/client/T018S4TL7CP'],
sc: ['sc/you/likes', 'sc/discover/the-upload'],
},
/**
* Instantly redirect when a key is matched. Put a space before any other
* queries to prevent unwanted redirects.
*/
instantRedirect: false,
/**
* Open triggered queries in a new tab.
*/
newTab: true,
/**
* Use command colors when domains are matched and on the help page.
*/
colors: true,
/**
* The delimiter between a command key and your search query. For example,
* to search GitHub for potatoes, you'd type "g:potatoes".
*/
searchDelimiter: ':',
/**
* The delimiter between a command key and a path. For example, you'd type
* "r/r/unixporn" to go to "https://reddit.com/r/unixporn".
*/
pathDelimiter: '/',
/**
* The delimiter between the hours and minutes on the clock.
*/
clockDelimiter: ' ',
/**
* Show a twenty-four-hour clock instead of a twelve-hour clock with AM/PM.
*/
twentyFourHourClock: true,
/**
* Action to take when the clock is clicked. Options include:
*
* - "Menu" to show the help menu
* - "Search" to show the search input
*/
clockAction: 'Menu',
};
</script>
<style type="text/css">
:root {
/* colors */
--background: #fffef8;
--foreground: #222328;
--foregroundSubtle: #525358;
--searchBackground: #222328;
--searchForeground: #fffef8;
/* fonts */
--font-family: Lato, sans-serif;
--base-font-size: 18px;
--font-weight-normal: 400;
--font-weight-bold: 700;
}
/* to download a different font locally:
https://google-webfonts-helper.herokuapp.com/fonts */
@font-face {
font-family: Lato;
font-style: normal;
font-weight: 400;
font-display: swap;
src: local('Lato Regular'), local('Lato-Regular'),
url('./fonts/lato-v14-latin-regular.woff2') format('woff2'),
url('./fonts/lato-v14-latin-regular.woff') format('woff');
}
@font-face {
font-family: Lato;
font-style: normal;
font-weight: 900;
font-display: swap;
src: local('Lato Black'), local('Lato-Black'),
url('./fonts/lato-v14-latin-900.woff2') format('woff2'),
url('./fonts/lato-v14-latin-900.woff') format('woff');
}
</style>
<style type="text/css">
* {
box-sizing: border-box;
}
html {
font-family: var(--font-family);
font-size: var(--base-font-size);
font-weight: var(--font-weight-normal);
}
body {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
transition: background 0.2s;
background: var(--background);
color: var(--foreground);
}
input,
button {
display: block;
width: 100%;
margin: 0;
padding: 0;
background: transparent;
color: inherit;
font-family: var(--font-family);
font-size: 1rem;
}
input,
button,
input:focus,
button:focus {
border: 0;
outline: 0;
-webkit-appearance: none;
-moz-appearance: none;
}
ul,
li {
margin: 0;
padding: 0;
list-style: none;
}
a,
a:focus {
color: inherit;
outline: 0;
}
.center {
display: flex;
width: 100%;
height: 100%;
}
.center > * {
margin: auto;
}
.overlay {
position: fixed;
top: 0;
left: 0;
overflow: auto;
width: 100%;
height: 100%;
visibility: hidden;
}
.clock {
display: block;
font-size: 4rem;
letter-spacing: 0.05rem;
cursor: pointer;
}
.am-pm {
font-size: 1rem;
letter-spacing: 0.1rem;
}
.search-form {
background: var(--searchBackground);
color: var(--searchForeground);
z-index: 2;
}
.search-form > div {
width: 100%;
}
.search-input {
width: 100%;
padding: 0 1rem;
margin-bottom: 20px;
font-size: 1.5rem;
font-weight: var(--font-weight-bold);
letter-spacing: 0.125rem;
text-transform: uppercase;
}
.search-suggestions {
display: none;
justify-content: center;
flex-direction: column;
flex-wrap: wrap;
overflow: hidden;
}
body.suggestions .search-suggestions {
display: flex;
}
.search-suggestion {
padding: 0.75rem 1rem;
border-radius: 2px;
text-align: left;
white-space: nowrap;
cursor: pointer;
}
.search-suggestion.highlight {
background: var(--searchForeground);
color: var(--searchBackground);
}
.search-suggestion b {
position: relative;
font-weight: var(--font-weight-normal);
}
.search-suggestion b::after {
content: ' ';
height: 0.4rem;
position: absolute;
right: 0;
bottom: 0.05rem;
left: 0;
background: var(--searchForeground);
opacity: 0.4;
}
.search-suggestion.highlight b::after {
opacity: 0;
}
.help {
padding: 3rem;
background: var(--background);
z-index: 1;
}
.category {
padding: 1.75rem 2.25rem;
vertical-align: text-top;
break-inside: avoid-column;
}
.category-name {
margin-bottom: 1rem;
font-size: 0.75rem;
font-weight: var(--font-weight-bold);
letter-spacing: 0.125rem;
text-transform: uppercase;
}
.command a {
display: flex;
align-items: center;
position: relative;
width: 100%;
padding: 0.5rem 0;
text-decoration: none;
}
.command-key {
display: block;
flex-shrink: 0;
float: left;
width: 2rem;
height: 2rem;
margin-right: 1rem;
border-radius: 50%;
background: var(--foreground);
color: var(--background);
font-size: 0.8rem;
line-height: 2rem;
text-align: center;
}
.command-name {
position: relative;
color: var(--foregroundSubtle);
}
.command-name::after {
content: ' ';
display: none;
position: absolute;
right: 0;
bottom: 0.05rem;
left: 0;
height: 0.4rem;
transition: 0.2s;
transform: translateX(-2rem);
background: var(--foreground);
opacity: 0;
}
body.help .command-name::after {
display: block;
}
.command a:hover .command-name::after,
.command a:focus .command-name::after {
transform: translateX(0);
opacity: 0.4;
}
body.help .help,
body.form .search-form {
visibility: visible;
}
@media (min-width: 600px) {
.clock {
font-size: 6rem;
}
.search-input {
text-align: center;
}
.search-suggestions {
align-items: center;
}
.categories {
columns: 2;
}
}
@media (min-width: 850px) {
.search-input {
font-size: 2.5rem;
}
.search-suggestions {
flex-direction: row;
}
.categories {
columns: 3;
}
}
@media (min-width: 1100px) {
.categories {
columns: 4;
}
}
</style>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex" />
<title>~</title>
<div class="center"><time class="clock" id="clock"></time></div>
<form
autocomplete="off"
class="center overlay search-form"
id="search-form"
spellcheck="false"
>
<div>
<input class="search-input" id="search-input" title="search" type="text" />
<ul class="search-suggestions" id="search-suggestions"></ul>
</div>
</form>
<aside class="center help overlay" id="help"></aside>
<script>
const $ = {
bodyClassAdd: (c) => $.el('body').classList.add(c),
bodyClassRemove: (c) => $.el('body').classList.remove(c),
el: (s) => document.querySelector(s),
els: (s) => [].slice.call(document.querySelectorAll(s) || []),
escapeRegex: (s) => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
flattenAndUnique: (arr) => [...new Set([].concat.apply([], arr))],
ieq: (a, b) => a.toLowerCase() === b.toLowerCase(),
iin: (a, b) => a.toLowerCase().indexOf(b.toLowerCase()) !== -1,
isDown: (e) => ['ctrl-n', 'down', 'tab'].includes($.key(e)),
isRemove: (e) => ['backspace', 'delete'].includes($.key(e)),
isUp: (e) => ['ctrl-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 meta = e.metaKey;
const shift = e.shiftKey;
switch (e.which) {
case 8:
return 'backspace';
case 9:
return shift ? 's-tab' : 'tab';
case 13:
return 'enter';
case 16:
return 'shift';
case 17:
return 'ctrl';
case 18:
return 'alt';
case 27:
return 'escape';
case 38:
return 'up';
case 40:
return 'down';
case 46:
return 'delete';
case 78:
return ctrl ? 'ctrl-n' : 'n';
case 80:
return ctrl ? 'ctrl-p' : 'p';
case 86:
if (ctrl) return 'ctrl-v';
if (meta) return 'ctrl-v';
break;
case 91:
case 93:
case 224:
return 'meta';
}
if (ctrl) return 'ctrl-*';
if (meta) return 'meta-*';
},
pad: (v) => ('0' + v.toString()).slice(-2),
};
</script>
<script>
class Clock {
constructor(options) {
this._el = $.el('#clock');
this._delimiter = options.delimiter;
this._twentyFourHour = options.twentyFourHour;
this._setTime = this._setTime.bind(this);
this._el.addEventListener('click', options.onClick);
this._start();
}
_setTime() {
const date = new Date();
let hours = $.pad(date.getHours());
let amPm = '';
if (!this._twentyFourHour) {
hours = date.getHours();
if (hours > 12) hours -= 12;
else if (hours === 0) hours = 12;
amPm =
`&nbsp;<span class="am-pm">` +
`${date.getHours() > 12 ? 'PM' : 'AM'}</span>`;
}
const minutes = $.pad(date.getMinutes());
this._el.innerHTML = `${hours}${this._delimiter}${minutes}${amPm}`;
this._el.setAttribute('datetime', date.toTimeString());
}
_start() {
this._setTime();
setInterval(this._setTime, 1000);
}
}
</script>
<script>
class Help {
constructor(options) {
this._el = $.el('#help');
this._colors = options.colors;
this._commands = options.commands;
this._newTab = options.newTab;
this._toggled = false;
this.toggle = this.toggle.bind(this);
this._handleKeydown = this._handleKeydown.bind(this);
this._buildAndAppendLists();
this._registerEvents();
}
toggle(show) {
this._toggled = typeof show !== 'undefined' ? show : !this._toggled;
this._toggled ? $.bodyClassAdd('help') : $.bodyClassRemove('help');
}
_buildAndAppendLists() {
const lists = document.createElement('ul');
lists.classList.add('categories');
this._getCategories().forEach((category) => {
lists.insertAdjacentHTML(
'beforeend',
`<li class="category">
<h2 class="category-name">${category}</h2>
<ul>${this._buildListCommands(category)}</ul>
</li>`
);
});
this._el.appendChild(lists);
}
_buildListCommands(currentCategory) {
return this._commands.reduce(
(acc, { category, color, name, key, url }, i) => {
if (category !== currentCategory) return acc;
return `
${acc}
<li class="command">
<a href="${url}" target="${this._newTab ? '_blank' : '_self'}">
${
this._colors
? `<style>.command-key-${i},.command-name-${i}::after{background:${color};}</style>`
: ''
}
<span class="command-key command-key-${i}">${key}</span>
<span class="command-name command-name-${i}">${name}</span>
</a>
</li>
`;
},
''
);
}
_getCategories() {
const categories = this._commands
.map((v) => v.category)
.filter((category) => category);
return [...new Set(categories)];
}
_handleKeydown(e) {
if ($.key(e) === 'escape') this.toggle(false);
}
_registerEvents() {
document.addEventListener('keydown', this._handleKeydown);
}
}
</script>
<script>
class Influencer {
constructor(options) {
this._limit = options.limit;
this._parseQuery = options.parseQuery;
}
addItem() {}
getSuggestions() {}
_addSearchPrefix(items, query) {
const searchPrefix = this._getSearchPrefix(query);
return items.map((s) => (searchPrefix ? searchPrefix + s : s));
}
_getSearchPrefix(query) {
const { isSearch, key, split } = this._parseQuery(query);
return isSearch ? `${key}${split} ` : false;
}
}
</script>
<script>
class DefaultInfluencer extends Influencer {
constructor({ defaultSuggestions }) {
super(...arguments);
this._defaultSuggestions = defaultSuggestions;
}
getSuggestions(query) {
return new Promise((resolve) =>
resolve((this._defaultSuggestions[query] || []).slice(0, this._limit))
);
}
}
</script>
<script>
class DuckDuckGoInfluencer extends Influencer {
constructor({ queryParser }) {
super(...arguments);
this.isAsync = true;
}
getSuggestions(rawQuery) {
const { query } = this._parseQuery(rawQuery);
if (!query) return Promise.resolve([]);
return new Promise((resolve) => {
const callback = 'autocompleteCallback';
window[callback] = (res) => {
const suggestions = res
.map((i) => i.phrase)
.filter((s) => !$.ieq(s, query))
.slice(0, this._limit);
resolve(this._addSearchPrefix(suggestions, rawQuery));
};
$.jsonp(`https://duckduckgo.com/ac/?callback=${callback}&q=${query}`);
});
}
}
</script>
<script>
class HistoryInfluencer extends Influencer {
constructor() {
super(...arguments);
this._storeName = 'history';
}
static clearHistory() {
localStorage.clear();
}
addItem(query) {
if (query.length < 2) return;
let exists;
const history = this._getHistory().map(([item, count]) => {
const match = $.ieq(item, query);
if (match) exists = true;
return [item, match ? count + 1 : count];
});
if (!exists) history.push([query, 1]);
const sorted = history
.sort((current, next) => current[1] - next[1])
.reverse();
this._setHistory(sorted);
}
getSuggestions(query) {
return new Promise((resolve) =>
resolve(
this._getHistory()
.map(([item]) => item)
.filter(
(item) => query && !$.ieq(item, query) && $.iin(item, query)
)
.slice(0, this._limit)
)
);
}
_fetch() {
return JSON.parse(localStorage.getItem(this._storeName)) || [];
}
_getHistory() {
this._history = this._history || this._fetch();
return this._history;
}
_save(history) {
localStorage.setItem(this._storeName, JSON.stringify(history));
}
_setHistory(history) {
this._history = history;
this._save(history);
}
}
</script>
<script>
class Suggester {
constructor(options) {
this.isAsync = false;
this._el = $.el('#search-suggestions');
this._asyncInfluencersAreBlocking = options.asyncInfluencersAreBlocking;
this._enabled = options.enabled;
this._influencers = options.influencers;
this._limit = options.limit;
this._currentInput = '';
this._currentSuggestions = [];
(this._highlitedSuggestion = null), (this._suggestionEls = []);
this._handleKeydown = this._handleKeydown.bind(this);
this._setSuggestions = this._setSuggestions.bind(this);
this._registerEvents();
}
setOnClick(callback) {
this._onClick = callback;
}
setOnHighlight(callback) {
this._onHighlight = callback;
}
setOnUnhighlight(callback) {
this._onUnhighlight = callback;
}
success(query) {
this._influencers.forEach((i) => i.addItem(query));
this._clearSuggestions();
}
suggest(input) {
if (!this._enabled) return;
this._currentInput = input.trim();
if (!this._currentInput) {
this._clearSuggestions();
return;
}
this._currentSuggestions = [];
if (this._asyncInfluencersAreBlocking) {
Promise.all(this._getInfluencers({ input })).then(this._setSuggestions);
} else {
Promise.all(this._getInfluencers({ input, syncOnly: true })).then(
this._setSuggestions
);
Promise.all(this._getInfluencers({ input, asyncOnly: true })).then(
this._setSuggestions
);
}
}
_buildSuggestionsHtml() {
return this._currentSuggestions
.slice(0, this._limit)
.reduce((acc, suggestion) => {
const match = new RegExp($.escapeRegex(this._currentInput), 'ig');
const matched = suggestion.match(match);
const suggestionHtml = matched
? suggestion.replace(match, `<b>${matched[0]}</b>`)
: suggestion;
return `
${acc}
<li>
<button
type="button"
class="js-search-suggestion search-suggestion"
data-suggestion="${suggestion}"
tabindex="-1"
>
${suggestionHtml}
</button>
</li>
`;
}, '');
}
_clearSuggestionClickEvents() {
this._suggestionEls.forEach((el) => {
el.removeEventListener('click', this._onClick);
});
}
_clearSuggestionHighlightEvents() {
this._suggestionEls.forEach((el) => {
el.removeEventListener('mouseover', this._highlight);
el.removeEventListener('mouseout', this._unHighlight);
});
}
_clearSuggestions() {
$.bodyClassRemove('suggestions');
this._clearSuggestionHighlightEvents();
this._clearSuggestionClickEvents();
this._el.innerHTML = '';
this._highlitedSuggestion = null;
this._suggestionEls = [];
}
_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);
}
_getInfluencers({ asyncOnly, input, syncOnly }) {
return this._influencers
.filter(
(influencer) =>
(!asyncOnly && !syncOnly) ||
(asyncOnly && influencer.isAsync) ||
(syncOnly && !influencer.isAsync)
)
.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) return;
this._highlitedSuggestion = el.getAttribute('data-suggestion');
this._onHighlight(this._highlitedSuggestion);
el.classList.add('highlight');
if (e) e.preventDefault();
}
_registerEvents() {
document.addEventListener('keydown', this._handleKeydown);
}
_registerSuggestionClickEvents() {
this._suggestionEls.forEach((el) => {
const value = el.getAttribute('data-suggestion');
el.addEventListener('click', this._onClick.bind(null, value));
});
}
_registerSuggestionHighlightEvents() {
const noHighlightUntilMouseMove = () => {
window.removeEventListener('mousemove', noHighlightUntilMouseMove);
this._suggestionEls.forEach((el) => {
el.addEventListener('mouseover', this._highlight.bind(this, el));
el.addEventListener('mouseout', this._unHighlight.bind(this));
});
};
window.addEventListener('mousemove', noHighlightUntilMouseMove);
}
_rehighlight() {
if (!this._highlitedSuggestion) return;
this._highlight($.el(`[data-suggestion="${this._highlitedSuggestion}"]`));
}
_setSuggestions(newSuggestions) {
this._currentSuggestions = $.flattenAndUnique([
this._currentSuggestions,
...newSuggestions,
]);
if (!this._currentSuggestions.length) return;
this._el.innerHTML = this._buildSuggestionsHtml();
this._suggestionEls = $.els('.js-search-suggestion');
this._registerSuggestionHighlightEvents();
this._registerSuggestionClickEvents();
$.bodyClassAdd('suggestions');
this._rehighlight();
}
_unHighlight(e) {
const el = $.el('.highlight');
if (!el) return;
this._onUnhighlight();
el.classList.remove('highlight');
if (e) e.preventDefault();
}
}
</script>
<script>
class QueryParser {
constructor(options) {
this._commands = options.commands;
this._searchDelimiter = options.searchDelimiter;
this._pathDelimiter = options.pathDelimiter;
this._protocolRegex = /^[a-zA-Z]+:\/\//i;
this._urlRegex = /^((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)$/i;
this._cachedQuery = '';
this._cachedRes = {};
this.parse = this.parse.bind(this);
}
parse(query) {
if (this._cachedQuery === query) return this._cachedRes;
this._cachedQuery = query;
const res = { query: query, split: null };
if (this._urlRegex.test(query)) {
const hasProtocol = this._protocolRegex.test(query);
res.redirect = hasProtocol ? query : 'http://' + query;
} else {
const trimmed = query.trim();
const splitSearch = trimmed.split(this._searchDelimiter);
const splitPath = trimmed.split(this._pathDelimiter);
this._commands.some(({ key, search, url }) => {
if (query === key) {
res.key = key;
res.isKey = true;
res.redirect = url;
return true;
}
if (splitSearch[0] === key && search) {
res.key = key;
res.isSearch = true;
res.split = this._searchDelimiter;
res.query = QueryParser._shiftAndTrim(splitSearch, res.split);
res.redirect = QueryParser._prepSearch(url, search, res.query);
return true;
}
if (splitPath[0] === key) {
res.key = key;
res.isPath = true;
res.split = this._pathDelimiter;
res.path = QueryParser._shiftAndTrim(splitPath, res.split);
res.redirect = QueryParser._prepPath(url, res.path);
return true;
}
if (key === '*') {
res.redirect = QueryParser._prepSearch(url, search, query);
}
});
}
res.color = QueryParser._getColorFromUrl(this._commands, res.redirect);
this._cachedRes = res;
return res;
}
static _getColorFromUrl(commands, url) {
const domain = new URL(url).hostname;
return (
commands
.filter((c) => new URL(c.url).hostname.includes(domain))
.map((c) => c.color)[0] || null
);
}
static _prepPath(url, path) {
return QueryParser._stripUrlPath(url) + '/' + path;
}
static _prepSearch(url, searchPath, query) {
if (!searchPath) return url;
const baseUrl = QueryParser._stripUrlPath(url);
const urlQuery = encodeURIComponent(query);
searchPath = searchPath.replace(/{}/g, urlQuery);
return baseUrl + searchPath;
}
static _shiftAndTrim(arr, delimiter) {
arr.shift();
return arr.join(delimiter).trim();
}
static _stripUrlPath(url) {
const parser = document.createElement('a');
parser.href = url;
return `${parser.protocol}//${parser.hostname}`;
}
}
</script>
<script>
class Form {
constructor(options) {
this._colors = options.colors;
this._formEl = $.el('#search-form');
this._inputEl = $.el('#search-input');
this._inputElVal = '';
this._instantRedirect = options.instantRedirect;
this._newTab = options.newTab;
this._parseQuery = options.parseQuery;
this._suggester = options.suggester;
this._toggleHelp = options.toggleHelp;
this._clearPreview = this._clearPreview.bind(this);
this._handleInput = this._handleInput.bind(this);
this._handleKeydown = this._handleKeydown.bind(this);
this._previewValue = this._previewValue.bind(this);
this._submitForm = this._submitForm.bind(this);
this._submitWithValue = this._submitWithValue.bind(this);
this.hide = this.hide.bind(this);
this.show = this.show.bind(this);
this._registerEvents();
this._loadQueryParam();
}
hide() {
$.bodyClassRemove('form');
this._inputEl.value = '';
this._inputElVal = '';
this._suggester.suggest('');
this._setBackgroundFromQuery('');
}
show() {
$.bodyClassAdd('form');
this._inputEl.focus();
}
_clearPreview() {
this._previewValue(this._inputElVal);
this._inputEl.focus();
}
_handleInput() {
const newQuery = this._inputEl.value;
const isHelp = newQuery === '?';
const { isKey } = this._parseQuery(newQuery);
this._inputElVal = newQuery;
this._suggester.suggest(newQuery);
this._setBackgroundFromQuery(newQuery);
if (!newQuery || isHelp) this.hide();
if (isHelp) this._toggleHelp();
if (this._instantRedirect && isKey) this._submitWithValue(newQuery);
}
_handleKeydown(e) {
if ($.isUp(e) || $.isDown(e) || $.isRemove(e)) return;
switch ($.key(e)) {
case 'alt':
case 'ctrl':
case 'ctrl-*':
case 'enter':
case 'meta':
case 'meta-*':
case 'shift':
return;
case 'escape':
this.hide();
return;
}
this.show();
}
_loadQueryParam() {
const q = new URLSearchParams(window.location.search).get('q');
if (q) this._submitWithValue(q);
}
_previewValue(value) {
this._inputEl.value = value;
this._setBackgroundFromQuery(value);
}
_redirect(redirect) {
if (this._newTab) window.open(redirect, '_blank');
else window.location.href = redirect;
}
_registerEvents() {
document.addEventListener('keydown', this._handleKeydown);
this._inputEl.addEventListener('input', this._handleInput);
this._formEl.addEventListener('submit', this._submitForm, false);
if (this._suggester) {
this._suggester.setOnClick(this._submitWithValue);
this._suggester.setOnHighlight(this._previewValue);
this._suggester.setOnUnhighlight(this._clearPreview);
}
}
_setBackgroundFromQuery(query) {
if (!this._colors) return;
const color = this._parseQuery(query).color;
if (!color) return;
this._formEl.style.background = color;
}
_submitForm(e) {
if (e) e.preventDefault();
const query = this._inputEl.value;
if (this._suggester) this._suggester.success(query);
this.hide();
this._redirect(this._parseQuery(query).redirect);
}
_submitWithValue(value) {
this._inputEl.value = value;
this._submitForm();
}
}
</script>
<script>
const queryParser = new QueryParser({
commands: CONFIG.commands,
pathDelimiter: CONFIG.pathDelimiter,
searchDelimiter: CONFIG.searchDelimiter,
});
const influencers = CONFIG.influencers.map((influencerConfig) => {
return new {
Default: DefaultInfluencer,
DuckDuckGo: DuckDuckGoInfluencer,
History: HistoryInfluencer,
}[influencerConfig.name]({
defaultSuggestions: CONFIG.defaultSuggestions,
limit: influencerConfig.limit,
parseQuery: queryParser.parse,
});
});
const suggester = new Suggester({
asyncInfluencersAreBlocking: CONFIG.asyncInfluencersAreBlocking,
enabled: CONFIG.suggestions,
influencers,
limit: CONFIG.suggestionsLimit,
});
const help = new Help({
colors: CONFIG.colors,
commands: CONFIG.commands,
newTab: CONFIG.newTab,
});
const form = new Form({
colors: CONFIG.colors,
instantRedirect: CONFIG.instantRedirect,
newTab: CONFIG.newTab,
parseQuery: queryParser.parse,
suggester,
toggleHelp: help.toggle,
});
new Clock({
delimiter: CONFIG.clockDelimiter,
onClick: CONFIG.clockAction === 'Search' ? form.show : help.toggle,
twentyFourHour: CONFIG.twentyFourHourClock,
});
</script>