From 54b9791dc39734aabe189e6c684f2272d5d4787b Mon Sep 17 00:00:00 2001 From: Andreas Nedbal Date: Sat, 8 Jan 2022 02:52:59 +0100 Subject: [PATCH] Port report vote functionality to TypeScript --- .../retrospring/features/moderation/vote.ts | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 app/javascript/retrospring/features/moderation/vote.ts diff --git a/app/javascript/retrospring/features/moderation/vote.ts b/app/javascript/retrospring/features/moderation/vote.ts new file mode 100644 index 00000000..b5c07edd --- /dev/null +++ b/app/javascript/retrospring/features/moderation/vote.ts @@ -0,0 +1,65 @@ +import Rails from '@rails/ujs'; + +import I18n from '../../../legacy/i18n'; +import { showNotification, showErrorNotification } from 'utilities/notifications'; + +export function voteReportHandler(event: Event): void { + const button = event.target as HTMLButtonElement; + const id = button.dataset.id; + const action = button.dataset.action; + const upvote = button.dataset.voteType === 'upvote'; + button.disabled = true; + + let success = false; + let targetUrl; + + if (action === 'vote') { + targetUrl = '/ajax/mod/create_vote'; + } + else if (action === 'unvote') { + targetUrl = '/ajax/mod/destroy_vote'; + } + + Rails.ajax({ + url: targetUrl, + type: 'POST', + data: new URLSearchParams({ + id: id, + upvote: String(upvote) + }).toString(), + success: (data) => { + success = data.success; + if (success) { + document.querySelector(`span#mod-count-${id}`).innerHTML = data.count; + } + + showNotification(data.message); + }, + error: (data, status, xhr) => { + console.log(data, status, xhr); + showErrorNotification(I18n.translate('frontend.error.message')); + }, + complete: () => { + if (success) { + switch (action) { + case 'vote': + button.disabled = true; + button.dataset.action = 'unvote'; + + const inverseVoteButton = document.querySelector(`[name=mod-vote][data-id="${id}"][data-vote-type="${ upvote ? 'downvote' : 'upvote' }"]`); + inverseVoteButton.disabled = false; + inverseVoteButton.dataset.action = 'unvote'; + break; + case 'unvote': + button.disabled = false; + button.dataset.action = 'vote'; + + const inverseUnvoteButton = document.querySelector(`[name=mod-vote][data-id="${id}"][data-vote-type="${ upvote ? 'downvote' : 'upvote' }"]`); + inverseUnvoteButton.disabled = false; + inverseUnvoteButton.dataset.action = 'vote'; + break; + } + } + } + }); +} \ No newline at end of file