import {Controller} from "stimulus"; import Rails from "@rails/ujs"; export default class extends Controller { static targets = [ "timer", "progressBar" ]; static values = { timeRemaining: Number, activityDuration: Number, postUrl: String, } connect() { if (!this.timerInterval) this.startUpdating(); this.timerTarget.textContent = Math.ceil(this.timeRemainingValue); this.postFailures = 0; } startUpdating() { let controller = this; controller.timerInterval = setInterval(() => { if (controller.timeRemainingValue > 0) { controller.timeRemainingValue = controller.timeRemainingValue - 0.01; } if (controller.timeRemainingValue > 0) { controller.timerTarget.textContent = Math.ceil(controller.timeRemainingValue).toString(); controller.progressBarTarget.style.width = `${(1 - (controller.timeRemainingValue / controller.activityDurationValue)) * 100}%`; } else { clearInterval(controller.timerInterval); controller.timerInterval = null; controller.finishActivity(); } }, 10); } finishActivity() { let controller = this; Rails.ajax({ type: "POST", url: controller.postUrlValue, error: () => { this.postFailures++; if (this.postFailures < 5) { setTimeout(controller.finishActivity, 1000); } else { alert("There was an error completing your activity. If your internet connection is otherwise working," + " please report this issue, mentioning what you were" + " doing at the time. Check if refreshing the page resolves this issue, and mention that as well."); } }, }); } }