User:Weeklyd3/scripts/autocomplete.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
function addHistoryItem(item) {
	var items = JSON.parse(localStorage.getItem('search-history') ?? '[]');
	items.unshift(item);
	localStorage.setItem('search-history', JSON.stringify(items));
}
function onkeydown(ev) {
	if (ev.key === 'Enter') addHistoryItem(ev.currentTarget.value);
}
window.currentValueLength = -1;
function onInput() {
	window.continue = true;
	const currentValueLengthNew = this.value.length;
	if (this.tagName !== 'INPUT') return;
	var items = JSON.parse(localStorage.getItem('search-history') ?? '[]');
	items.forEach((function(item) {
		if (!window.continue) return console.log('FAIL: Not allowed to continue');
		if (this.value.length <= window.currentValueLength) return console.log('FAIL: Text deleted: Before input: ' + window.currentValueLength + ' after input: ' + this.value.length);
		if (!item.toLowerCase().startsWith(this.value.toLowerCase())) return console.log('FAIL: no match');
		const val = item.slice(this.value.length);
		const currentLength = this.value.length;
		this.value += val;
		this.selectionStart = currentLength;
		this.selectionEnd = this.value.length;
		window.continue = false;
	}).bind(this));
	window.currentValueLength = currentValueLengthNew;
}
document.querySelector('#searchInput').addEventListener('input', onInput.bind(document.querySelector('#searchInput')));
document.querySelector('#searchInput').addEventListener('keydown', onkeydown);