-
Notifications
You must be signed in to change notification settings - Fork 0
/
ujs.js
93 lines (75 loc) · 2.58 KB
/
ujs.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Event delegation system for common actions
*/
import { $, $$, makeEl } from './dom';
import { fire, delegate } from './events';
const headers = () => ({
'Accept': 'text/javascript',
'X-CSRF-Token': window.booru.csrfToken
});
function confirm(event, target) {
if (!window.confirm(target.dataset.confirm)) {
event.preventDefault();
event.stopImmediatePropagation();
}
}
function disable(event, target) {
// failed validations prevent the form from being submitted;
// stop here or the form will be permanently locked
if (target.type === 'submit' && target.closest(':invalid') !== null) return;
// delay is needed because Safari stops the submit if the button is immediately disabled
target.innerHTML = target.dataset.disableWith;
requestAnimationFrame(() => target.disabled = 'disabled');
}
// you should use button_to instead of link_to[method]!
function linkMethod(event, target) {
event.preventDefault();
const form = makeEl('form', { action: target.href, method: 'POST' });
const csrf = makeEl('input', { type: 'hidden', name: window.booru.csrfParam, value: window.booru.csrfToken });
const method = makeEl('input', { type: 'hidden', name: '_method', value: target.dataset.method });
document.body.appendChild(form);
form.appendChild(csrf);
form.appendChild(method);
form.submit();
}
function formRemote(event, target) {
event.preventDefault();
fetch(target.action, {
credentials: 'same-origin',
method: (target.dataset.method || target.method || 'POST').toUpperCase(),
headers: headers(),
body: new FormData(target)
}).then(response =>
fire(target, 'fetchcomplete', response)
);
}
function formReset(event, target) {
$$('input[disabled][data-disable-with]', target).forEach(input =>
input.removeAttribute('disabled')
);
}
function linkRemote(event, target) {
event.preventDefault();
fetch(target.href, {
credentials: 'same-origin',
method: target.dataset.method.toUpperCase(),
headers: headers()
}).then(response =>
fire(target, 'fetchcomplete', response)
);
}
function leftClick(func) {
return (event, target) => { if (event.button === 0) func(event, target); };
}
delegate(document, 'click', {
'a[data-confirm],button[data-confirm],input[data-confirm]': leftClick(confirm),
'a[data-disable-with],button[data-disable-with],input[data-disable-with]': leftClick(disable),
'a[data-method]:not([data-remote])': leftClick(linkMethod),
'a[data-remote]': leftClick(linkRemote),
});
delegate(document, 'submit', {
'form[data-remote]': formRemote
});
delegate(document, 'reset', {
'form': formReset
});