-
Notifications
You must be signed in to change notification settings - Fork 531
/
base.js
306 lines (276 loc) · 10.2 KB
/
base.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/* eslint-disable no-unused-vars */
//================================================================
//============================================= Settings & Helpers
//================================================================
//Settings & constants
const REQ_TIMEOUT_SHORT = 1_500;
const REQ_TIMEOUT_MEDIUM = 5_000;
const REQ_TIMEOUT_LONG = 9_000;
const REQ_TIMEOUT_REALLY_LONG = 15_000;
const REQ_TIMEOUT_REALLY_REALLY_LONG = 30_000;
const SPINNER_HTML = '<div class="txSpinner">Loading...</div>';
//Helpers
const anyUndefined = (...args) => { return [...args].some((x) => (typeof x === 'undefined')); };
const xss = (x) => {
let tmp = document.createElement('div');
tmp.innerText = x;
return tmp.innerHTML;
};
const convertMarkdown = (input, inline = false) => {
const toConvert = xss(input)
.replaceAll(/\n/g, ' \n')
.replaceAll(/\t/g, ' ');
const markedOptions = {
breaks: true,
};
const func = inline ? marked.parseInline : marked.parse;
return func(toConvert, markedOptions)
.replaceAll('&lt;', '<')
.replaceAll('&gt;', '>');
};
//================================================================
//================================================= Event Handlers
//================================================================
//Page load
document.addEventListener('DOMContentLoaded', function(event) {
if (typeof $.notifyDefaults !== 'undefined') {
$.notifyDefaults({
z_index: 2000,
mouse_over: 'pause',
placement: {
align: 'center',
},
offset: {
y: 64,
},
});
}
if (typeof jconfirm !== 'undefined') {
jconfirm.defaults = {
title: 'Confirm:',
draggable: false,
escapeKey: true,
closeIcon: true,
backgroundDismiss: true,
typeAnimated: false,
animation: 'scale',
type: 'red',
columnClass: 'medium',
theme: document.body.classList.contains('theme--dark') ? 'dark' : 'light',
};
}
});
//Handle profile picture load error
const pfpList = document.getElementsByClassName('profile-pic');
for (let pfp of pfpList) {
pfp.addEventListener('error', () => {
if (pfp.src != 'img/default_avatar.png') {
pfp.src = 'img/default_avatar.png';
}
});
}
//================================================================
//================================================= Helper funcs
//================================================================
const checkApiLogoutRefresh = (data) => {
if (data.logout === true) {
window.parent.postMessage({ type: 'logoutNotice' });
return true;
} else if (data.refresh === true) {
window.location.reload(true);
return true;
}
return false;
};
//usage: if (checkApiLogoutRefresh(data)) return;
/**
* To display the markdown errors.
* NOTE: likely deprecate when creating default api response handlers
* @param {object} data
* @param {object} notify
* @returns
*/
const updateMarkdownNotification = (data, notify) => {
if (data.markdown === true) {
let msgHtml = convertMarkdown(data.message, true);
if (data.type === 'danger') {
msgHtml += `<div class="text-right">
<small>
For support, visit <strong><a href="http://discord.gg/txAdmin" target="_blank" class="text-dark">discord.gg/txAdmin</a></strong>.
</small>
</div>`;
}
notify.update('progress', 0);
notify.update('type', data.type);
notify.update('message', msgHtml);
//since we can't change the duration with an update
setTimeout(() => {
notify.update('progress', 0);
}, 5000);
} else {
notify.update('progress', 0);
notify.update('type', data.type);
notify.update('message', data.message);
}
return false;
};
//Must be as close to a JQuery $.ajax() as possible
//TODO: abstract a little bit more and use fetch
//TODO: use the function above for all calls
//NOTE: datatype is the expected return, we can probably remove it
//NOTE: still one $.ajax at setup.html > setFavTemplatesCards
//NOTE: to send json:
// data: JSON.stringify(data)
// contentType: 'application/json'
const txAdminAPI = ({type, url, data, dataType, timeout, success, error}) => {
if (anyUndefined(type, url)) return false;
url = TX_BASE_PATH + url;
timeout = timeout ?? REQ_TIMEOUT_MEDIUM;
dataType = dataType || 'json';
success = success || (() => {});
error = error || (() => {});
const headers = {'X-TxAdmin-CsrfToken': (csrfToken) ? csrfToken : 'not_set'}
// console.log(`txAdminAPI Req to: ${url}`);
return $.ajax({type, url, timeout, data, dataType, success, error, headers});
};
const txAdminAlert = ({content, modalColor, title}) => {
$.confirm({
title,
content: content,
type: modalColor || 'green',
buttons: {
close: {
text: 'Close',
keys: ['enter'],
}
},
});
};
const txAdminConfirm = ({content, confirmBtnClass, modalColor, title}) => {
return new Promise((resolve, reject) => {
$.confirm({
title,
content: content,
type: modalColor || 'red',
buttons: {
cancel: () => {resolve(false);},
confirm: {
btnClass: confirmBtnClass || 'btn-red',
keys: ['Enter', 'NumpadEnter'],
action: () => {resolve(true);},
},
},
onClose: () => {resolve(false);},
});
});
};
const txAdminPrompt = ({
confirmBtnClass = 'btn-blue',
modalColor = 'blue',
title = '',
description = '',
placeholder = '',
required = true,
}) => {
return new Promise((resolve, reject) => {
$.confirm({
title,
type: modalColor,
content: `
<form action="">
<div class="form-group">
<label>${description}</label>
<input type="text" placeholder="${placeholder}" class="inputField form-control" ${required && 'required'} />
</div>
</form>`,
buttons: {
cancel: () => {resolve(false);},
formSubmit: {
text: 'Submit',
btnClass: confirmBtnClass,
action: function () {
resolve(this.$content.find('.inputField').val());
},
},
},
onClose: () => {
resolve(false);
},
onContentReady: function () {
const jc = this;
this.$content.find('form').on('submit', function (e) {
e.preventDefault();
jc.$$formSubmit.trigger('click');
});
this.$content.find('input').focus();
},
});
});
};
//Starts a notify which is expected to take long
//This notify will keep being updated by adding dots at the end
const startHoldingNotify = (awaitingMessage) => {
const holdingHtml = (secs) => {
const extraDots = '.'.repeat(secs);
return `<p class="text-center">${awaitingMessage}${extraDots}</p>`;
}
const notify = $.notify({ message: holdingHtml(0) }, {});
let waitingSeconds = 0;
const progressTimerId = setInterval(() => {
waitingSeconds++;
notify.update('message', holdingHtml(waitingSeconds));
notify.update('progress', 0);
}, 1000);
return {notify, progressTimerId};
}
//================================================================
//================================================= Darkmode Theme
//================================================================
(function () {
if (!isWebInterface) return;
const darkModeCookie = document.cookie.match(/(^| )txAdmin-darkMode=([^;]+)/);
if (darkModeCookie === null) {
console.log('no theme cookie found');
//If the user has Dark Mode as their OS default
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
console.log('OS dark mode detected');
document.body.classList.toggle('theme--dark');
document.cookie = 'txAdmin-darkMode=true;path=/';
//If the user is on desktop
} else if (window.location.pathname == '/') {
const darkModeSuggestionCookie = document.cookie.match(/(^| )txAdmin-darkModeSuggestion=([^;]+)/);
const suggestionInterval = 24 * 60 * 60 * 1000; // every day
if (darkModeSuggestionCookie === null) {
const expDate = new Date();
expDate.setTime(expDate.getTime() + suggestionInterval);
const darkToggleArea = document.getElementById('darkToggleArea');
const tooltip = new coreui.Tooltip(darkToggleArea, {
container: 'body',
boundary: 'window',
offset: function offset(_ref) {
return [0, _ref.popper.height / 3];
},
});
setTimeout(() => {
tooltip.show();
document.cookie = `txAdmin-darkModeSuggestion=true;expires=${expDate.toUTCString()};path=/`;
}, 2000);
}
}
}
const hiddenClass = 'd-none';
let isDarkMode = document.body.classList.contains('theme--dark');
const toggle1 = document.getElementById('darkToggleDark');
const toggle2 = document.getElementById('darkToggleLight');
toggle1.classList.toggle(hiddenClass, isDarkMode);
toggle2.classList.toggle(hiddenClass, !isDarkMode);
const handlerFn = function () {
document.body.classList.toggle('theme--dark');
toggle1.classList.toggle(hiddenClass);
toggle2.classList.toggle(hiddenClass);
isDarkMode = !isDarkMode;
document.cookie = `txAdmin-darkMode=${isDarkMode};path=/`;
};
toggle1.addEventListener('click', handlerFn);
toggle2.addEventListener('click', handlerFn);
})();