Ron Au
refactor
2d460b1
raw
history blame
3.02 kB
import { generateDetails, createTask, queueTask, longPollTask } from './network.js';
import { cardHTML } from './card-html.js';
import {
durationTimer,
updateCardName,
initialiseCardRotation,
setOutput,
screenshotCard,
} from './dom-manipulation.js';
const nameInput = document.querySelector('input[name="name"');
const nameToggle = document.querySelector('button.toggle-name');
let pokeName;
let trainerName;
let useTrainerName = true;
let generating = false;
let mousemoveHandlerForPreviousCard;
const generate = async () => {
if (generating) {
return;
}
try {
const scene = document.querySelector('.scene');
const cardSlot = scene.querySelector('.card-slot');
const durationDisplay = document.querySelector('.duration');
scene.removeEventListener('mousemove', mousemoveHandlerForPreviousCard, true);
cardSlot.innerHTML = '';
generating = true;
setOutput('booster', 'generating');
await new Promise((resolve) => setTimeout(resolve, 9999));
const details = await generateDetails();
pokeName = details.name;
const task = await createTask(details.energy_type);
document.querySelector('.actions').style.opacity = '1';
durationDisplay.classList.add('displayed');
const timer = durationTimer(durationDisplay);
const timerCleanup = timer().cleanup;
const longPromises = [queueTask(task.task_id), longPollTask(task)];
const completedTask = await Promise.any(longPromises);
setOutput('booster', 'completed');
generating = false;
timerCleanup(completedTask);
cardSlot.innerHTML = cardHTML(details);
updateCardName(trainerName, pokeName, useTrainerName);
const picture = document.querySelector('img.picture');
picture.src = completedTask.value;
mousemoveHandlerForPreviousCard = initialiseCardRotation(scene);
setOutput('card', 'completed');
} catch (err) {
generating = false;
console.error(err);
}
};
nameInput.addEventListener('input', (e) => {
trainerName = [...e.target.value].filter((char) => char.match(/[\wÀ-ÿ '".,&+#!?:/\\()_-]/g)?.length).join('');
nameInput.value = trainerName;
updateCardName(trainerName, pokeName, useTrainerName);
});
document.querySelector('form.trainer-name').addEventListener('submit', (e) => {
e.preventDefault();
generate();
});
nameToggle.addEventListener('click', () => {
useTrainerName = !useTrainerName;
updateCardName(trainerName, pokeName, useTrainerName);
if (!useTrainerName) {
nameToggle.classList.add('off');
} else {
nameToggle.classList.remove('off');
}
});
document.querySelector('.booster').addEventListener('click', generate);
document.querySelector('button.generate-new').addEventListener('click', generate);
document.querySelector('button.save').addEventListener('click', async () => {
const a = document.createElement('a');
a.href = await screenshotCard();
a.download = `${updateCardName(trainerName, pokeName, useTrainerName)} - This Pokémon Does Not Exist.png`;
a.click();
});