forked from toluschr/BetterDiscord-Animated-Status
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Animated_Status.plugin.js
353 lines (299 loc) · 10.5 KB
/
Animated_Status.plugin.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
//META{"name":"AnimatedStatus","source":"https://raw.githubusercontent.com/toluschr/BetterDiscord-Animated-Status/master/Animated_Status.plugin.js","website":"https://github.com/toluschr/BetterDiscord-Animated-Status"}*//
class AnimatedStatus {
/* BD functions */
getName() { return "Animated Status"; }
getVersion() { return "0.13.2"; }
getAuthor() { return "toluschr"; }
getDescription() { return "Animate your Discord status"; }
SetData(key, value) {
BdApi.setData("AnimatedStatus", key, value);
}
GetData(key) {
return BdApi.getData("AnimatedStatus", key);
}
/* Code related to Animations */
load() {
this.kSpacing = "15px";
this.kMinTimeout = 2900;
this.cancel = undefined;
this.animation = this.GetData("animation") || [];
this.timeout = this.GetData("timeout") || this.kMinTimeout;
this.randomize = this.GetData("randomize") || false;
// Import Older Config Files
if (typeof this.timeout == "string")
this.timeout = parseInt(this.timeout);
if (this.animation.length > 0 && Array.isArray(this.animation[0]))
this.animation = this.animation.map(em => this.ConfigObjectFromArray(em));
Status.authToken = BdApi.findModule(m => m.default && m.default.getToken).default.getToken();
this.currentUser = BdApi.findModule(m => m.default && m.default.getCurrentUser).default.getCurrentUser();
}
start() {
if (this.animation.length == 0)
BdApi.showToast("Animated Status: No status set. Go to Settings>Plugins to set a custom animation!");
else
this.AnimationLoop();
}
stop() {
if (this.cancel) {
this.cancel();
} else {
console.assert(this.loop != undefined);
clearTimeout(this.loop);
}
Status.Set(null);
}
ConfigObjectFromArray(arr) {
let data = {};
if (arr[0] !== undefined && arr[0].length > 0) data.text = arr[0];
if (arr[1] !== undefined && arr[1].length > 0) data.emoji_name = arr[1];
if (arr[2] !== undefined && arr[2].length > 0) data.emoji_id = arr[2];
if (arr[3] !== undefined && arr[3].length > 0) data.timeout = parseInt(arr[3]);
return data;
}
async ResolveStatusField(text = "") {
let evalPrefix = "eval ";
if (!text.startsWith(evalPrefix)) return text;
try {
return eval(text.substr(evalPrefix.length));
} catch (e) {
BdApi.showToast(e, {type: "error"});
return "";
}
}
AnimationLoop(i = 0) {
i %= this.animation.length;
// Every loop needs its own shouldContinue variable, otherwise there
// is the possibility of multiple loops running simultaneously
let shouldContinue = true;
this.loop = undefined;
this.cancel = () => { shouldContinue = false; };
Promise.all([this.ResolveStatusField(this.animation[i].text),
this.ResolveStatusField(this.animation[i].emoji_name),
this.ResolveStatusField(this.animation[i].emoji_id)]).then(p => {
Status.Set(this.ConfigObjectFromArray(p));
this.cancel = undefined;
if (shouldContinue) {
let timeout = this.animation[i].timeout || this.timeout;
this.loop = setTimeout(() => {
if (this.randomize) {
i += Math.floor(Math.random() * (this.animation.length - 2));
}
this.AnimationLoop(i + 1);
}, timeout);
}
});
}
NewEditorRow({text, emoji_name, emoji_id, timeout} = {}) {
let hbox = GUI.newHBox();
hbox.style.marginBottom = this.kSpacing;
let textWidget = hbox.appendChild(GUI.newInput(text, "Text"));
textWidget.style.marginRight = this.kSpacing;
let emojiWidget = hbox.appendChild(GUI.newInput(emoji_name, "👍" + (this.currentUser.premiumType ? " / Nitro Name" : "")));
emojiWidget.style.marginRight = this.kSpacing;
emojiWidget.style.width = "140px";
let optNitroIdWidget = hbox.appendChild(GUI.newInput(emoji_id, "Nitro ID"));
if (!this.currentUser.premiumType) optNitroIdWidget.style.display = "none";
optNitroIdWidget.style.marginRight = this.kSpacing;
optNitroIdWidget.style.width = "140px";
let optTimeoutWidget = hbox.appendChild(GUI.newNumericInput(timeout, this.kMinTimeout, "Time"));
optTimeoutWidget.style.width = "75px";
hbox.onkeydown = (e) => {
let activeContainer = document.activeElement.parentNode;
let activeIndex = Array.from(activeContainer.children).indexOf(document.activeElement);
let keymaps = {
"Delete": [
[[false, true], () => {
activeContainer = hbox.nextSibling || hbox.previousSibling;
hbox.parentNode.removeChild(hbox);
}],
],
"ArrowDown": [
[[true, true], () => {
activeContainer = this.NewEditorRow();
hbox.parentNode.insertBefore(activeContainer, hbox.nextSibling);
}],
[[false, true], () => {
let next = hbox.nextSibling;
if (next != undefined) {
next.replaceWith(hbox);
hbox.parentNode.insertBefore(next, hbox);
}
}],
[[false, false], () => {
activeContainer = hbox.nextSibling;
}],
],
"ArrowUp": [
[[true, true], () => {
activeContainer = this.NewEditorRow();
hbox.parentNode.insertBefore(activeContainer, hbox);
}],
[[false, true], () => {
let prev = hbox.previousSibling;
if (prev != undefined) {
prev.replaceWith(hbox);
hbox.parentNode.insertBefore(prev, hbox.nextSibling);
}
}],
[[false, false], () => {
activeContainer = hbox.previousSibling;
}],
],
};
let letter = keymaps[e.key];
if (letter == undefined) return;
for (let i = 0; i < letter.length; i++) {
if (letter[i][0][0] != e.ctrlKey || letter[i][0][1] != e.shiftKey)
continue;
letter[i][1]();
if (activeContainer) activeContainer.children[activeIndex].focus();
e.preventDefault();
return;
}
};
return hbox;
}
EditorFromJSON(json) {
let out = document.createElement("div");
for (let i = 0; i < json.length; i++) {
out.appendChild(this.NewEditorRow(json[i]));
}
return out;
}
JSONFromEditor(editor) {
return Array.prototype.slice.call(editor.childNodes).map(row => {
return this.ConfigObjectFromArray(Array.prototype.slice.call(row.childNodes).map(e => e.value));
});
}
// Settings
getSettingsPanel() {
let settings = document.createElement("div");
settings.style.padding = "10px";
// timeout
settings.appendChild(GUI.newLabel("Step-Duration (3000: 3 seconds, 3500: 3.5 seconds, ...), overwritten by invididual steps"));
let timeout = settings.appendChild(GUI.newNumericInput(this.timeout, this.kMinTimeout));
timeout.style.marginBottom = this.kSpacing;
// Animation Container
settings.appendChild(GUI.newLabel("Animation"));
let animationContainer = settings.appendChild(document.createElement("div"));
animationContainer.marginBottom = this.kSpacing;
// Editor
let edit = animationContainer.appendChild(this.EditorFromJSON(this.animation));
// Actions
let actions = settings.appendChild(GUI.newHBox());
// Add Step
let addStep = actions.appendChild(GUI.setSuggested(GUI.newButton("+", false)));
addStep.title = "Add step to end";
addStep.onclick = () => edit.appendChild(this.NewEditorRow());
// Del Step
let delStep = actions.appendChild(GUI.setDestructive(GUI.newButton("-", false)));
delStep.title = "Remove last step";
delStep.style.marginLeft = this.kSpacing;
delStep.onclick = () => edit.removeChild(edit.childNodes[edit.childNodes.length - 1]);
// Move save to the right (XXX make use of flexbox)
actions.appendChild(GUI.setExpand(document.createElement("div"), 2));
// Save
let save = actions.appendChild(GUI.newButton("Save"));
GUI.setSuggested(save, true);
save.onclick = () => {
try {
// Set timeout
this.SetData("randomize", this.randomize);
this.SetData("timeout", parseInt(timeout.value));
this.SetData("animation", this.JSONFromEditor(edit));
} catch (e) {
BdApi.showToast(e, {type: "error"});
return;
}
// Show Toast
BdApi.showToast("Settings were saved!", {type: "success"});
// Restart
this.stop();
this.load();
this.start();
};
// End
return settings;
}
}
/* Status API */
const Status = {
strerror: (req) => {
if (req.status < 400) return undefined;
if (req.status == 401) return "Invalid AuthToken";
// Discord _sometimes_ returns an error message
let json = JSON.parse(req.response);
for (const s of ["errors", "custom_status", "text", "_errors", 0, "message"])
if ((json == undefined) || ((json = json[s]) == undefined))
return "Unknown error. Please report at github.com/toluschr/BetterDiscord-Animated-Status";
return json;
},
Set: async (status) => {
let req = new XMLHttpRequest();
req.open("PATCH", "/api/v9/users/@me/settings", true);
req.setRequestHeader("authorization", Status.authToken);
req.setRequestHeader("content-type", "application/json");
req.onload = () => {
let err = Status.strerror(req);
if (err != undefined)
BdApi.showToast(`Animated Status: Error: ${err}`, {type: "error"});
};
if (status === {}) status = null;
req.send(JSON.stringify({custom_status: status}));
},
};
// Used to easily style elements like the 'native' discord ones
const GUI = {
newInput: (text = "", placeholder = "") => {
let input = document.createElement("input");
input.className = "inputDefault-3FGxgL input-2g-os5";
input.value = String(text);
input.placeholder = String(placeholder);
return input;
},
newNumericInput: (text = "", minimum = 0, placeholder = "") => {
let out = GUI.newInput(text, placeholder);
out.setAttribute("type", "number");
out.addEventListener("focusout", () => {
if (parseInt(out.value) < minimum) {
out.value = String(minimum);
BdApi.showToast(`Value must not be lower than ${minimum}`, {type: "error"});
}
});
return out;
},
newLabel: (text = "") => {
let label = document.createElement("h5");
label.className = "h5-2RwDNl";
label.innerText = String(text);
return label;
},
newButton: (text, filled = true) => {
let button = document.createElement("button");
button.className = "button-f2h6uQ colorBrand-I6CyqQ sizeSmall-wU2dO- grow-2sR_-F";
if (filled) button.classList.add("lookFilled-yCfaCM");
else button.classList.add("lookOutlined-3yKVGo");
button.innerText = String(text);
return button;
},
newHBox: () => {
let hbox = document.createElement("div");
hbox.style.display = "flex";
hbox.style.flexDirection = "row";
return hbox;
},
setExpand: (element, value) => {
element.style.flexGrow = value;
return element;
},
setSuggested: (element, value = true) => {
if (value) element.classList.add("colorGreen-3y-Z79");
else element.classList.remove("colorGreen-3y-Z79");
return element;
},
setDestructive: (element, value = true) => {
if (value) element.classList.add("colorRed-rQXKgM");
else element.classList.remove("colorRed-rQXKgM");
return element;
}
};