mutate-a-word/js/index.mjs

89 lines
2.8 KiB
JavaScript

"use strict";
import { mutate, random_item } from './mutate.mjs';
let display_options = 3;
let initial_words = [
"rockets",
"cheese",
"treasure",
"island"
]
window.addEventListener("load", (_event) => {
const el_starting_word = document.querySelector("#starting-word");
const el_starting_regen = document.querySelector("#starting-regen");
if(el_starting_word.value.length === 0)
el_starting_word.value = random_item(initial_words);
handle_starting_keyup();
el_starting_word.addEventListener("keyup", handle_starting_keyup);
el_starting_regen.addEventListener("click", handle_starting_keyup);
el_starting_regen.addEventListener("mouseup", handle_starting_keyup);
el_starting_regen.addEventListener("touchend", handle_starting_keyup);
});
function handle_starting_keyup(_event) {
const el_starting_word = document.querySelector("#starting-word");
const el_mutations = document.querySelector("#mutations");
el_mutations.replaceChildren(); // Empty node of all children
mutation_step(el_starting_word.value);
}
function handle_mutation_word_keyup(event) {
// 1: Find DOM elements
const el_mutations = document.querySelector("#mutations");
const el_step = event.target.closest(".mutation-step");
const el_word = event.target.closest(".mutation-option");
const els_word = el_step.querySelectorAll(".mutation-option");
// 2: Update UI - Change classes, Remove all subsequent mutation steps
for(let i = 0; i < els_word.length; i++)
els_word[i].classList.remove("selected");
el_word.classList.add("selected");
while(el_step.nextElementSibling !== null)
el_step.parentNode.removeChild(el_step.nextElementSibling);
// 3: Do a new mutation step
el_mutations.appendChild(document.createElement("hr"))
mutation_step(el_word.dataset.word);
}
function mutation_step(word) {
// 0: Validate input
if(typeof word !== "string")
throw new Error(`Error: Expected argument 1 (word) to be of type string, but got value of type ${typeof word}.`);
// 1: Find DOM elements
const el_mutations = document.querySelector("#mutations");
// 2: Generate mutations
// TODO: Eliminate duplicates
const words_new = Array(display_options).fill(null)
.map(() => mutate(word));
// 3: Update DOM
let el_step = document.createElement("div");
el_step.classList.add("mutation-step");
for(let word_item of words_new) {
let el_word = document.createElement("span");
el_word.classList.add("mutation-option");
el_word.appendChild(document.createTextNode(word_item));
el_word.dataset.word = word_item;
el_step.appendChild(el_word);
el_word.addEventListener("click", handle_mutation_word_keyup);
el_word.addEventListener("touchend", handle_mutation_word_keyup);
el_word.addEventListener("mouseup", handle_mutation_word_keyup);
}
el_mutations.appendChild(el_step);
window.scrollTo(0,document.body.scrollHeight);
}