AniwatchPlus/enhancements/quickSearch.js

63 lines
2.2 KiB
JavaScript
Raw Normal View History

const quickSearchID = 'ea-quickSearch';
2020-07-29 13:54:21 +02:00
const quickSearchLink = 'ea-quickSearchLink';
2020-07-29 13:37:41 +02:00
runAfterLoad(() => {
2020-07-29 13:26:59 +02:00
initSearch();
}, ".*");
function initSearch() {
let entry = document.createElement('li');
entry.setAttribute('ng-repeat', 'item in navbar');
entry.setAttribute('ng-class', '{\'anime-indicator\': item[\'@attributes\'].title==\'Anime\'}');
let quickSearchElement = document.createElement('input');
quickSearchElement.setAttribute('aria-label', 'Quick Search Input');
quickSearchElement.setAttribute('ng-model-options', '{debounce: 500}');
quickSearchElement.type = 'text';
quickSearchElement.classList.add('ng-pristine', 'ng-valid', 'ng-empty', 'ng-touched');
quickSearchElement.placeholder = 'Quick Search (Shift + F)';
quickSearchElement.id = quickSearchID;
// register Enter keybinding
quickSearchElement.addEventListener('keypress', event => handleQuickSearch(event));
2020-07-29 13:26:59 +02:00
entry.appendChild(quickSearchElement);
2020-07-29 13:41:25 +02:00
// Aniwatch CSS requires the search input to be in some kind of known menu container
2020-07-29 13:54:21 +02:00
let linkElement = document.createElement('a');
linkElement.appendChild(quickSearchElement);
linkElement.id = quickSearchLink;
entry.appendChild(linkElement);
2020-07-29 13:40:52 +02:00
let menu = document.getElementById('materialize-menu-dropdown');
2020-07-29 13:26:59 +02:00
menu.insertAdjacentElement('beforeend', entry);
// register focus hotkey
document.addEventListener('keypress', event => handleSearchForShiftF(event));
2020-07-29 13:26:59 +02:00
}
function handleQuickSearch(event) {
2020-07-29 13:26:59 +02:00
if (event.key === 'Enter') {
2020-07-29 13:58:06 +02:00
let quickSearchElement = document.getElementById(quickSearchID);
let linkElement = document.getElementById(quickSearchLink);
2020-07-29 13:26:59 +02:00
let url = new URL(window.location.origin)
url.pathname = '/search';
2020-07-29 13:58:06 +02:00
url.searchParams.append('q', quickSearchElement.value);
2020-07-29 13:26:59 +02:00
2020-07-29 13:54:21 +02:00
linkElement.href = `${url.pathname}${url.search}`;
linkElement.click();
2020-07-29 13:58:06 +02:00
// clean up afterwards
linkElement.href = '';
quickSearchElement.value = '';
2020-07-29 13:26:59 +02:00
}
}
function handleSearchForShiftF(event) {
if (isShiftPressed) {
if (event.key === 'F') {
event.preventDefault();
document.getElementById(quickSearchID).focus();
}
}
2020-07-29 13:26:59 +02:00
}