-
Notifications
You must be signed in to change notification settings - Fork 1
/
PingNotification.plugin.js
1356 lines (1244 loc) · 57.3 KB
/
PingNotification.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
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @name PingNotification
* @author DaddyBoard
* @version 7.2.2
* @description Show in-app notifications for anything you would hear a ping for.
* @website https://github.com/DaddyBoard/PingNotification
* @source https://raw.githubusercontent.com/DaddyBoard/PingNotification/main/PingNotification.plugin.js
* @updateUrl https://github.com/DaddyBoard/PingNotification/blob/main/PingNotification.plugin.js
* @invite ggNWGDV7e2
*/
const { React, Webpack, ReactDOM } = BdApi;
const UserStore = Webpack.getStore("UserStore");
const ChannelStore = Webpack.getStore("ChannelStore");
const GuildStore = Webpack.getStore("GuildStore");
const SelectedChannelStore = Webpack.getStore("SelectedChannelStore");
const RelationshipStore = Webpack.getStore("RelationshipStore");
const UserGuildSettingsStore = Webpack.getStore("UserGuildSettingsStore");
const transitionTo = Webpack.getByStrings(["transitionTo - Transitioning to"],{searchExports:true});
const MessageParserModule = Webpack.getModule(m => m.defaultRules && m.parse);
const parse = MessageParserModule?.parse;
const GuildMemberStore = Webpack.getModule(m => m.getMember);
const Dispatcher = BdApi.Webpack.getByKeys("subscribe", "dispatch")
const MessageStore = BdApi.Webpack.getStore("MessageStore");
const MessageAccessories = BdApi.Webpack.getByPrototypeKeys("renderEmbeds", {searchExports:true});
const MessageActions = BdApi.Webpack.getByKeys("fetchMessage", "deleteMessage");
const ChannelAckModule = (() => {
const filter = BdApi.Webpack.Filters.byStrings("type:\"CHANNEL_ACK\",channelId", "type:\"BULK_ACK\",channels:");
const module = BdApi.Webpack.getModule((e, m) => filter(BdApi.Webpack.modules[m.id]));
return Object.values(module).find(m => m.toString().includes("type:\"CHANNEL_ACK\",channelId"));
})();
const config = {
changelog: [
{
title: "Improvements",
type: "improved",
items: [
"Reverted back to 7.2.0 code (before theming and close button changes)",
"7.2.1 introduced multiple janky formatting issues with code blocks, names clashing with close button, etc.",
"I will look into a better way of re-structuring this PR/Request and add back in a future update. If it works for you, feel free to downgrade to 7.2.1 and change the meta version to 7.2.2 to stop updates"
]
}
],
settings: [
{
type: "category",
id: "behavior",
name: "Behavior Settings",
collapsible: true,
shown: false,
settings: [
{
type: "slider",
id: "duration",
name: "Notification Duration",
note: "How long notifications stay on screen (in seconds)",
value: 15,
min: 1,
max: 60,
markers: [1, 20, 40, 60],
units: "s",
defaultValue: 15,
stickToMarkers: false
},
{
type: "dropdown",
id: "popupLocation",
name: "Popup Location",
note: "Where notifications appear on screen",
value: "bottomRight",
options: [
{ label: "Top Left", value: "topLeft" },
{ label: "Top Right", value: "topRight" },
{ label: "Bottom Left", value: "bottomLeft" },
{ label: "Bottom Right", value: "bottomRight" }
]
},
{
type: "switch",
id: "readChannelOnClose",
name: "Mark Channel as Read on Close",
note: "Automatically mark the channel as read when closing a notification",
value: false
},
{
type: "switch",
id: "disableMediaInteraction",
name: "Disable Media Interaction",
note: "Make all clicks navigate to the message instead of allowing media interaction",
value: false
},
{
type: "switch",
id: "allowNotificationsInCurrentChannel",
name: "Current Channel Notifications",
note: "Show notifications for the channel you're currently viewing",
value: false
}
]
},
{
type: "category",
id: "appearance",
name: "Appearance Settings",
collapsible: true,
shown: false,
settings: [
{
type: "switch",
id: "privacyMode",
name: "Privacy Mode",
note: "Blur notification content until hovered",
value: false
},
{
type: "switch",
id: "applyNSFWBlur",
name: "Blur NSFW Content",
note: "Blur content from NSFW channels",
value: false
},
{
type: "switch",
id: "showTimer",
name: "Show Timer",
note: "Show the seconds left of the notification(numbers, not the progress bar)",
value: true
}
]
},
{
type: "category",
id: "userStyling",
name: "User Styling",
collapsible: true,
shown: false,
settings: [
{
type: "switch",
id: "coloredUsernames",
name: "Colored Usernames",
note: "Show usernames in their role colors",
value: true
},
{
type: "switch",
id: "showNicknames",
name: "Show Nicknames",
note: "Use server nicknames instead of usernames",
value: true
},
{
type: "switch",
id: "usernameOrDisplayName",
name: "Use Display Name",
note: "Show the display name instead of the username. On = Display Name, Off = Username",
value: false
}
]
},
{
type: "category",
id: "advancedSettings",
name: "Advanced Settings",
collapsible: true,
shown: false,
settings: [
{
type: "slider",
id: "maxWidth",
name: "Notification Width",
note: "Default: 370px",
value: 370,
min: 100,
max: 400,
markers: [100, 200, 300, 370, 400],
units: "px",
defaultValue: 370,
stickToMarkers: false
},
{
type: "slider",
id: "maxHeight",
name: "Notification Height",
note: "Default: 300px",
value: 300,
min: 200,
max: 600,
markers: [200, 300, 400, 500, 600],
units: "px",
defaultValue: 300,
stickToMarkers: false
}
]
}
]
};
module.exports = class PingNotification {
constructor(meta) {
this.meta = meta;
this.defaultSettings = {
duration: 15000,
maxWidth: 370,
maxHeight: 300,
popupLocation: "bottomRight",
allowNotificationsInCurrentChannel: false,
privacyMode: false,
coloredUsernames: true,
showNicknames: true,
applyNSFWBlur: false,
readChannelOnClose: false,
disableMediaInteraction: false,
showTimer: true,
usernameOrDisplayName: true
};
this.settings = this.loadSettings();
this.activeNotifications = [];
this.onMessageReceived = this.onMessageReceived.bind(this);
}
start() {
const lastVersion = BdApi.Data.load('PingNotification', 'lastVersion');
if (lastVersion !== this.meta.version) {
BdApi.UI.showChangelogModal({
title: this.meta.name,
subtitle: this.meta.version,
changes: config.changelog
});
BdApi.Data.save('PingNotification', 'lastVersion', this.meta.version);
}
this.messageCreateHandler = async (event) => {
if (!event?.message) return;
try {
let message = MessageStore.getMessage(event.message.channel_id, event.message.id) ||
await MessageActions.fetchMessage({
channelId: event.message.channel_id,
messageId: event.message.id
});
if (message.messageReference) {
const referencedMessage = MessageStore.getMessage(
message.messageReference.channel_id,
message.messageReference.message_id
) || await MessageActions.fetchMessage({
channelId: message.messageReference.channel_id,
messageId: message.messageReference.message_id
});
if (referencedMessage) {
message.messageReference.author = referencedMessage.author;
message.messageReference.message = referencedMessage;
}
}
if (message) {
this.onMessageReceived(message);
}
} catch (error) {
console.error("PingNotification: Error fetching message", error);
}
};
this.messageUpdateHandler = async (event) => {
if (!event?.message) return;
const activeNotification = this.activeNotifications.find(n =>
n.messageId === event.message.id && n.channelId === event.message.channel_id
);
if (activeNotification) {
try {
let updatedMessage = MessageStore.getMessage(event.message.channel_id, event.message.id) ||
await MessageActions.fetchMessage({
channelId: event.message.channel_id,
messageId: event.message.id
});
if (updatedMessage.messageReference) {
const referencedMessage = MessageStore.getMessage(
updatedMessage.messageReference.channel_id,
updatedMessage.messageReference.message_id
) || await MessageActions.fetchMessage({
channelId: updatedMessage.messageReference.channel_id,
messageId: updatedMessage.messageReference.message_id
});
if (referencedMessage) {
updatedMessage.messageReference.message = referencedMessage;
updatedMessage.messageReference.author = referencedMessage.author;
}
}
if (updatedMessage) {
this.updateNotification(activeNotification, updatedMessage);
}
} catch (error) {
console.error("PingNotification: Error fetching updated message", error);
}
}
};
this.reactionAddHandler = async (event) => {
if (!event?.messageId) return;
const activeNotification = this.activeNotifications.find(n =>
n.messageId === event.messageId && n.channelId === event.channelId
);
if (activeNotification) {
try {
const updatedMessage = MessageStore.getMessage(event.channelId, event.messageId) ||
await MessageActions.fetchMessage({
channelId: event.channelId,
messageId: event.messageId
});
if (updatedMessage) {
this.updateNotification(activeNotification, updatedMessage);
}
} catch (error) {
console.error("PingNotification: Error fetching message for reaction update", error);
}
}
};
this.reactionRemoveHandler = this.reactionAddHandler;
Dispatcher.subscribe("MESSAGE_CREATE", this.messageCreateHandler);
Dispatcher.subscribe("MESSAGE_UPDATE", this.messageUpdateHandler);
Dispatcher.subscribe("MESSAGE_REACTION_ADD", this.reactionAddHandler);
Dispatcher.subscribe("MESSAGE_REACTION_REMOVE", this.reactionRemoveHandler);
BdApi.DOM.addStyle("PingNotificationStyles", this.css);
}
stop() {
if (Dispatcher) {
Dispatcher.unsubscribe("MESSAGE_CREATE", this.messageCreateHandler);
Dispatcher.unsubscribe("MESSAGE_UPDATE", this.messageUpdateHandler);
Dispatcher.unsubscribe("MESSAGE_REACTION_ADD", this.reactionAddHandler);
Dispatcher.unsubscribe("MESSAGE_REACTION_REMOVE", this.reactionRemoveHandler);
}
this.removeAllNotifications();
BdApi.DOM.removeStyle("PingNotificationStyles");
}
loadSettings() {
const savedSettings = BdApi.Data.load('PingNotification', 'settings');
return Object.assign({}, this.defaultSettings, savedSettings);
}
saveSettings(newSettings) {
this.settings = newSettings;
BdApi.Data.save('PingNotification', 'settings', newSettings);
}
css = `
.ping-notification {
background-color: rgba(30, 31, 34, 0.95);
color: var(--text-normal);
border-radius: 12px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(0, 0, 0, 0.1), 0 0 1px rgba(255, 255, 255, 0.1);
z-index: 9999;
overflow: hidden;
backdrop-filter: blur(10px);
animation: notificationPop 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
transform: translateZ(0);
}
@keyframes notificationPop {
0% { transform: scale(0.9) translateZ(0); opacity: 0; }
100% { transform: scale(1) translateZ(0); opacity: 1; }
}
.ping-notification-content {
padding: 12px;
cursor: pointer;
position: relative;
color: var(--text-normal);
}
.ping-notification-header {
display: flex;
align-items: center;
margin-bottom: 8px;
}
.ping-notification-avatar {
width: 24px;
height: 24px;
border-radius: 50%;
margin-right: 8px;
}
.ping-notification-title {
flex-grow: 1;
font-weight: bold;
font-size: 14px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.ping-notification-close {
cursor: pointer;
font-size: 18px;
padding: 0 4px;
}
.ping-notification-body {
font-size: 15px;
margin-bottom: 8px;
word-break: break-word;
scrollbar-width: none;
-ms-overflow-style: none;
}
.ping-notification-body::-webkit-scrollbar {
display: none;
}
.ping-notification-content.privacy-mode .ping-notification-body,
.ping-notification-content.privacy-mode .ping-notification-attachment {
filter: blur(20px);
transition: filter 0.3s ease;
position: relative;
}
.ping-notification-hover-text {
position: absolute;
top: calc(50% + 20px);
left: 50%;
transform: translate(-50%, -50%);
color: var(--text-normal);
font-size: 14px;
font-weight: 500;
pointer-events: none;
opacity: 1;
transition: opacity 0.3s ease;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
white-space: nowrap;
z-index: 100;
background-color: rgba(0, 0, 0, 0.7);
padding: 4px 8px;
border-radius: 4px;
}
.ping-notification-content.privacy-mode:hover .ping-notification-hover-text {
opacity: 0;
}
.ping-notification-content.privacy-mode:hover .ping-notification-body,
.ping-notification-content.privacy-mode:hover .ping-notification-attachment {
filter: blur(0);
}
.ping-notification .spoilerContent_aa9639,
.ping-notification .spoilerMarkdownContent_aa9639 {
background-color: rgba(255, 255, 255, 0.15);
border-radius: 3px;
transition: background-color 0.2s ease;
}
.ping-notification-media img,
.ping-notification-media video,
.ping-notification-media [class*="clickableMedia"],
.ping-notification-media [class*="imageContainer"],
.ping-notification-media [class*="videoContainer"],
.ping-notification-media [class*="wrapper"],
.ping-notification-media [class*="imageWrapper"] {
max-width: 100% !important;
height: auto !important;
object-fit: contain !important;
pointer-events: auto !important;
-webkit-user-drag: none !important;
user-drag: none !important;
-webkit-touch-callout: none !important;
}
.ping-notification-media [class*="spoilerContent"],
.ping-notification-media [class*="hiddenSpoilers"] {
max-width: 100% !important;
max-height: 250px !important;
width: auto !important;
height: auto !important;
}
.ping-notification-media [class*="draggableWrapper"] {
pointer-events: none !important;
}
.ping-notification [class*="hoverButtonGroup_d0395d"],
.ping-notification [class*="codeActions_f8f345"],
.ping-notification [class*="reactionBtn"] {
display: none !important;
}
.ping-notification code {
background-color: var(--background-secondary);
border-radius: 3px;
padding: 0.2em 0.4em;
margin: 0;
font-size: 85%;
font-family: var(--font-code);
color: var(--text-normal);
}
.ping-notification pre {
background-color: var(--background-secondary);
border-radius: 4px;
padding: 0.5em;
margin: 0.5em 0;
overflow-x: auto;
}
.ping-notification pre code {
background-color: transparent;
padding: 0;
border-radius: 0;
font-size: 85%;
color: var(--text-normal);
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.45;
}
.ping-notification-media.disable-interaction * {
pointer-events: none !important;
user-select: none !important;
-webkit-user-drag: none !important;
}
.ping-notification-media.disable-interaction [class*="imageWrapper"],
.ping-notification-media.disable-interaction [class*="clickableMedia"],
.ping-notification-media.disable-interaction [class*="imageContainer"],
.ping-notification-media.disable-interaction [class*="videoContainer"],
.ping-notification-media.disable-interaction [class*="wrapper"] {
cursor: pointer !important;
}
`;
onMessageReceived(message) {
if (!message?.channel_id) return;
const channel = ChannelStore.getChannel(message.channel_id);
const currentUser = UserStore.getCurrentUser();
if (!channel || message.author.id === currentUser.id) return;
if (this.shouldNotify(message, channel, currentUser)) {
this.showNotification(message, channel);
}
}
shouldNotify(message, channel, currentUser) {
if (!this.settings.allowNotificationsInCurrentChannel &&
channel.id === SelectedChannelStore.getChannelId()) {
return false;
}
if (message.author.id === currentUser.id) return false;
if (message.flags && (message.flags & 64) === 64) return false;
if (!channel.guild_id) {
const isGroupDMMuted = UserGuildSettingsStore.isChannelMuted(null, channel.id);
const isUserBlocked = RelationshipStore.isBlocked(message.author.id);
return !isGroupDMMuted && !isUserBlocked;
}
if (UserGuildSettingsStore.isGuildOrCategoryOrChannelMuted(channel.guild_id, channel.id)) {
return false;
}
const channelOverride = UserGuildSettingsStore.getChannelMessageNotifications(channel.guild_id, channel.id);
const guildDefault = UserGuildSettingsStore.getMessageNotifications(channel.guild_id);
const finalSetting = channelOverride === 3 ? guildDefault : channelOverride;
const isDirectlyMentioned = message.mentions?.includes(currentUser.id);
const isEveryoneMentioned = message.mentionEveryone &&
!UserGuildSettingsStore.isSuppressEveryoneEnabled(channel.guild_id);
let isRoleMentioned = false;
if (message.mentionRoles?.length > 0 &&
!UserGuildSettingsStore.isSuppressRolesEnabled(channel.guild_id)) {
const member = GuildMemberStore.getMember(channel.guild_id, currentUser.id);
if (member?.roles) {
isRoleMentioned = message.mentionRoles.some(roleId =>
member.roles.includes(roleId)
);
}
}
const isMentioned = isDirectlyMentioned || isEveryoneMentioned || isRoleMentioned;
switch (finalSetting) {
case 0: return true;
case 1: return isMentioned;
case 2: return false;
default: return false;
}
}
showNotification(message, channel) {
const notificationElement = BdApi.DOM.createElement('div', {
className: 'ping-notification',
target: document.body
});
notificationElement.creationTime = Date.now();
notificationElement.channelId = channel.id;
notificationElement.messageId = message.id;
ReactDOM.render(
React.createElement(NotificationComponent, {
message: message,
channel: channel,
settings: this.settings,
onClose: (isManual) => {
notificationElement.manualClose = isManual;
this.removeNotification(notificationElement);
},
onClick: () => {
this.onNotificationClick(channel, message);
this.removeNotification(notificationElement);
},
onImageLoad: () => {
this.adjustNotificationPositions();
},
onSwipe: (direction) => {
const isRightSwipe = direction === 'right';
const isLeftSwipe = direction === 'left';
const isRightLocation = this.settings.popupLocation.endsWith("Right");
const isLeftLocation = this.settings.popupLocation.endsWith("Left");
if ((isRightSwipe && isRightLocation) || (isLeftSwipe && isLeftLocation)) {
this.removeNotification(notificationElement);
}
}
}),
notificationElement
);
this.activeNotifications.push(notificationElement);
this.adjustNotificationPositions();
return notificationElement;
}
removeNotification(notificationElement) {
if (document.body.contains(notificationElement)) {
if (this.settings.readChannelOnClose && notificationElement.manualClose) {
ChannelAckModule(notificationElement.channelId);
}
ReactDOM.unmountComponentAtNode(notificationElement);
document.body.removeChild(notificationElement);
this.activeNotifications = this.activeNotifications.filter(n => n !== notificationElement);
this.adjustNotificationPositions();
}
}
removeAllNotifications() {
this.activeNotifications.forEach(notification => {
if (document.body.contains(notification)) {
ReactDOM.unmountComponentAtNode(notification);
document.body.removeChild(notification);
}
});
this.activeNotifications = [];
}
adjustNotificationPositions() {
const { popupLocation } = this.settings;
let offset = 20;
const isTop = popupLocation.startsWith("top");
const isLeft = popupLocation.endsWith("Left");
const sortedNotifications = [...this.activeNotifications].sort((a, b) => {
return b.creationTime - a.creationTime;
});
sortedNotifications.forEach((notification) => {
const height = notification.offsetHeight;
notification.style.transition = 'all 0.3s ease-in-out';
notification.style.position = 'fixed';
if (isTop) {
notification.style.top = `${offset}px`;
notification.style.bottom = 'auto';
} else {
notification.style.bottom = `${offset}px`;
notification.style.top = 'auto';
}
if (isLeft) {
notification.style.left = '20px';
notification.style.right = 'auto';
} else {
notification.style.right = '20px';
notification.style.left = 'auto';
}
offset += height + 10;
});
}
onNotificationClick(channel, message) {
const notificationsToRemove = this.activeNotifications.filter(notification =>
notification.channelId === channel.id
);
notificationsToRemove.forEach(notification => {
this.removeNotification(notification);
});
transitionTo(`/channels/${channel.guild_id || "@me"}/${channel.id}/${message.id}`);
}
getSettingsPanel() {
const settingsConfig = structuredClone(config.settings);
settingsConfig.forEach(category => {
if (category.settings) {
category.settings.forEach(setting => {
if (setting.id === 'duration') {
setting.value = this.settings.duration / 1000;
} else {
setting.value = this.settings[setting.id];
}
if (['maxWidth', 'maxHeight', 'showTimer', 'privacyMode', 'popupLocation', 'usernameOrDisplayName'].includes(setting.id)) {
setting.onChange = (value) => {
this.settings[setting.id] = value;
this.saveSettings(this.settings);
const testNotification = this.activeNotifications.find(n => n.isTest);
if (testNotification) {
this.updateNotification(testNotification, testNotification.testMessage, testNotification.testChannel);
} else {
this.showTestNotification();
}
};
}
});
}
});
return BdApi.UI.buildSettingsPanel({
settings: settingsConfig,
onChange: (category, id, value) => {
if (id === 'duration') {
this.settings[id] = value * 1000;
} else {
this.settings[id] = value;
}
this.saveSettings(this.settings);
}
});
}
updateNotification(notificationElement, updatedMessage, channel) {
ReactDOM.render(
React.createElement(NotificationComponent, {
message: updatedMessage,
channel: updatedMessage.isTestMessage ? channel : ChannelStore.getChannel(updatedMessage.channel_id),
settings: this.settings,
onClose: (isManual) => {
notificationElement.manualClose = isManual;
this.removeNotification(notificationElement);
},
onClick: () => {
if (!updatedMessage.isTestMessage) {
this.onNotificationClick(ChannelStore.getChannel(updatedMessage.channel_id), updatedMessage);
}
this.removeNotification(notificationElement);
},
onImageLoad: () => {
this.adjustNotificationPositions();
},
onSwipe: (direction) => {
const isRightSwipe = direction === 'right';
const isLeftSwipe = direction === 'left';
const isRightLocation = this.settings.popupLocation.endsWith("Right");
const isLeftLocation = this.settings.popupLocation.endsWith("Left");
if ((isRightSwipe && isRightLocation) || (isLeftSwipe && isLeftLocation)) {
this.removeNotification(notificationElement);
}
}
}),
notificationElement,
() => {
requestAnimationFrame(() => {
this.adjustNotificationPositions();
});
}
);
}
showTestNotification() {
this.activeNotifications = this.activeNotifications.filter(n => {
if (n.isTest) {
ReactDOM.unmountComponentAtNode(n);
document.body.removeChild(n);
return false;
}
return true;
});
const currentUser = UserStore.getCurrentUser();
const testMessage = {
id: "test-message",
content: "",
plainText: "This is a test notification to help visualize the changes you are making.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n\nSed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
author: currentUser,
timestamp: new Date(),
attachments: [],
embeds: [],
mentions: [],
mention_roles: [],
mention_everyone: false,
messageReference: null,
flags: 0,
isTestMessage: true
};
const testChannel = {
id: "test-channel",
name: "Test Channel",
guild_id: null,
type: 0,
nsfw: false
};
const notification = this.showNotification(testMessage, testChannel);
notification.isTest = true;
notification.testMessage = testMessage;
notification.testChannel = testChannel;
}
}
function NotificationComponent({ message, channel, settings, onClose, onClick, onImageLoad, onSwipe }) {
const guild = channel.guild_id ? GuildStore.getGuild(channel.guild_id) : null;
const member = guild ? GuildMemberStore.getMember(guild.id, message.author.id) : null;
const [remainingTime, setRemainingTime] = React.useState(settings.duration);
const [isPaused, setIsPaused] = React.useState(false);
const notificationTitle = React.useMemo(() => {
let title = '';
const isNSFW = channel.nsfw || channel.nsfw_;
if (channel.guild_id) {
title = guild ? `${guild.name} • #${channel.name}` : `Unknown Server • #${channel.name}`;
} else if (channel.type === 3) {
const recipients = channel.recipients?.map(id => UserStore.getUser(id)).filter(u => u);
const name = channel.name || recipients?.map(u => u.username).join(', ');
title = `Group Chat • ${name}`;
} else {
title = `Direct Message`;
}
if (isNSFW && settings.applyNSFWBlur) {
title += ' • ';
return React.createElement('div', { style: { display: 'flex', alignItems: 'center' } },
title,
React.createElement('span', {
style: {
color: 'rgb(240, 71, 71)',
fontWeight: 'bold',
marginLeft: '4px'
}
}, 'NSFW')
);
}
return title;
}, [channel, guild?.name, settings.applyNSFWBlur]);
const roleColor = React.useMemo(() => {
if (!guild || !member || !member.roles) return null;
const getRoles = Webpack.getModule(m => m.getRole);
const guildRoles = getRoles.getRoles(guild.id);
if (!guildRoles) return null;
const roles = member.roles
.map(roleId => guildRoles[roleId])
.filter(role => role && typeof role.color === 'number' && role.color !== 0);
if (roles.length === 0) return null;
const colorRole = roles.sort((a, b) => (b.position || 0) - (a.position || 0))[0];
return colorRole ? `#${colorRole.color.toString(16).padStart(6, '0')}` : null;
}, [guild?.id, member?.roles]);
const displayName = React.useMemo(() => {
if (settings.showNicknames && member?.nick) {
return member.nick;
}
if (settings.usernameOrDisplayName) {
if (!message.author.globalName) {
return message.author.username;
}
return message.author.globalName;
}
return message.author.username;
}, [settings.showNicknames, member?.nick, message.author.username, settings.usernameOrDisplayName]);
const avatarUrl = React.useMemo(() => {
return message.author.avatar
? `https://cdn.discordapp.com/avatars/${message.author.id}/${message.author.avatar}.png?size=128`
: `https://cdn.discordapp.com/embed/avatars/${parseInt(message.author.discriminator) % 5}.png`;
}, [message.author]);
React.useEffect(() => {
let interval;
if (!isPaused) {
interval = setInterval(() => {
setRemainingTime(prev => {
if (prev <= 100) {
clearInterval(interval);
onClose(false);
return 0;
}
return prev - 100;
});
}, 100);
}
return () => clearInterval(interval);
}, [isPaused, onClose, settings.duration]);
const progress = (remainingTime / settings.duration) * 100;
const getProgressColor = () => {
const green = [67, 181, 129];
const orange = [250, 166, 26];
const red = [240, 71, 71];
let color;
if (progress > 66) {
color = interpolateColor(orange, green, (progress - 66) / 34);
} else if (progress > 33) {
color = interpolateColor(red, orange, (progress - 33) / 33);
} else {
color = red;
}
return color;
};
const interpolateColor = (color1, color2, factor) => {
return color1.map((channel, index) =>
Math.round(channel + (color2[index] - channel) * factor)
);
};
const progressColor = getProgressColor();
const progressColorString = `rgb(${progressColor[0]}, ${progressColor[1]}, ${progressColor[2]})`;
const handleSwipe = (e) => {
const startX = e.touches ? e.touches[0].clientX : e.clientX;
const handleMove = (moveEvent) => {
const currentX = moveEvent.touches ? moveEvent.touches[0].clientX : moveEvent.clientX;
const deltaX = currentX - startX;
const threshold = 100;
if (Math.abs(deltaX) > threshold) {
const isRightSwipe = deltaX > 0;
const isLeftSwipe = deltaX < 0;
const isRightLocation = settings.popupLocation.endsWith("Right");
const isLeftLocation = settings.popupLocation.endsWith("Left");
if ((isRightSwipe && isRightLocation) || (isLeftSwipe && isLeftLocation)) {
document.removeEventListener('mousemove', handleMove);
document.removeEventListener('mouseup', handleEnd);
document.removeEventListener('touchmove', handleMove);
document.removeEventListener('touchend', handleEnd);
onClose(true);
}
}
};
const handleEnd = () => {
document.removeEventListener('mousemove', handleMove);
document.removeEventListener('mouseup', handleEnd);
document.removeEventListener('touchmove', handleMove);
document.removeEventListener('touchend', handleEnd);
};
document.addEventListener('mousemove', handleMove);
document.addEventListener('mouseup', handleEnd);
document.addEventListener('touchmove', handleMove);
document.addEventListener('touchend', handleEnd);
};
const baseWidth = 370;
const baseHeight = 300;
const scaleFactor = Math.min(
Math.max(0.8, settings.maxWidth / baseWidth),
Math.max(0.8, settings.maxHeight / baseHeight)
);
const getDynamicScale = (scale) => {
return 1 + (Math.log1p(scale - 1) * 0.5);
};
const dynamicScale = getDynamicScale(scaleFactor);
const avatarSize = Math.round(40 * dynamicScale);