forked from hestiacp/hestiacp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalpineInit.js
More file actions
75 lines (69 loc) · 1.96 KB
/
alpineInit.js
File metadata and controls
75 lines (69 loc) · 1.96 KB
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
// Set up various Alpine things after it's initialized
export default function alpineInit() {
// Bulk edit forms
Alpine.bind('BulkEdit', () => ({
/** @param {SubmitEvent} evt */
'@submit'(evt) {
evt.preventDefault();
document.querySelectorAll('.js-unit-checkbox').forEach((el) => {
if (el.checked) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = el.name;
input.value = el.value;
evt.target.appendChild(input);
}
});
evt.target.submit();
},
}));
// Form state
Alpine.store('form', {
dirty: false,
makeDirty() {
this.dirty = true;
},
});
document
.querySelectorAll('#main-form input, #main-form select, #main-form textarea')
.forEach((el) => {
el.addEventListener('change', () => {
Alpine.store('form').makeDirty();
});
});
// Notifications methods called by the view code
Alpine.data('notifications', () => ({
initialized: false,
open: false,
notifications: [],
toggle() {
this.open = !this.open;
if (!this.initialized) {
this.list();
}
},
async list() {
const token = document.querySelector('#token').getAttribute('token');
const res = await fetch(`/list/notifications/?ajax=1&token=${token}`);
this.initialized = true;
if (!res.ok) {
throw new Error('An error occurred while listing notifications.');
}
this.notifications = Object.values(await res.json());
},
async remove(id) {
const token = document.querySelector('#token').getAttribute('token');
await fetch(`/delete/notification/?delete=1¬ification_id=${id}&token=${token}`);
this.notifications = this.notifications.filter((notification) => notification.ID != id);
if (this.notifications.length === 0) {
this.open = false;
}
},
async removeAll() {
const token = document.querySelector('#token').getAttribute('token');
await fetch(`/delete/notification/?delete=1&token=${token}`);
this.notifications = [];
this.open = false;
},
}));
}