37 lines
1.4 KiB
JavaScript
Raw Normal View History

2026-06-09 18:37:49 +02:00
import { OptimisticAction } from "./OptimisticAction.js";
2026-05-23 08:34:13 +02:00
2026-06-09 18:37:49 +02:00
export class VoteManager extends OptimisticAction {
2026-05-23 01:50:31 +02:00
constructor() {
2026-06-09 18:37:49 +02:00
super();
2026-05-23 01:50:31 +02:00
this.initVoteButtons();
}
initVoteButtons() {
2026-05-27 21:06:18 +02:00
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);
2026-05-23 01:50:31 +02:00
});
});
}
2026-05-27 21:06:18 +02:00
2026-06-09 18:37:49 +02:00
cast(form, button) {
2026-05-27 21:06:18 +02:00
const action = form.getAttribute("action");
const value = form.querySelector('input[name="value"]').value;
2026-06-09 18:37:49 +02:00
return this.submit(action, { value }, button, (result) => this.render(action, result));
2026-05-27 21:06:18 +02:00
}
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);
});
}
2026-05-23 01:50:31 +02:00
}