summaryrefslogtreecommitdiff
path: root/resources/optional.js
blob: c5e85e91857537a660eeae394a23f2a1e89abc7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// This JavaScript just serves to improve the user experience
// it is not at all required for submitting a vote.

const form = document.getElementById('vote-form');
const commentInput = form.querySelector('textarea');
const radios = {};

// Make the comment input required if you select to oppose or abstain.
for (const radio of form.querySelectorAll('input[type=radio]')) {
    radio.addEventListener('change', e => {
        commentInput.required = e.target.value != 'yes';
    });
    radios[radio.value] = radio;
}

// Disable the Enter key in the comment input (because
// the PHP code replaces newlines with spaces anyway).
commentInput.addEventListener('keypress', e => {
    if (e.key == 'Enter') {
        e.preventDefault();
    }
});

// Remind users what they voted for and prevent them from casting the same vote again.
const script = form.querySelector('script[data-votes]');
const votes = JSON.parse(script.textContent);
const previousVote = votes[mw.config.get('wgUserName')];

if (previousVote) {
    const note = document.createElement('span');
    note.textContent = mw.message('vote-already-' + previousVote).text();
    script.insertAdjacentElement('beforebegin', note);
    radios[previousVote].checked = true;
    const submitButton = form.querySelector('input[type=submit]');
    submitButton.disabled = true;
    form.querySelector('h3').textContent = mw.message('vote-edit-your-vote').text();

    for (const radio of Object.values(radios)) {
        radio.addEventListener('change', e => {
            if (e.target.value == previousVote) {
                submitButton.disabled = true;
                note.textContent = mw.message('vote-already-' + previousVote).text();
            } else {
                submitButton.disabled = false;
                note.textContent = mw.message('vote-change', previousVote, e.target.value).text();
            }
        })
    }
}

// FUTURE: disable form if you are logged in but may not edit the page