Plugin
BetterFolders
Adds new functionality to server folders. Custom Folder Icons. Close other folders on open.
Installation: Datei herunterladen und in deinen BetterDiscord-Ordner legen —
%appdata%\\BetterDiscord\\plugins
(Windows) bzw. über Discord: Einstellungen → Plugins → Plugin-Ordner öffnen.
BetterFolders.plugin.js · 656 Zeilen · 23.6 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
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
/*
FILE META START
name: BetterFolders.plugin.js
version: 0.0.10
description: Multi-surface admin, cloud, bot host, login, and secure chat server.
lastModified: 2026-05-04T20:22:59.632Z
checksum: a84dd09b7d0ad37666b2a66f1a07dd04c9bd3b625933b0dd3a80921037dbe01d
FILE META END
*/
/**
* @name BetterFolders
* @author Zerthox
* @description Adds new functionality to server folders. Custom Folder Icons. Close other folders on open.
* @version 3.8.1
* @invite J6wTJJ5fp
* @website https://github.com/Zerthox/BetterDiscord-Plugins
* @source https://github.com/Zerthox/BetterDiscord-Plugins/tree/master/src/BetterFolders
* @updateUrl https://headcraft.cloud/better-discord/BetterFolders.plugin.js
*/
/*@cc_on @if (@_jscript)
var pluginName = WScript.ScriptName.split(".")[0];
var shell = WScript.CreateObject("WScript.Shell");
shell.Popup(
"Do NOT run scripts from the internet with the Windows Script Host!\nMove this file to your BetterDiscord plugins folder.",
0,
pluginName + ": Warning!",
0x1030,
);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var pluginsPath = shell.expandEnvironmentStrings("%appdata%\\BetterDiscord\\plugins");
if (!fso.FolderExists(pluginsPath)) {
var popup = shell.Popup(
"Unable to find BetterDiscord on your computer.\nOpen the download page of BetterDiscord?",
0,
pluginName + ": BetterDiscord not found",
0x34,
);
if (popup === 6) {
shell.Exec('explorer "https://betterdiscord.app"');
}
} else if (WScript.ScriptFullName === pluginsPath + "\\" + WScript.ScriptName) {
shell.Popup(
'This plugin is already in the correct folder.\nNavigate to the "Plugins" settings tab in Discord and enable it there.',
0,
pluginName,
0x40,
);
} else {
var popup = shell.Popup("Open the BetterDiscord plugins folder?", 0, pluginName, 0x34);
if (popup === 6) {
shell.Exec("explorer " + pluginsPath);
}
}
WScript.Quit();
@else @*/
'use strict';
let meta = null;
const getMeta = () => {
if (meta) {
return meta;
}
else {
throw Error("Accessing meta before initialization");
}
};
const setMeta = (newMeta) => {
meta = newMeta;
};
const load = (key) => BdApi.Data.load(getMeta().name, key);
const save = (key, value) => BdApi.Data.save(getMeta().name, key, value);
const checkObjectValues = (target) => target !== window && target instanceof Object && target.constructor?.prototype !== target;
const byEntry = (filter, every = false) => {
return ((target, ...args) => {
if (checkObjectValues(target)) {
const values = Object.values(target);
return values.length > 0 && values[every ? "every" : "some"]((value) => filter(value, ...args));
}
else {
return false;
}
});
};
const byName$1 = (name) => {
return (target) => (target?.displayName ?? target?.constructor?.displayName) === name;
};
const byKeys$1 = (...keys) => {
return (target) => target instanceof Object && keys.every((key) => key in target);
};
const bySource$1 = (...fragments) => {
return (target) => {
while (target instanceof Object && "$$typeof" in target) {
target = target.render ?? target.type;
}
if (target instanceof Function) {
const source = target.toString();
const renderSource = target.prototype?.render?.toString();
return fragments.every((fragment) => typeof fragment === "string"
? source.includes(fragment) || renderSource?.includes(fragment)
: fragment(source) || (renderSource && fragment(renderSource)));
}
else {
return false;
}
};
};
const confirm = (title, content, options = {}) => BdApi.UI.showConfirmationModal(title, content, options);
const mappedProxy = (target, mapping) => {
const map = new Map(Object.entries(mapping));
return new Proxy(target, {
get(target, prop) {
return target[map.get(prop) ?? prop];
},
set(target, prop, value) {
target[map.get(prop) ?? prop] = value;
return true;
},
deleteProperty(target, prop) {
delete target[map.get(prop) ?? prop];
map.delete(prop);
return true;
},
has(target, prop) {
return map.has(prop) || prop in target;
},
ownKeys() {
return [...map.keys(), ...Object.keys(target)];
},
getOwnPropertyDescriptor(target, prop) {
return Object.getOwnPropertyDescriptor(target, map.get(prop) ?? prop);
},
defineProperty(target, prop, attributes) {
Object.defineProperty(target, map.get(prop) ?? prop, attributes);
return true;
},
});
};
const find = (filter, { resolve = true, entries = false } = {}) => BdApi.Webpack.getModule(filter, {
defaultExport: resolve,
searchExports: entries,
});
const byName = (name, options) => find(byName$1(name), options);
const byKeys = (keys, options) => find(byKeys$1(...keys), options);
const bySource = (contents, options) => find(bySource$1(...contents), options);
const resolveKey = (target, filter) => [
target,
(target ? Object.entries(target).find(([, value]) => filter(value))?.[0] : null),
];
const findWithKey = (filter) => resolveKey(find(byEntry(filter)), filter);
const demangle = (mapping, required, proxy = false) => {
const req = Object.keys(mapping);
const found = find((target) => checkObjectValues(target)
&& req.every((req) => Object.values(target).some((value) => mapping[req](value))));
return proxy
? mappedProxy(found, Object.fromEntries(Object.entries(mapping).map(([key, filter]) => [
key,
Object.entries(found ?? {}).find(([, value]) => filter(value))?.[0],
])))
: Object.fromEntries(Object.entries(mapping).map(([key, filter]) => [
key,
Object.values(found ?? {}).find((value) => filter(value)),
]));
};
let controller = new AbortController();
const waitFor = (filter, { resolve = true, entries = false } = {}) => BdApi.Webpack.waitForModule(filter, {
signal: controller.signal,
defaultExport: resolve,
searchExports: entries,
});
const abort = () => {
controller.abort();
controller = new AbortController();
};
const COLOR = "#3a71c1";
const print = (output, ...data) => output(`%c[${getMeta().name}] %c${getMeta().version ? `(v${getMeta().version})` : ""}`, `color: ${COLOR}; font-weight: 700;`, "color: #666; font-size: .8em;", ...data);
const log = (...data) => print(console.log, ...data);
const warn = (...data) => print(console.warn, ...data);
const error = (...data) => print(console.error, ...data);
let manualPatches = [];
const addManual = (cancel, name) => {
manualPatches.push(cancel);
};
const patch = (type, object, method, callback, options) => {
const original = object?.[method];
const name = options.name ?? String(method);
if (!(original instanceof Function)) {
if (options.force && !original) {
warn(`Forcing patch on ${name}`);
object[method] = function noop() { };
addManual(() => {
object[method] = original;
});
}
else {
throw TypeError(`patch target ${name} is ${original} not function`);
}
}
const cancel = BdApi.Patcher[type](getMeta().name, object, method, options.once
? (context, args, result) => {
const newResult = callback({ cancel, original, context, args, result });
cancel();
return newResult;
}
: (context, args, result) => callback({ cancel, original, context, args, result }));
if (!options.silent) {
log(`Patched ${name}`);
}
return cancel;
};
const instead = (object, method, callback, options = {}) => patch("instead", object, method, callback, options);
const after = (object, method, callback, options = {}) => patch("after", object, method, callback, options);
const unpatchAll = () => {
if (manualPatches.length + BdApi.Patcher.getPatchesByCaller(getMeta().name).length > 0) {
BdApi.Patcher.unpatchAll(getMeta().name);
for (const cancel of manualPatches) {
cancel();
}
manualPatches = [];
log("Unpatched all");
}
};
const inject = (styles) => {
if (typeof styles === "string") {
BdApi.DOM.addStyle(getMeta().name, styles);
}
};
const clear = () => BdApi.DOM.removeStyle(getMeta().name);
const ClientActions = /* @__PURE__ */ byKeys(["toggleGuildFolderExpand"]);
const SortedGuildStore = /* @__PURE__ */ byName("SortedGuildStore");
const ExpandedGuildFolderStore =
/* @__PURE__ */ byName("ExpandedGuildFolderStore");
const { React } = BdApi;
const Button = /* @__PURE__ */ byKeys(["Colors", "Link"], { entries: true });
const Flex = /* @__PURE__ */ byKeys(["Child", "Justify", "Align"], { entries: true });
const FormItem = /* @__PURE__ */ bySource(["titleClassName:", "required:"], { entries: true });
const FormSwitch = /* @__PURE__ */ bySource(["checked:", "innerRef:", "layout:"], {
entries: true,
});
const FormDivider = /* @__PURE__ */ bySource(["marginTop:", (source) => /{className:.,gap:.}=/.test(source)], {
entries: true,
});
const FormText = /* @__PURE__ */ bySource(["type:", "style:", "disabled:", "variant:", ".DEFAULT"], {
entries: true,
});
const margins = /* @__PURE__ */ byKeys(["marginBottom40", "marginTop4"]);
const { RadioGroup} = /* @__PURE__ */ demangle({
RadioGroup: bySource$1((source) => /{label:.,description:.,required:./.test(source)),
getRadioAttributes: bySource$1(`role:"radio"`),
});
const TextInput = /* @__PURE__ */ bySource(["placeholder", "maxLength", "clearable"], { entries: true });
const ImageInput = /* @__PURE__ */ find((target) => typeof target.defaultProps?.multiple === "boolean" && typeof target.defaultProps?.maxFileSizeBytes === "number");
const replaceElement = (target, replace) => {
target.type = replace.type;
target.key = replace.key ?? target.key;
target.props = replace.props;
};
const queryTree = (node, predicate) => {
const worklist = [node].flat();
while (worklist.length !== 0) {
const node = worklist.shift();
if (React.isValidElement(node)) {
if (predicate(node)) {
return node;
}
const children = node?.props?.children;
if (children) {
worklist.push(...[children].flat());
}
}
}
return null;
};
const queryTreeForParent = (tree, predicate) => {
let childIndex = -1;
const parent = queryTree(tree, (node) => {
const children = node?.props?.children;
if (children instanceof Array) {
const index = children.findIndex(predicate);
if (index > -1) {
childIndex = index;
return true;
}
}
});
return [parent, childIndex];
};
const getFiber = (node) => {
const key = Object.keys(node).find((key) => key.startsWith("__reactFiber"));
return node?.[key];
};
const queryFiber = (fiber, predicate, direction = "up" , depth = 30) => {
if (depth < 0) {
return null;
}
if (predicate(fiber)) {
return fiber;
}
if (direction === "up" || direction === "both" ) {
let count = 0;
let parent = fiber.return;
while (parent && count < depth) {
if (predicate(parent)) {
return parent;
}
count++;
parent = parent.return;
}
}
if (direction === "down" || direction === "both" ) {
let child = fiber.child;
while (child) {
const result = queryFiber(child, predicate, "down" , depth - 1);
if (result) {
return result;
}
child = child.sibling;
}
}
return null;
};
const findOwner = (fiber, depth = 50) => {
return queryFiber(fiber, (node) => node?.stateNode instanceof React.Component, "up" , depth);
};
const forceFullRerender = (fiber) => new Promise((resolve) => {
const owner = findOwner(fiber);
if (owner) {
const { stateNode } = owner;
instead(stateNode, "render", () => null, { once: true, silent: true });
stateNode.forceUpdate(() => stateNode.forceUpdate(() => resolve(true)));
}
else {
resolve(false);
}
});
const SettingsContainer = ({ name, children, onReset }) => (React.createElement("div", null,
children,
onReset ? (React.createElement(React.Fragment, null,
React.createElement(FormDivider, { gap: 20 }),
React.createElement(Flex, { justify: Flex.Justify.END },
React.createElement(Button, { size: Button.Sizes.SMALL, onClick: () => confirm(name, "Reset all settings?", {
onConfirm: onReset,
}) }, "Reset")))) : null));
class SettingsStore {
defaults;
current;
onLoad;
listeners = new Set();
constructor(defaults, onLoad) {
this.defaults = defaults;
this.onLoad = onLoad;
}
load() {
this.current = { ...this.defaults, ...load("settings") };
this.onLoad?.();
this._dispatch(false);
}
_dispatch(save$1) {
for (const listener of this.listeners) {
listener(this.current);
}
if (save$1) {
save("settings", this.current);
}
}
getCurrent = () => this.current;
update = (settings) => {
const update = typeof settings === "function" ? settings(this.current) : settings;
this.current = { ...this.current, ...update };
this._dispatch(true);
};
reset() {
this.current = { ...this.defaults };
this._dispatch(true);
}
delete(...keys) {
this.current = { ...this.current };
for (const key of keys) {
delete this.current[key];
}
this._dispatch(true);
}
useCurrent() {
return React.useSyncExternalStore(this.addListenerEffect, this.getCurrent);
}
useSelector(selector, deps = null, compare = Object.is) {
const state = React.useRef(null);
const snapshot = React.useCallback(() => {
const next = selector(this.current);
if (!compare(state.current, next)) {
state.current = next;
}
return state.current;
}, deps ?? [selector]);
return React.useSyncExternalStore(this.addListenerEffect, snapshot);
}
useState() {
const current = this.useCurrent();
return [current, this.update];
}
useStateWithDefaults() {
const current = this.useCurrent();
return [current, this.defaults, this.update];
}
useListener(listener, deps) {
React.useEffect(() => this.addListenerEffect(listener), deps ?? [listener]);
}
addListener(listener) {
this.listeners.add(listener);
return listener;
}
addListenerEffect = (listener) => {
this.addListener(listener);
return () => this.removeListener(listener);
};
removeListener(listener) {
this.listeners.delete(listener);
}
removeAllListeners() {
this.listeners.clear();
}
addReactChangeListener = this.addListener;
removeReactChangeListener = this.removeListener;
}
const createSettings = (defaults, onLoad) => new SettingsStore(defaults, onLoad);
const createPlugin = (plugin) => (meta) => {
setMeta(meta);
const { start, stop, styles, Settings, SettingsPanel } = plugin instanceof Function ? plugin(meta) : plugin;
Settings?.load();
return {
start() {
log("Enabled");
inject(styles);
start?.();
},
stop() {
abort();
unpatchAll();
clear();
stop?.();
log("Disabled");
},
getSettingsPanel: SettingsPanel
? () => (React.createElement(SettingsContainer, { name: meta.name, onReset: Settings ? () => Settings.reset() : null },
React.createElement(SettingsPanel, null)))
: null,
};
};
const Settings = createSettings({
closeOnOpen: false,
folders: {},
});
const css = ".customIcon-BetterFolders{box-sizing:border-box;border-radius:var(--radius-lg);width:var(--guildbar-folder-size);height:var(--guildbar-folder-size);padding:var(--custom-folder-preview-padding);background-size:contain;background-position:center;background-repeat:no-repeat}";
const styles = {
customIcon: "customIcon-BetterFolders"
};
const folderStyles = byKeys(["folderIcon", "folderIconWrapper", "folderPreviewWrapper"]);
const renderIcon = (data) => (React.createElement("div", { className: styles.customIcon, style: { backgroundImage: data?.icon ? `url(${data.icon})` : null } }));
const BetterFolderIcon = ({ data, childProps, FolderIcon }) => {
if (FolderIcon) {
const result = FolderIcon(childProps);
if (data?.icon) {
const replace = renderIcon(data);
const iconWrapper = queryTree(result, (node) => node?.props?.className === folderStyles.folderIconWrapper);
if (iconWrapper) {
replaceElement(iconWrapper, replace);
}
else {
error("Failed to find folderIconWrapper element");
}
if (data.always) {
const previewWrapper = queryTree(result, (node) => node?.props?.className === folderStyles.folderPreviewWrapper);
if (previewWrapper) {
replaceElement(previewWrapper, replace);
}
else {
error("Failed to find folderPreviewWrapper element");
}
}
}
return result;
}
else {
return null;
}
};
const compareFolderData = (a, b) => a?.icon === b?.icon && a?.always === b?.always;
const ConnectedBetterFolderIcon = ({ folderId, ...props }) => {
const data = Settings.useSelector((current) => current.folders[folderId], [folderId], compareFolderData);
return React.createElement(BetterFolderIcon, { data: data, ...props });
};
const BetterFolderUploader = ({ icon, always, onChange }) => (React.createElement(React.Fragment, null,
React.createElement(Flex, { align: Flex.Align.CENTER, className: margins.marginBottom20 },
React.createElement(Button, { color: Button.Colors.WHITE, look: Button.Looks.OUTLINED },
"Upload Image",
React.createElement(ImageInput, { onChange: (img) => onChange({ icon: img, always }) })),
React.createElement(FormText, { type: "description", style: { margin: "0 10px 0 40px" } }, "Preview:"),
renderIcon({ icon})),
React.createElement(FormSwitch, { checked: always, onChange: (checked) => onChange({ icon, always: checked }), label: "Always display icon" })));
const mountFolderSettingsPatch = ({ context, }) => {
const { props: { folderId }, state, } = context;
if (state.iconType) {
warn("FolderSettings already patched in mount");
return;
}
const original = context.handleSubmit;
context.handleSubmit = (...args) => {
const result = original(...args);
const { folders } = Settings.current;
if (state.iconType === "custom" && state.icon) {
folders[folderId] = { icon: state.icon, always: state.always };
Settings.update({ folders });
}
else if ((state.iconType === "default" || !state.icon) && folders[folderId]) {
delete folders[folderId];
Settings.update({ folders });
}
return result;
};
const { icon = null, always = false } = Settings.current.folders[folderId] ?? {};
context.setState({
iconType: icon ? "custom" : "default" ,
icon,
always,
});
};
const renderFolderSettingsPatch = ({ context, result, }) => {
const { props: { folderId }, state, } = context;
const [parent] = queryTreeForParent(result, (node) => node?.type === TextInput);
if (!parent) {
warn("Unable to find text input parent");
return;
}
const { children } = parent.props;
children.push(React.createElement(FormItem, { title: "Icon" },
React.createElement(RadioGroup, { value: state.iconType, options: [
{ value: "default" , name: "Default Icon" },
{ value: "custom" , name: "Custom Icon" },
], onChange: ({ value }) => context.setState({ iconType: value }) })));
if (state.iconType === "custom" ) {
const tree = SortedGuildStore.getGuildsTree();
children.push(React.createElement(FormItem, { title: "Custom Icon" },
React.createElement(BetterFolderUploader, { icon: state.icon, always: state.always, folderNode: tree.nodes[folderId], onChange: ({ icon, always }) => context.setState({ icon, always }) })));
}
};
const guildStyles = byKeys(["guilds", "base"]);
const getGuildsOwner = () => {
const node = document.getElementsByClassName(guildStyles.guilds)?.[0];
if (node) {
const owner = findOwner(getFiber(node));
if (!owner) {
warn("Unable to find guilds owner");
}
return owner;
}
else {
warn("Unable to find guilds node");
}
return null;
};
const triggerRerender = async (guildsFiber) => {
if (guildsFiber && (await forceFullRerender(guildsFiber))) {
log("Rerendered guilds");
}
else {
warn("Unable to rerender guilds");
}
};
const index = createPlugin({
start() {
let FolderIcon = null;
const guildsOwner = getGuildsOwner();
const FolderIconWrapper = findWithKey(bySource$1("folderNode:", "folderGroupId:", "folderName"));
after(...FolderIconWrapper, ({ args: [props], result }) => {
const icon = queryTree(result, (node) => node?.props?.folderNode);
if (!icon) {
return error("Unable to find FolderIcon component");
}
if (!FolderIcon) {
log("Found FolderIcon component");
FolderIcon = icon.type;
}
replaceElement(icon, React.createElement(ConnectedBetterFolderIcon, { folderId: props.folderNode.id, childProps: icon.props, FolderIcon: FolderIcon }));
}, { name: "FolderIconWrapper" });
triggerRerender(guildsOwner);
after(ClientActions, "toggleGuildFolderExpand", ({ original, args: [folderId] }) => {
if (Settings.current.closeOnOpen) {
for (const id of ExpandedGuildFolderStore.getExpandedFolders()) {
if (id !== folderId) {
original(id);
}
}
}
});
waitFor(bySource$1(".folderName", ".onClose"), { entries: true }).then((FolderSettings) => {
after(FolderSettings.prototype, "render", renderFolderSettingsPatch, {
name: "FolderSettings render",
});
after(FolderSettings.prototype, "componentDidMount", mountFolderSettingsPatch, {
name: "FolderSettings mount",
force: true,
});
});
},
stop() {
triggerRerender(getGuildsOwner());
},
styles: css,
Settings,
SettingsPanel: () => {
const [{ closeOnOpen }, setSettings] = Settings.useState();
return (React.createElement(FormSwitch, { label: "Close on open", description: "Close other folders when opening a new folder", checked: closeOnOpen, onChange: (checked) => {
if (checked) {
for (const id of Array.from(ExpandedGuildFolderStore.getExpandedFolders()).slice(1)) {
ClientActions.toggleGuildFolderExpand(id);
}
}
setSettings({ closeOnOpen: checked });
} }));
},
});
module.exports = index;
/*@end @*/