123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- import './styles/counter.css'
- import { Countdown } from './counter.js'
- import { fetchObject } from './fetch.js';
- import { entrypoint } from './entrypoint.local.js';
- // select elements
- const main = document.querySelector('#app');
- const heading = document.createElement('h1');
- const message = document.createElement('div');
- message.classList.add('message');
- const app = document.createElement('div');
- app.classList.add('countdown-timer');
- main.appendChild(heading);
- main.appendChild(app);
- main.appendChild(message);
- const checkCounter = () => {
- const intervalId = setInterval(async () => {
- const counter = await api.getCounter();
- if (counter.error) {
- clearInterval(intervalId);
- showErrorMessage(counter.error);
- return;
- }
- heading.innerText = counter.name;
- if (counter.state === 'ready') {
- hideMessage();
- const period = new Date(counter.minutes * 1000 * 60);
- render(Countdown.getTime(period));
- } else if (counter.state === 'completed') {
- const zero = new Date(0);
- showMessage();
- render(Countdown.getTime(zero));
- } else {
- clearInterval(intervalId);
- const countdownTimer = new Countdown(
- getEndTime(counter),
- render,
- complete
- )
- }
- }, 1000)
- }
- const api = new fetchObject(entrypoint, main.dataset.id);
- checkCounter();
- const getEndTime = (counter) => {
- return new Date(Date.parse(counter.endTime));
- };
- const format = (t) => {
- return t < 10 ? '0' + t : t;
- };
- const render = (time) => {
- app.innerHTML = `
- <div class="count-down">
- <div class="timer hidden">
- <h2 class="days">${format(time.days)}</h2>
- <small>Days</small>
- </div>
- <div class="timer">
- <h2 class="hours">${format(time.hours)}</h2>
- <small>Hours</small>
- </div>
- <div class="timer">
- <h2 class="minutes">${format(time.minutes)}</h2>
- <small>Minutes</small>
- </div>
- <div class="timer">
- <h2 class="seconds">${format(time.seconds)}</h2>
- <small>Seconds</small>
- </div>
- </div>
- `;
- };
- const showMessage = () => {
- message.innerHTML = "Le compteur est terminé";
- //app.innerHTML = '';
- //heading.style.display = 'none';
- };
- const hideMessage = () => {
- message.innerHTML = '';
- heading.style.display = 'block';
- };
- const complete = () => {
- showMessage();
- checkCounter();
- };
- const showErrorMessage = (error) => {
- message.innerHTML = 'Erreur ' + error.code + ' - ' + error.message;
- const buttonRestart = document.createElement('button');
- buttonRestart.innerText = "Réessayer";
- app.appendChild(buttonRestart);
- buttonRestart.addEventListener('click', (e) => {
- buttonRestart.remove();
- checkCounter();
- })
- }
|