heonian-webdic/main.js
2022-06-07 00:18:05 +02:00

118 lines
3.5 KiB
JavaScript

let json = null;
let searchDictionary = {};
let header = null;
let main = null;
function animateHeader(inout = false) {
//todo: debounce this
if (inout) {
header.classList.add("header-animation-reverse");
header.classList.remove("header-animation");
setTimeout(() => {
header.classList.add("fullscreen");
},500);
setTimeout(() => {
header.classList.remove("header-animation-reverse");
},1000);
} else {
header.classList.add("header-animation");
header.classList.remove("header-animation-reverse");
setTimeout(() => {
header.classList.remove("fullscreen");
},500);
setTimeout(() => {
header.classList.remove("header-animation");
},1000);
}
//somewhere here we animate in the actual page too, but it.. doesnt exist yet
}
// on space animateHeader()
document.addEventListener("keydown", (e) => {
//on / key press
if (e.keyCode === 191) {
e.preventDefault();
header.querySelector("input").focus();
}
if (e.keyCode === 27) {
//if search box not focused, and if we're not on the home page, go back to home page
if (!header.querySelector("input").matches(":focus") && !header.classList.contains("fullscreen")) {
e.preventDefault();
animateHeader(true);
}
}
if (e.keyCode === 13) {
if (header.querySelector("input").matches(":focus")) {
//search
e.preventDefault();
animateHeader(); //just in case
doSearch();
}
}
});
function stripWord(word) {
return word.replace(/[^a-zA-Z]/g, "");
}
function loadDictionary() {
fetch("/wordlist.json").then((e) => {
if (e.status === 200) {
//convert to json lmao
e.json().then((e) => {
json = e;
let values = Object.values(json);
let keys = Object.keys(json);
//prepare search. maybe async this if we're loading a specific word?
for (let i = 0; i < keys.length; i++) {
//create array
searchDictionary[keys[i]] = [];
//add: base word (obvious, will always exist)
searchDictionary[keys[i]].push(stripWord(keys[i]));
//add: base word, but in heonian (todo, needs translator)
//add: translation (will always exist, i hope)
searchDictionary[keys[i]].push(stripWord(values[i].translation));
}
//ok, we're all ready!
document.querySelector("header input").placeholder = "search";
});
} else {
alert("yeah something went horribly wrong loading the wordlist so uh,,, certified ike moment");
return;
}
});
}
function search(word) {
word = stripWord(word);
let result = [];
for (let key in searchDictionary) {
for (let value in searchDictionary[key]) {
if (searchDictionary[key][value].includes(word)) {
result.push(key);
}
}
}
return result;
}
function doSearch() {
let results = search(header.querySelector("input").value);
if (results.length == 0) {
main.innerHTML = "no results lulw";
} else {
//actually render results or w/e
}
}
window.onload = () => {
header = document.querySelector("header");
main = document.querySelector("main");
loadDictionary();
}