import { OptimisticAction } from "./OptimisticAction.js"; export class VoteManager extends OptimisticAction { constructor() { super(); this.initVoteButtons(); } initVoteButtons() { document.querySelectorAll('form[action^="/votes/"] button[type="submit"]').forEach((button) => { const form = button.closest("form"); button.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); this.cast(form, button); }); }); } cast(form, button) { const action = form.getAttribute("action"); const value = form.querySelector('input[name="value"]').value; return this.submit(action, { value }, button, (result) => this.render(action, result)); } render(action, result) { const targetUid = action.split("/").pop(); document.querySelectorAll(`[data-vote-count="${targetUid}"]`).forEach((counter) => { counter.textContent = result.net; }); document.querySelectorAll(`form[action="${action}"] button[type="submit"]`).forEach((button) => { const formValue = parseInt(button.closest("form").querySelector('input[name="value"]').value, 10); button.classList.toggle("voted", result.value !== 0 && formValue === result.value); }); } }