import { generateDetails, createTask, 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'); 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 completedTask = await longPollTask(task); generating = false; timerCleanup(completedTask); if (completedTask.status === 'failed') { setOutput('booster', 'failed'); throw new Error(`Task failed: ${completedTask.error}`); } setOutput('booster', 'completed'); cardSlot.innerHTML = cardHTML(details); updateCardName(trainerName, pokeName, useTrainerName); document.querySelector('img.picture').src = completedTask.value; mousemoveHandlerForPreviousCard = initialiseCardRotation(scene); await new Promise((resolve) => setTimeout(resolve, window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 1_500 : 1_000) ); 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(); });