69 lines
2.1 KiB
JavaScript
69 lines
2.1 KiB
JavaScript
|
"use strict";
|
||
|
|
||
|
import mutate from './mutate.mjs';
|
||
|
|
||
|
let display_options = 3;
|
||
|
|
||
|
|
||
|
window.addEventListener("load", (_event) => {
|
||
|
const el_starting_word = document.querySelector("#starting-word");
|
||
|
|
||
|
if(el_starting_word.value.length > 0)
|
||
|
handle_starting_keyup();
|
||
|
|
||
|
el_starting_word.addEventListener("keyup", 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_step = event.target.closest(".mutation-step");
|
||
|
const el_word = event.target.closest(".mutation-option");
|
||
|
|
||
|
// 2: Update UI - Add classes, Remove all subsequent mutation steps
|
||
|
el_word.classList.add("selected");
|
||
|
while(el_step.nextElementSibling !== null)
|
||
|
el_step.parentNode.removeChild(el_step.nextElementSibling);
|
||
|
|
||
|
// 3: Do a new mutation step
|
||
|
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);
|
||
|
}
|