-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCustomPanelForSendingPictures.plugin.js
1518 lines (1460 loc) · 76.5 KB
/
CustomPanelForSendingPictures.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 CustomPanelForSendingPictures
* @author Japanese Schoolgirl (Lisa)
* @description Adds panel that loads pictures via settings file with used files and links, allowing you to send pictures in chat with or without text by clicking on pictures preview on the panel. Settings file is automatically created on scanning the plugin folder or custom folder (supports subfolders and will show them as sections/groups).
* @authorId 248447383828955137
* @authorLink https://github.com/Japanese-Schoolgirl
* @invite nZMbKkw
* @website https://github.com/Japanese-Schoolgirl/DiscordPlugin-CustomPanelForSendingPictures
* @source https://raw.githubusercontent.com/Japanese-Schoolgirl/DiscordPlugin-CustomPanelForSendingPictures/main/CustomPanelForSendingPictures.plugin.js
* @updateUrl https://raw.githubusercontent.com/Japanese-Schoolgirl/DiscordPlugin-CustomPanelForSendingPictures/main/CustomPanelForSendingPictures.plugin.js
* @version 0.6.3
*/
/*========================| Info |========================*/
const config =
{
changelog:
[
{
title: `This is a potentially unstable update. The plugin is no longer dependent on ZeresPluginLibrary and now it also has a built-in update checker`,
type: "fixed", // without type || fixed || improved || progress
items: [`Starting with this version the plugin can work without using ZeresPluginLibrary/0PluginLibrary and in case of anything the plugin now has its own update checker (can be disabled in the settings). As this is a potentially unstable release, it is recommended to backup your settings or roll back to a previous version if necessary.`]
}
],
info:
{
name: "CustomPanelForSendingPictures",
author_details:
{
name: "Japanese Schoolgirl (Lisa)",
github_username: "Japanese-Schoolgirl",
discord_server: "https://discord.gg/nZMbKkw",
steam_link: "https://steamcommunity.com/id/EternalSchoolgirl/",
twitch_link: "https://www.twitch.tv/EternalSchoolgirl"
},
github: "https://github.com/Japanese-Schoolgirl/DiscordPlugin-CustomPanelForSendingPictures",
github_raw: "https://raw.githubusercontent.com/Japanese-Schoolgirl/DiscordPlugin-CustomPanelForSendingPictures/main/CustomPanelForSendingPictures.plugin.js"
}
};
/*========================| Essential functions |========================*/
const getModule_ = (module) =>
{ // || window.require;
try { return require(module); }
catch(err) { console.warn(err); return false; };
};
const PluginApi_ = window.BdApi ? window.BdApi : window.alert("PLUGIN API NOT FOUND"); // Window scope is needed here
const BufferFromFormat_ = getModule_("buffer").from; /*(content, format) =>
{// This library will be used when the "Buffer" module breaks: https://unpkg.com/[email protected]/base64js.min.js
if(format == "base64") { return base64js.toByteArray(content); } else { return Uint8Array.from(content, (v) => v.charCodeAt(0)); }
}*/
/*========================| Modules |========================*/
const request_ = PluginApi_.Net.fetch; // or getModule_("request");
const electron_ = getModule_("electron");
const fs_ = getModule_("fs");
const path_ = getModule_("path");
const open_folder_ = electron_ ? electron_.shell.openPath : false;
const messageModule = (channelID, sendText, reply = null) =>
{
try
{ // Replace for broken DiscordAPI.currentChannel.sendMessage
let SEND = PluginApi_.findModule(m => m._sendMessage && typeof m._sendMessage === "function")._sendMessage;
SEND(channelID, {content: sendText, validNonShortcutEmojis: Array(0)}, {/* messageReference:{"channel_id":"channelID","message_id":"messageID"} */});
} catch(err) { console.warn(err); }
};
const uploadModule = (channelID, file, sendText = null) =>
{ // Sending text before file
if(sendText) { messageModule(channelID, sendText); }
try
{ // Found module from BdApi/EDApi for uploading files can be replaced with WebpackModules.getByProps("upload").upload and etc.
//Previous method: PluginApi_.findModule(m => m.upload && typeof m.upload === "function").upload({channelId:channelID, file: file});
let UPLOAD = PluginApi_.findModule(m => m.instantBatchUpload && typeof m.instantBatchUpload === "function").instantBatchUpload;
// Check if user have old version of Discord's upload module
let isUpdatedModule = !UPLOAD.toString().match(/^function\(e,t,n\)/);
if(isUpdatedModule) { UPLOAD({ channelId: channelID, files: [file] }); }
else { UPLOAD(channelID, [file]); }
} catch(err) { console.warn(err); }
};
/*========================| DEPRECATED |========================*/
/*
# Buffer_ replaced with BufferFromFormat_:
const Buffer_ = typeof Buffer !== "undefined" ? Buffer : getModule_("buffer").Buffer;
# Modules that have stopped working:
const util_ = getModule_("util");
# Might be useful later:
const https_ = getModule_("https");
const ComponentDispatchModule = PluginApi_.findModule(m => m.ComponentDispatch && typeof m.ComponentDispatch === "object").ComponentDispatch; // For insert text with .dispatchToLastSubscribe and etc.
*/
/*========================| Core |========================*/
//-----------| Create Settings and Variables |-----------//
var picsGlobalSettings = {};
var pluginPath, settingsPath, configPath, picturesPath, DiscordLanguage, isWindows;
pluginPath = PluginApi_.Plugins.folder;
settingsPath = path_.join(pluginPath, config.info.name + '.settings.json');
configPath = path_.join(pluginPath, config.info.name + '.configuration.json');
picturesPath = path_.join(pluginPath, config.info.name);
DiscordLanguage = navigator.language; // Output is "en-US", "ru" etc.
isWindows = navigator.userAgentData.platform.toLowerCase() == 'windows' ? true : false; // For not Windows OS support
var getDiscordTextarea = () => { return document.querySelector('div[class*="channelTextArea"]') };
var lastSent = {};
let sendingCooldown = {time: 0, duration: 0};
let sentType = '.sent';
let srcType = '.src';
let emptyIMG = 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAEAAAAALAAAAAABAAEAgQAAAAAAAAAAAAAAAAICRAEAOw==';
let NotFoundIMG = 'https://i.imgur.com/r0OCBLX.png'; // Old is 'https://i.imgur.com/jz767Z6.png', src as base64 also ok;
let imgPreviewSize = {W: '48px', H: '48px'};
let mainFolderName = 'Main folder!/\\?'; // It'll still be used for arrays and objects. Change in configuration only affects at section's name
let folderListName = `?/\\!FolderList!/\\?`;
var Configuration = { // Almost all Default values need only as placeholder
CheckForUpdates: { Value: true, Default: true, Title: `Check for updates`, Description: `Enables built-in update checking.` },
UseSentLinks: { Value: true, Default: true, Title: `Use "Sent Links"`, Description: `To create and use ${sentType} files that are replacing file sending by sending links.` },
SendTextWithFile: { Value: false, Default: false, Title: `Send text from textbox before sending file`, Description: `To send text from textbox before sending local or web file. Doesn't delete text from textbox. Doesn't send message over 2000 symbols limit.` },
OnlyForcedUpdate: { Value: false, Default: false, Title: `Only forced update`, Description: `Doesn't allow plugin to automatically update settings via scan with used files without user interaction.` },
sentType2srcType: { Value: false, Default: false, Title: `Treat ${sentType} as ${srcType}`, Description: `To use ${sentType} as ${srcType}.` },
RepeatLastSent: { Value: false, Default: false, Title: `Repeat last sent`, Description: `To use Alt+V hotkey for repeat sending your last sent file or link (without text) to current channel.` },
SizeLimitForFile: { Value: true, Default: true, Title: `Prevent sending files larger than 10 MB`, Description: `Prevents a message from being sent if the file size is larger than 10 MB.` },
AutoClosePanel: { Value: false, Default: false, Title: `Auto close panel`, Description: `To autoclose pictures panel after sending any file when pressed without Shift modificator key.` },
SendingFileCooldown: { Value: 0, Default: '0', Title: `Sending file cooldown`, Description: `To set cooldown in millisecond before you can send another file. Set 0 in this setting to turn this off. This option exists to prevent double/miss clicks so it doesn't apply to hotkey sending.` },
ScaleSizeForPictures: { Value: { type: 'width', num: '45', subpanel: true, exp: false }, Default: '', Title: `Set size for scaling (on by default)`, Description: `For automatic proportional scaling of pictures from local or web files to set size. Value is set only either for width or height. Clicking while holding Ctrl key will ignore enabling of this option. Remove value in this setting to turn this off.` },
SetLinkParameters: { Value: '', Default: '?width=45&height=45', Title: `Set parameters for web file (off by default)`, Description: `To automatically add custom parameters for sending links. Remove value in this setting to turn this off.` },
mainFolderPath: { Value: picturesPath, Default: picturesPath, Title: `There is your folder for pictures:`, Description: `You can set your Main folder which will be scanned for pictures and subfolders. Please try to avoid using folders with very big amount of files. Chosen directory should already exist.` },
mainFolderNameDisplay: { Value: 'Main folder', Default: 'Main folder', Title: `Displayed section name for Main folder`, Description: `You can set this section name to Main folder:` },
SectionTextColor: { Value: '#000000bb', Default: '#000000bb', Title: `Section's name color`, Description: `Your current color is:` },
};
//-----------| Start of Styles section |-----------//
var CPFSP_Styles = () => { return ` /* Extract from "emojiList" and etc classes + additional margin and fixes */
:root {
--sectionText: ${Configuration.SectionTextColor.Value};
--sectionTextFlash: rgba(255, 0, 0, 0.2);
}
@keyframes spin360 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes loadingCircle {
0% {
box-shadow: 2px 3px 4px var(--sectionTextFlash) inset,
2px 2px 2px var(--sectionText) inset,
2px -2px 2px var(--sectionText) inset;
}
100% {
box-shadow: 2px 3px 4px var(--sectionTextFlash) inset,
2px 2px 2px var(--sectionText) inset,
2px -2px 2px var(--sectionText) inset;
}
}
#CPFSP_Panel {
overflow: hidden;
position: relative;
background-color: transparent;
}
.CPFSP_List {
top: ${5+22+27}px; /* 5 + height from search bar + height from buttons panel */
right: 0px;
bottom: 8px;
left: 8px;
position: absolute;
overflow: hidden scroll;
padding-right: 5px;
}
.CPFSP_Section {
height: 100%;
margin-bottom: 12px;
margin-left: 18px;
font-size: 18px;
font-weight: 600;
color: var(--sectionText); /* color: var(--header-primary); */
text-shadow: 0px 0px 5px white, 0px 0px 10px white, 0px 0px 5px black, 0px 0px 10px black, 0px 0px 1px purple;
}
.CPFSP_ul {
/*
height: 56px;
display: inline-block;
grid-auto-flow: column;
grid-template-columns: repeat(auto-fill,56px);
*/
}
.CPFSP_li {
display: inline-block;
margin: 5px 0px 0px 5px;
/* background-image: linear-gradient(to bottom, var(--sectionText) 0%, var(--sectionTextFlash) 100%); */
}
.CPFSP_li[waitload] {
box-shadow: 2px 3px 4px var(--sectionText) inset; /* in case if animation not starts */
border-radius: 50%;
animation: spin360 1s linear infinite, loadingCircle 2s alternate infinite; /* Causes lags */
}
.CPFSP_IMG {
min-width: ${imgPreviewSize.W};
max-width: ${imgPreviewSize.W};
min-height: ${imgPreviewSize.H};
max-height: ${imgPreviewSize.H};
cursor: pointer;
background-size: 48px 48px;
}
.CPFSP_li[waitload] .CPFSP_IMG {
content: url(${emptyIMG});
}
#CPFSP_btnsPanel, #CPFSP_scaleSubpanelID {
height: 27px; /* old is 30px */
line-height: 27px; /* old is 32px */
width: 100%;
display: grid;
grid-template-columns: auto 110px; /* or 75% 25%; */
font-size: 15px;
font-weight: 600;
/* column-gap: 5px; */
}
.CPFSP_btnDefault {
cursor: pointer;
color: var(--channels-default);
background-color: var(--background-tertiary);
text-align: center;
min-width: 48px;
border-width: 1px 1px 1px 1px;
border-style: solid;
/*border-radius: 60px 60px 60px 60px;*/
}
.CPFSP_btnDefault:hover {
color: var(--interactive-hover);
}
.CPFSP_btnDefault:active {
color: var(--interactive-active);
}
#CPFSP_ButtonGo {
/* ? */
}
.CPFSP_activeButton {
background-color: var(--background-accent);
color: #fff;
}
#CPFSP_spoilerCheckbox {
max-width: 22px;
color: var(--channels-default);
background-color: var(--background-tertiary);
border-radius: 0px 0px 10px 0px;
z-index: 1;
}
#CPFSP_spoilerCheckbox input {
margin-left: 5px;
transform: scale(1.5);
vertical-align: middle;
}
#CPFSP_spoilerCheckbox p {
margin: 0px 0px 10px 2px;
line-height: 1;
writing-mode: vertical-lr;
text-orientation: upright;
font-weight: bolder;
}
#CPFSP_scaleSubpanelID {
position: absolute;
justify-content: right;
grid-template-columns: none;
}
#CPFSP_scaleSubpanelID input {
max-width: 75px;
}
.CPFSP_searchBar {
display: grid;
grid-template-columns: auto 150px;
width: 100%;
font-size: 16px;
}
#CPFSP_searchBarInput {
height: 26px;
line-height: 26px;
box-sizing: border-box;
color: var(--text-normal);
padding: 0 8px;
background-color: var(--background-tertiary);
border-color: var(--channels-default);
border: solid;
border-width: 1px 1px 0px 1px;
border-radius: 10px 10px 0px 0px;
overflow: hidden;
resize: none;
}
#CPFSP_searchBarOptions {
text-align-last: center;
border-radius: 80px 80px 80px 80px;
background-color: var(--background-tertiary);
color: var(--interactive-active);
}
#CPFSP_scaleType {
cursor: pointer;
color: var(--channels-default);
font-weight: 600;
}
#CPFSP_scaleExp, #CPFSP_scaleSubpanel {
color: var(--channels-default);
font-weight: 600;
}
#CPFSP_scaleExp input, #CPFSP_scaleSubpanel input {
cursor: pointer;
margin: 5px 0px 0px 0px;
}
`};
var CPFSP_imgFilter = (value, options) => { return ` /* Adds filter that sets display none to all imgs that match with it */
#CPFSP_Panel .CPFSP_List li.CPFSP_li:not([${options.lettercase}${options.match}="${value}"]) {
display: none !important;
}
.CPFSP_Section text {
display: none !important;
}
.CPFSP_ul {
display: inline !important;
}
`};
var searchNames = {
emojisGUI: 'div[role="tablist"]', // Panel with menu and buttons (aria label is Expression Picker)
emojisPanel: 'div[role="tabpanel"]', // Or emojisGUI.lastElementChild (cause bug with scale subpanel);
emojisClassGUI: 'div[class*="contentWrapper"]' // Whole panel
}
var elementNames = {
id: 'CPFSP_StyleSheet',
filter: 'CPFSP_StyleFilter',
CPFSP_panelID: 'CPFSP_Panel',
CPFSP_scalePanelID: 'CPFSP_scaleSubpanelID',
CPFSP_buttonGoID: 'CPFSP_ButtonGo',
CPFSP_activeButton: 'CPFSP_activeButton',
elementList: 'CPFSP_List',
folderSection: 'CPFSP_Section',
elementRow: 'CPFSP_ul',
elementCol: 'CPFSP_li',
newPicture: 'CPFSP_IMG',
buttonsPanel: 'CPFSP_btnsPanel',
buttonDefault: 'CPFSP_btnDefault',
buttonRefresh: 'CPFSP_btnRefresh',
buttonOpenFolder: 'CPFSP_btnOpenFolder',
spoilerCheckbox: 'CPFSP_spoilerCheckbox',
searchBar: 'CPFSP_searchBar',
searchBarInput: 'CPFSP_searchBarInput',
searchBarOptions: 'CPFSP_searchBarOptions',
emojiTabID: 'emoji-picker-tab',
gifTabID: 'gif-picker-tab',
stickerTabID: 'sticker-picker-tab',
Config_scaleType: 'CPFSP_scaleType',
Config_scaleSubpanel: 'CPFSP_scaleSubpanel',
Config_scaleExp: 'CPFSP_scaleExp'
}
var labelsNames = {
Modal_OkDownload: `Download Now`,
Modal_Cancel: `Cancel`,
Modal_Missing: `Library Missing`,
Modal_MissingLibs: `The library plugin needed for turned on options in plugin ${config.info.name} is missing. Please click "Download Now" to install it.`,
Constants_Missing: `Some importants constants in plugin ${config.info.name} is missing`,
Yamete: `Yamete!`,
tooBig: `It's too big!`,
forYou: `For you:`,
symbolsLimit: `B-baka, your text wasn't sent with image because your text is over 2000 symbols!`,
filesizeLimit: `B-baka, your message wasn't sent because your file size is larger than 10 MB!`,
Pictures: `Pictures`,
btnRefresh: `Refresh`,
btnOpenFolder: `Open folder`,
btnFolderPath: `Folder path`,
searchPicture: `Search picture`,
spoilerCheckbox: `Spoiler`,
spoilerTooltip: `If it is checked, then links and files will be sent as spoilers`,
filterAnyMatch: `Any match`,
filterStrictMatch: `Strict match`,
filterAnyLetterCase: `Case-insensitive`,
filterInAnyPlace: `In any place`,
configMenu: `Configuration Menu`,
width: `Width`,
height: `Height`,
intNumber: `Integer number`,
scaleSubpanel: `Adds the subpanel for image resizing to the emoji panel`,
scaleExperimental: `Experimental support for animations (will be used external module)`
}
var funcs_ = {}; // Object for store all custom functions
var tempVars_ = {}; // Object for store all temp vars
//-----------| End of Styles section |-----------//
//-----------| Functions |-----------//
funcs_.versionCheck = (this_plugin) =>
{
config.info.version = this_plugin.meta.version;
config.info.description = this_plugin.meta.description;
const previousVersion = this_plugin.api.Data.load("version");
if(previousVersion !== config.info.version)
{
this_plugin.api.UI.showChangelogModal({
title: this_plugin.meta.name,
subtitle: config.info.version,
blurb: "If you think the automatic updates are broken (and there is a chance for this), you can check for the latest version here: https://raw.githubusercontent.com/Japanese-Schoolgirl/DiscordPlugin-CustomPanelForSendingPictures/refs/heads/main/CustomPanelForSendingPictures.plugin.js",
changes: config.changelog
});
this_plugin.api.Data.save("version", this_plugin.meta.version);
}
}
funcs_.updateCheck = (this_plugin) =>
{
// Does not check for updates if they are not needed
if(!Configuration.CheckForUpdates.Value) { return }
function downloadNewVersion()
{
PluginApi_.showConfirmationModal(`Update ${config.info.name}?`, `If plugin's built-in updater conflicts in any way, you can always disable its update checking in the settings.`,
{
confirmText: "Update Now",
cancelText: "Cancel",
onConfirm: () =>
{
request_(this_plugin.getUpdateURL()).then(r => {
if (!r || r.status != 200) throw new Error();
else return r.text();
}).then(b => {
if (!b) throw new Error();
else return fs_.writeFile(path_.join(PluginApi_.Plugins.folder, "CustomPanelForSendingPictures.plugin.js"), b, _ => PluginApi_.showNotice("Finished downloading!", {type: "success"}));
}).catch(err => {
PluginApi_.showNotice("Error", `Could not download latest version. Try again later or download it manually from GitHub: ${config.info.github_raw}`);
});
}
});
}
fetch(this_plugin.getUpdateURL())
.then(response => response.text())
.then(data =>
{
const versionRegEx = /(\* @version [0-9]+\.[0-9]+\.[0-9]+)/;
const match = data.match(versionRegEx);
if(match)
{
const latestVersion = match[1].match(/[0-9]+\.[0-9]+\.[0-9]+/)[0];
console.log(`Latest version for ${config.info.name} is ${latestVersion}. Your is config.info.version`);
// Compare the latest version with your current version
if(latestVersion !== config.info.version)
{
PluginApi_.UI.showNotice(`Update for ${config.info.name} is available! Your current version is ${config.info.version}. Latest version is ${latestVersion}`);
downloadNewVersion();
}
} else { console.warn(`Failed to extract version number for ${config.info.name} :<`); }
})
.catch(err => console.error(`Error fetching version file for ${config.info.name}:`, err));
}
funcs_.warnsCheck = () =>
{
if(!(PluginApi_.UI && PluginApi_.Patcher)) { console.warn(labelsNames.Constants_Missing); }
}
funcs_.showAlert = PluginApi_.UI.alert; // Old function is Modals.showAlertModal;
funcs_.setStyles = (command = null) =>
{
if(document.getElementById(elementNames.id) && command == 'delete') { return document.getElementById(elementNames.id).remove(); }
if(document.getElementById(elementNames.id)) { return }
let pluginStyles = document.createElement('style');
pluginStyles.setAttribute('id', elementNames.id);
pluginStyles.innerHTML = CPFSP_Styles();
return document.body.append(pluginStyles);
}
funcs_.setStyleFilter = (event = null, command = null) =>
{
let text = document.getElementById(elementNames.searchBarInput) ? document.getElementById(elementNames.searchBarInput).value : null;
if(!text) { command = 'delete'; }
if(text) { if(!text.length) { command = 'delete'; } }
if(document.getElementById(elementNames.filter) && command == 'delete') { return document.getElementById(elementNames.filter).remove(); }
if(!event || command == 'delete') { return }
let options = document.getElementById(elementNames.searchBarOptions) ? document.getElementById(elementNames.searchBarOptions).value : null;
switch(options)
{
case 'AnyMatch': options = { lettercase: 'lowerPicName', match: '*' }; break;
case 'StrictMatch': options = { lettercase: 'strictPicName', match: '^' }; break;
case 'AnyLetterCase': options = { lettercase: 'lowerPicName', match: '^' }; break;
case 'InAnyPlace': options = { lettercase: 'strictPicName', match: '*' }; break;
default: options = { lettercase: 'lowerPicName', match: '*' };
}
text = options.lettercase == 'lowerPicName' ? text.toLowerCase() : text;
if(document.getElementById(elementNames.filter)) { return document.getElementById(elementNames.filter).innerHTML = CPFSP_imgFilter(text, options); }
let pluginStyleFilter = document.createElement('style');
pluginStyleFilter.setAttribute('id', elementNames.filter);
pluginStyleFilter.innerHTML = CPFSP_imgFilter(text, options);
return document.body.append(pluginStyleFilter);
}
funcs_.setLanguage = () =>
{ // Janky localization
switch(DiscordLanguage)
{
case 'ru':
config.info.description = `Добавляет панель, которая подгружает картинки через файл настроек с используемыми файлами и ссылками, позволяя отправлять картинки с текстом или без текста нажатием по превью картинок на панели. Файл настроек автоматически создаётся при сканировании выбранной папки или папки плагина (поддерживает подпапки и будет отображать их как секции/группы).`; // Only config constanta, not keys inside
labelsNames.Modal_OkDownload = `Скачать сейчас`;
labelsNames.Modal_Cancel = `Отмена`;
labelsNames.Modal_Missing = `Отсутствует библиотека`;
labelsNames.Modal_MissingLibs = `Отсутствует библиотека, необходимая для работы включённых опций в плагине ${config.info.name}. Пожалуйста, нажмите "${labelsNames.Modal_OkDownload}" для её установки.`;
labelsNames.Constants_Missing = `Отсутствуют некоторые константы, важные для плагина ${config.info.name}.`;
labelsNames.Yamete = `Ямете!`;
labelsNames.tooBig = `Это слишком велико!`;
labelsNames.forYou = `Для тебя:`;
labelsNames.symbolsLimit = `Б-бака, твой текст не был отправлен с файлом, потому что в нём больше 2000 символов!`;
labelsNames.filesizeLimit = `Б-бака, твоё сообщение не было отправлено, потому что размер файла больше 10 МБ!`;
labelsNames.Pictures = `Картинки`;
labelsNames.btnRefresh = `Обновить`;
labelsNames.btnOpenFolder = `Открыть папку`;
labelsNames.btnFolderPath = `Путь папки`;
labelsNames.searchPicture = `Искать картинку`;
labelsNames.spoilerCheckbox = `Спойлер`;
labelsNames.spoilerTooltip = `Если отмечено галочкой, то ссылки и файлы отправляются как спойлеры`;
labelsNames.filterAnyMatch = `Любое совпадение`;
labelsNames.filterStrictMatch = `Строгое совпадение`;
labelsNames.filterAnyLetterCase = `Любой регистр`;
labelsNames.filterInAnyPlace = `В любом месте`;
labelsNames.configMenu = `Меню Конфигурации`;
labelsNames.width = `Ширина`;
labelsNames.height = `Высота`;
labelsNames.intNumber = `Целое число`;
labelsNames.scaleSubpanel = `Добавляет субпанель для масштабирования картинок к панели с эмодзи`;
labelsNames.scaleExperimental = `Экспериментальная поддержка анимаций (будет использоваться посторонний модуль)`;
Configuration.CheckForUpdates.Title = `Проверять обновления`;
Configuration.CheckForUpdates.Description = `Включает встроенную проверку обновлений.`;
Configuration.UseSentLinks.Title = `Использовать "Отправленные Ссылки"`;
Configuration.UseSentLinks.Description = `Включает создание и использование ${sentType} файлов, которые заменяют отправку файлов отправкой ссылок.`;
Configuration.SendTextWithFile.Title = `Отправлять текст из чата перед отправляемым файлом`;
Configuration.SendTextWithFile.Description = `Включает отправку текста из чата перед отправляемым локальным или веб файлом. Не удаляет текст из чата. Не отправляет сообщение превышающее 2000 символов.`;
Configuration.OnlyForcedUpdate.Title = `Только принудительное обновление`;
Configuration.OnlyForcedUpdate.Description = `Не позволяет плагину автоматически обновлять настройки через сканирование с используемыми файлами без участия пользователя.`;
Configuration.sentType2srcType.Title = `Рассматривать ${sentType} как ${srcType}`;
Configuration.sentType2srcType.Description = `Для использования ${sentType} в качестве ${srcType}.`;
Configuration.RepeatLastSent.Title = `Повторение последний отправки`;
Configuration.RepeatLastSent.Description = `Включает использование сочетания клавиш Alt+V для повторения отправки последнего отправленного файла или ссылки (без текста) в текущий канал.`;
Configuration.SizeLimitForFile.Title = `Не отправлять файл размером больше 10 МБ`;
Configuration.SizeLimitForFile.Description = `Предотвращает отправку сообщения, если размер отправляемого файла в нём больше 10 МБ.`;
Configuration.AutoClosePanel.Title = `Автоматическое закрытие панели`;
Configuration.AutoClosePanel.Description = `Для автоматического закрытия панели с картинками после отправки любого файла по нажатию, если не зажата клавиша Shift.`;
Configuration.SendingFileCooldown.Title = `Минимальная задержка перед отправкой`;
Configuration.SendingFileCooldown.Description = `Присваивает минимальную задержку в миллисекундах перед отправкой следующего файла. При присвоении значения 0 опция будет отключена. Эта опция существует для предотвращения удвоенных/случайных нажатий мышкой и поэтому не применяется на отправку по быстрой клавише.`;
Configuration.ScaleSizeForPictures.Title = `Присвоить размер для масштабирования (включено по умолчанию)`;
Configuration.ScaleSizeForPictures.Description = `Для автоматического пропорционального масштабирования размера картинок из локальных или веб файлов к заданному размеру. Значение указывается только для ширины или высоты. Клик с зажатой клавишей Ctrl игнорирует включение этой опции. Удаление значения в этой настройке выключает её.`;
Configuration.SetLinkParameters.Title = `Присваивать параметры веб файлу (выключено по умолчанию)`;
Configuration.SetLinkParameters.Description = `Включает автоматическое добавление параметров для отправляемой ссылки. Удаление значения в этой настройке выключает её.`;
Configuration.mainFolderPath.Title = `Здесь располагается папка под картинки:`;
Configuration.mainFolderPath.Description = `Позволяет указать Главную папку, которая будет сканироваться на картинки и подпапки. Пожалуйста, постарайтесь избежать использования папок с большим количеством файлов. Выбранная директория должна быть созданной.`;
Configuration.mainFolderNameDisplay.Title = `Отображаемое имя секции для Главной папки`;
Configuration.mainFolderNameDisplay.Description = `Присваивает выбранное название для секции с Главной папкой:`;
Configuration.SectionTextColor.Title = `Цвет имени секций`;
Configuration.SectionTextColor.Description = `Текущий цвет это:`;
break
default: // is "en-US"
break
}
}
funcs_.openFolder = (event = null) =>
{
function openMethod()
{
if(open_folder_)
{
// For Linux child_process_.exec(`xdg-open "${Configuration.mainFolderPath.Value}"`);
// let openFolderMethod = isWindows ? `start ""` : `xdg-open`;
// child_process_.exec(`${openFolderMethod} "${Configuration.mainFolderPath.Value}"`);
// New method (via "electron" module):
open_folder_(Configuration.mainFolderPath.Value);
}
else { funcs_.showAlert(labelsNames.btnFolderPath + ":", Configuration.mainFolderPath.Value); }
}
switch(fs_.existsSync(Configuration.mainFolderPath.Value))
{
case false: try { fs_.mkdirSync(Configuration.mainFolderPath.Value); } catch (err) { console.warn(err.code); break; } // Try create folder
default: openMethod(); // Open Main folder in explorer
}
}
funcs_.checkLibraries = async () =>
{
if(!Configuration.ScaleSizeForPictures.Value.exp) { return }
// For latest version: https://unpkg.com/gifsicle-wasm-browser/dist/gifsicle.min.js || https://cdn.jsdelivr.net/npm/gifsicle-wasm-browser/dist/gifsicle.min.js
funcs_.gifsicle = await import("https://unpkg.com/[email protected]/dist/gifsicle.min.js").then((module) => { return module.default; });
}
funcs_.readLocalFile = (filePath, format, sendFile) =>
{
if(!filePath) { return false }
if(!format) { return fs_.readFileSync(filePath); }
if(!sendFile) { return fs_.readFileSync(filePath, { encoding: format }); }
return BufferFromFormat_(fs_.readFileSync(filePath, { encoding: format }), format);
}
// Currently not working: "fs_.promises" & "util_.promisify()"
funcs_.readLocalFileAsync = (filePath, format) =>
{
return new Promise((resolve, reject) =>
{
fs_.readFile(filePath, format, (err, data) =>
{
if(err) { reject(err); }
else { resolve(data); }
})
});
}
funcs_.writeFile = (filePath, content) =>
{ // Async alternative for fs_.writeFileSync
fs_.writeFile(filePath, content, (err) =>
{
if(err) { throw err };
});
}
funcs_.scaleTo = (oldWidth, oldHeight, knownType, knownValue) =>
{
if(!knownType || !knownValue || !oldWidth || !oldHeight) { return }
let newWidth = knownType == 'width' ? knownValue : null;
let newHeight = knownType == 'height' ? knownValue : null;
if(newWidth) { return Math.round(newHeight = (oldHeight / (oldWidth / newWidth))); }
if(newHeight) { return Math.round(newWidth = (oldWidth / (oldHeight / newHeight))); }
}
funcs_.resizeGif = async (gifPath, newWidth, newHeight, gifName) =>
{
if(!gifPath || !newWidth || !newHeight) { return false }
/* Deprecated gifsicle.exe method
if(!fs_.existsSync(path_.join(pluginPath, resizePluginName + '.exe'))) { console.warn(`${resizePluginName}.exe not found!`); return false }
let gifsiclePath = path_.join(pluginPath, resizePluginName);
let gifsicleOutput = gifsiclePath + '.output';
try
{
child_process_.execSync(`"${gifsiclePath}" "${gifPath}" --resize ${newWidth}x${newHeight} -o "${gifsicleOutput}"`);
} catch(err) { console.warn(err); }
if(!fs_.existsSync(gifsicleOutput)) { console.warn("Why output file doesn't exist?!"); return false }
let outputData = funcs_.readLocalFile(gifsicleOutput, "base64", true);
fs_.unlinkSync(gifsicleOutput);
*/
var outputData;
try
{
let inputName = "gifsicleInput";
let outputName = "gifsicleOutput";
let gifFile = (new File([funcs_.readLocalFile(gifPath, "base64", true)], inputName));
outputData = funcs_.gifsicle.run({
input: [{ file: gifFile, name: inputName }],
command: [`${inputName} --resize ${newWidth}x${newHeight} -o /out/${outputName} `]
}).then((outfiles) => { return outfiles[0]; });
} catch(err) { console.warn(err); }
return await outputData;
}
funcs_.saveSettings = (data, once = null) =>
{
if(Object.keys(data).length < 2) { return funcs_.loadDefaultSettings(); } // This happen when folder is empty
try { funcs_.writeFile(settingsPath, JSON.stringify(data)); }
catch(err) { console.warn('There has been an error saving your setting data:', err.message); }
if(once) { return picsGlobalSettings; } // to avoid endless engine
return funcs_.loadSettings();
// DEBUG // console.log('Path: ', __dirname);
}
funcs_.loadSettings = (anotherTry = null) =>
{
let newPicsGlobalSettings = {};
if(!fs_.existsSync(settingsPath)) { return funcs_.loadDefaultSettings(); } // This happen when settings file doesn't exist
try { newPicsGlobalSettings = JSON.parse(funcs_.readLocalFile(settingsPath)); }
catch(err)
{
console.warn('There has been an error parsing your settings JSON:', err.message);
if(!anotherTry) { return funcs_.loadSettings(true) }
return picsGlobalSettings;
}
if(!Object.keys(newPicsGlobalSettings).length) { return funcs_.loadDefaultSettings(); } // This happen when settings file is empty
picsGlobalSettings = newPicsGlobalSettings;
return picsGlobalSettings;
}
funcs_.loadDefaultSettings = () =>
{
picsGlobalSettings = {};
picsSettings = [ { name: 'AnnoyingLisa', link: 'https://i.imgur.com/l5Jf0VP.png' }, { name: 'AngryLisaNoises', link: 'https://i.imgur.com/VMXymqg.png'} ]; // Placeholder
picsGlobalSettings[folderListName] = [ { name: mainFolderName, path: Configuration.mainFolderPath.Value } ];
picsGlobalSettings[mainFolderName] = picsSettings;
//funcs_.saveSettings(picsGlobalSettings);
funcs_.saveSettings(picsGlobalSettings, true);
return picsGlobalSettings;
}
funcs_.loadConfiguration = () =>
{
let newData;
if(!fs_.existsSync(configPath)) { return } // This happen when settings file doesn't exist
try { newData = JSON.parse(funcs_.readLocalFile(configPath)); }
catch(err) { console.warn('There has been an error parsing your config JSON:', err.message); return }
if(!newData || !Object.keys(newData).length) { return } // This happen when settings file is empty
Object.keys(Configuration).forEach((key) =>
{
if(newData[key] == undefined) { return }; // I hope that I will not forget that not to do !newData[key] here :0
Configuration[key].Value = newData[key];
});
if(Configuration.RepeatLastSent.Value)
{
document.body.removeEventListener('keydown', funcs_.RepeatLastSentFunc);
document.body.addEventListener('keydown', funcs_.RepeatLastSentFunc);
}
funcs_.setLanguage();
funcs_.checkLibraries();
Configuration.ScaleSizeForPictures.Default = labelsNames.intNumber; // Fix placeholder
}
funcs_.setConfigValue = (event, key, newValue = null, specialKey = null) =>
{
//console.log(event, key, newValue, specialKey);
if(!event || !key || newValue == null) { return false }
if(!specialKey) { Configuration[key].Value = newValue; }
else { Configuration[key].Value[specialKey] = newValue; }
funcs_.saveConfiguration();
return true
}
funcs_.saveConfiguration = () =>
{
let exportData = {};
Object.keys(Configuration).forEach((key) =>
{
exportData[key] = Configuration[key].Value;
});
try { funcs_.writeFile(configPath, JSON.stringify(exportData)); }
catch(err) { console.warn('There has been an error saving your config data:', err.message); }
funcs_.loadConfiguration();
}
funcs_.createSetting = (...args) =>
{
let type = args[0];
if(!type) { return }
switch(type)
{
//case 'Switch': return new Settings.Slider(args[1], args[2], 0, 1, Number(args[3]), args[4], { markers: [0, 1], stickToMarkers: true }); // Temporary fix
case 'Switch': return new Settings.Switch(args[1], args[2], args[3], args[4], args[5]);
case 'Textbox': return new Settings.Textbox(args[1], args[2], args[3], args[4], args[5]);
case 'ColorPicker': return new Settings.Textbox(args[1], args[2], args[3], args[4], args[5]); // Temporary fix
//case 'ColorPicker': return new Settings.ColorPicker(args[1], args[2], args[3], args[4], args[5]);
case 'Keybind': return new Settings.Keybind(args[1], args[2], args[3], args[4], args[5]);
case 'Dropdown': return new Settings.Dropdown(args[1], args[2], args[3], args[4], args[5], args[6]);
case 'RadioGroup': return new Settings.RadioGroup(args[1], args[2], args[3], args[4], args[5], args[6]);
case 'Slider': return new Settings.Slider(args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
default: break;
}
}
funcs_.scanDirectory = (forced = null, repeat = null) =>
{ // Scanning plugin folder
if((Configuration.OnlyForcedUpdate.Value && !forced) && !repeat) { return funcs_.loadSettings(); }
if(fs_.existsSync(Configuration.mainFolderPath.Value))
{ // Exist
funcs_.findPictures(Configuration.mainFolderPath.Value);
return funcs_.loadSettings(); // funcs_.findPictures will store data in picsGlobalSettings, so with state it possible to decide when new data is received
}
else
{ // Not Exist
if(Configuration.mainFolderPath.Value.length < 2) { Configuration.mainFolderPath.Value = Configuration.mainFolderPath.Default; } // Protection against shoot on foots
try { fs_.mkdirSync(Configuration.mainFolderPath.Value); } // Try create folder
catch (err) { console.warn(err.code); }
if(!repeat) { funcs_.scanDirectory(forced, true); } // Fixed issue with necessary double scan when user delete folder
return picsGlobalSettings;
}
}
funcs_.closeCurrentReply = () =>
{ // Exits the reply mode by it's close button
// "DiscordSelectors.Textarea.attachedBars" stopped working
if(!getDiscordTextarea()) { return }
try { getDiscordTextarea().querySelector('div[class*="replyBar"] div[class*="closeButton"]').click(); } catch(err) {};
}
funcs_.findPictures = (scanPath, newAllPicsSettings = {}, folderName = null, foldersForScan = [], emtpyFoldersList = []) =>
{ // Scanning for pictures in select folder, "foldersForScan" store folders from plugin directory
let newPicsSettings = [];
let files;
let isFirstScan = !folderName; // !(Object.keys(newAllPicsSettings).length);
if(!scanPath) { return funcs_.loadSettings(); }
if(!fs_.existsSync(scanPath)) { return funcs_.loadSettings(); }
if(!folderName) { folderName = mainFolderName; }
// function getDirs(scanPath) { return fs_.readdirSync(scanPath).filter(file => fs_.statSync(path_.join(scanPath, file)).isDirectory()); }
try { files = fs_.readdirSync(scanPath); }
catch(err) { console.warn('Unable to scan directory:' + err); return funcs_.loadSettings(); }
let alreadySentFiles = [];
if(isFirstScan) { foldersForScan.push({ name: mainFolderName, path: Configuration.mainFolderPath.Value }); } // Adds necessary information about main folder
if(isFirstScan) { newAllPicsSettings[folderListName] = foldersForScan; } // Unnecessary reordering fix?
let currentFolder = isFirstScan ? mainFolderName : folderName; // Get name of current folder
let index = 0;
files.forEach((file, absoluteIndex) =>
{
let isFolder = fs_.statSync(path_.join(scanPath, file)).isDirectory();
let fileTypesAllow = ['.jpg', '.jpeg', '.bmp', '.png', '.webp', '.gif', srcType, sentType];
let fileType = path_.extname(file).toLowerCase();
let filePath = path_.join(scanPath, file);
let webLink;
if(isFolder && isFirstScan) { foldersForScan.push({name: file, path: filePath }); } // Add each folder only in this cycle due isFirstScan there prevents scans subfolders in subfolders. However this code not organize for subsubsubsubfolders scan yet
if(isFolder && isFirstScan && !absoluteIndex) { newPicsSettings[index] = { name: 'Placeholder', link: 'https://i.imgur.com/VMXymqg.png?AlwaysSendThisImageToNextUniverse/\\?????' }; } // Adds as placeholder only once due Main folder can't be "emtpy"
if(fileTypesAllow.indexOf(fileType) == -1) { return } // Check at filetype
if(fileType == sentType || fileType == srcType)
{
try { webLink = JSON.parse(funcs_.readLocalFile(filePath)); }
catch(err) { console.warn(`There has been an error parsing ${sentType} file:`, err.message); return }
if(Configuration.sentType2srcType.Value) { fileType = srcType; }
}
if(fileType == sentType)
{
if(!Configuration.UseSentLinks.Value) { return } // Doesn't uses this files type if user don't turn on it
alreadySentFiles.push({ name: file, link: webLink });
return
}
if(fileType == srcType) { newPicsSettings[index] = { name: file, link: webLink }; }
else if(fileTypesAllow.indexOf(fileType) != -1) { newPicsSettings[index] = { name: file, link: 'file:///' + filePath }; }
index++; // Index will increase ONLY if file is allowed
});
// DEBUG // console.log(newPicsSettings);
// DEBUG // console.log(alreadySentFiles);
alreadySentFiles.forEach((file) =>
{ // Replace all local links with web links
let found = newPicsSettings.find(el => el.name == file.name.slice(0, -sentType.length));
if(found) { found.link = file.link; }
});
if(!Object.keys(files).length || !Object.keys(newPicsSettings).length)
{ // Detect and adds emtpy folder to list for delete
//foldersForScan.splice(foldersForScan.findIndex((el) => el.name == currentFolder), 1); // Didn't work properly
//foldersForScan.find((el) => el.name == currentFolder).name = 'undefined';
//newAllPicsSettings[folderListName] = foldersForScan;
//Variants above don't work correctly
emtpyFoldersList.push(foldersForScan.find((el) => el.name == currentFolder));
}
if(Object.keys(newPicsSettings).length) { newAllPicsSettings[currentFolder] = newPicsSettings; } // Prevents adding empty folder
if(Object.keys(foldersForScan).length)
{ // There subfolders scan request
if(isFirstScan) { newAllPicsSettings[folderListName] = foldersForScan; } // isFirstScan there prevents scans subfolders in subfolders. However this blah blah blah I already said this
let needSkip;
foldersForScan.some((folder, folderIndex) =>
{
if(currentFolder == folder.name && folderIndex < Object.keys(foldersForScan).length-1) // it is X < X, where X count of folders
{
funcs_.findPictures(foldersForScan[folderIndex+1].path, newAllPicsSettings, foldersForScan[folderIndex+1].name, foldersForScan, emtpyFoldersList);
return (needSkip = true);
}
});
if(needSkip) { return false } // If funcs_.findPictures used inside itself then this method will end there
}
// DEBUG // console.log(folders, newAllPicsSettings, newPicsSettings, isFirstScan);
emtpyFoldersList.forEach((emtpyFolder) =>
{
newAllPicsSettings[folderListName].splice(newAllPicsSettings[folderListName].findIndex((folder) => folder.name == emtpyFolder.name && folder.path == emtpyFolder.path), 1);
});
try
{ // Remove placeholder and delete Main folder from section. This happen if in Main folder only folders with pictures
if((1 < newAllPicsSettings[folderListName].length) && (newAllPicsSettings[mainFolderName].length < 2))
{
let placeholder = newAllPicsSettings[mainFolderName][0];
if((placeholder.name === 'Placeholder') && (placeholder.link === 'https://i.imgur.com/VMXymqg.png?AlwaysSendThisImageToNextUniverse/\\?????'))
{
newAllPicsSettings[folderListName].splice([newAllPicsSettings[folderListName].findIndex((el) => el.name == mainFolderName)], 1);
delete newAllPicsSettings[mainFolderName];
}
}
} catch(err) { console.warn(err); }
return funcs_.saveSettings(newAllPicsSettings); // Apply new settings
}
funcs_.moveToPicturesPanel = (elem = null, once = null) =>
{ // once for funcs_.scanDirectory and waitingScan check
let command = (elem == 'refresh') ? 'refresh' : elem ? elem.target.getAttribute('command') : null;
let buttonCPFSP = document.getElementById(elementNames.CPFSP_buttonGoID);
if(!buttonCPFSP) { return }
let emojisGUI = buttonCPFSP.parentNode.parentNode.parentNode; // Up to "contentWrapper-"
let emojisPanel = emojisGUI.querySelector(searchNames.emojisPanel); // Emojis panel, old way for getting this is querySelector('div[role*="tabpanel"]'), but Stickers tab doesn't have any role :I
if(!emojisPanel) { return }
let allPicsSettings;
//# Previous button click fix: START
let emojisMenu = emojisGUI.querySelector(searchNames.emojisGUI);
let previousButton = emojisMenu.querySelector('button[aria-selected*="true"]'); // Will return Button tag
let previousButtonID = previousButton ? previousButton.id : null;
if(previousButtonID)
{
buttonCPFSP.setAttribute('from', previousButtonID); // Necessary for fixing previous button
function previousButtonFix(event)
{
let buttonCPFSP = document.getElementById(elementNames.CPFSP_buttonGoID);
let from = buttonCPFSP.getAttribute('from');
let fix = (from == elementNames.emojiTabID) ? elementNames.gifTabID : elementNames.emojiTabID;
// Select other button and after this select previous button again
document.getElementById(fix).addEventListener("click", document.getElementById(from).click(), { once: true } ); // Maybe not better idea
document.getElementById(fix).click();
buttonCPFSP.classList.remove(elementNames.CPFSP_activeButton);
// DEBUG // console.log('Fixed', event);
}
function additionalButtonFix(event)
{
let buttonCPFSP = document.getElementById(elementNames.CPFSP_buttonGoID);
buttonCPFSP.classList.remove(elementNames.CPFSP_activeButton);
}
try
{ // Unselecting previous button
previousButton.addEventListener("click", previousButtonFix, { once: true } );
previousButton.classList.value = previousButton.classList.value.replace('ButtonActive', 'Button');
// To not choose the already selected
emojisMenu.querySelectorAll('button[class*="navItem"]').forEach((el) =>
{ // For each Button with label
if(el.id == previousButtonID || el.id == elementNames.CPFSP_buttonGoID) { return }
el.removeEventListener("click", additionalButtonFix, { once: true } ); // Just in cases of incidental duplicate
el.addEventListener("click", additionalButtonFix, { once: true } );
el.classList.value = el.classList.value.replace('ButtonActive', 'Button');
})
} catch(err) { console.warn(err); }
}
//# Previous button click fix: END
function creatingPanel()
{
allPicsSettings = funcs_.scanDirectory(command);
if((document.getElementById(elementNames.CPFSP_panelID) && command != 'refresh')) { return } // Will repeat if command == refresh
emojisPanel.innerHTML = ''; // Clear panel
emojisPanel.setAttribute('id', elementNames.CPFSP_panelID); // Change panel ID
emojisPanel.removeAttribute('class'); // Removes classes for avoid styles problems
buttonCPFSP.classList.add(elementNames.CPFSP_activeButton); // Add CSS for select
funcs_.setStyleFilter(undefined, 'delete'); // Remove last filter
/*let previousButton = document.getElementById(buttonCPFSP.getAttribute('from'));
try
{ // Unselecting previous button
previousButton.classList.value = previousButton.classList.value.replace('ButtonActive', 'Button');
} catch(err) { console.warn(err); }*/
// Adds buttons
let buttonsPanel = document.createElement('div'); // Panel for buttons
buttonsPanel.setAttribute('id', elementNames.buttonsPanel);
let buttonRefresh = document.createElement('div'); // Refresh button
buttonRefresh.setAttribute('class', elementNames.buttonDefault);
buttonRefresh.setAttribute('command', 'refresh');
buttonRefresh.innerText = labelsNames.btnRefresh;
//buttonRefresh.removeEventListener('click', funcs_.moveToPicturesPanel); // Insurance
buttonRefresh.addEventListener('click', funcs_.moveToPicturesPanel);
buttonsPanel.append(buttonRefresh);
let buttonOpenFolder = document.createElement('div'); // Open folder button
buttonOpenFolder.setAttribute('class', elementNames.buttonDefault);
buttonOpenFolder.innerText = open_folder_ ? labelsNames.btnOpenFolder : labelsNames.btnFolderPath;
buttonOpenFolder.addEventListener('click', funcs_.openFolder);
buttonsPanel.append(buttonOpenFolder);
emojisPanel.insertBefore(buttonsPanel, emojisPanel.firstChild); // Adds button to panel
// Adds checkbox for spoiler
let SpoilerCheckbox = document.createElement('div');
SpoilerCheckbox.setAttribute('id', elementNames.spoilerCheckbox);
SpoilerCheckbox.setAttribute('title', labelsNames.spoilerTooltip);
SpoilerCheckbox.innerHTML = `<input type="checkbox"></input><p>${labelsNames.spoilerCheckbox}</p>`;
buttonsPanel.append(SpoilerCheckbox);
// Adds search bar
let SearchBarPanel = document.createElement('div'); // Panel for Search bar
SearchBarPanel.setAttribute('class', elementNames.searchBar);
let picturesSearch = document.createElement('input'); // Search in pictures with CSS filter
picturesSearch.setAttribute('id', elementNames.searchBarInput);
picturesSearch.setAttribute('placeholder', labelsNames.searchPicture);
picturesSearch.addEventListener('input', funcs_.setStyleFilter);
SearchBarPanel.append(picturesSearch);
let picturesSearchOptions = document.createElement('select'); // Options select for Search bar
picturesSearchOptions.addEventListener('change', funcs_.setStyleFilter);
picturesSearchOptions.setAttribute('id', elementNames.searchBarOptions);
picturesSearchOptions.add(new Option(labelsNames.filterAnyMatch, 'AnyMatch', true, true));
picturesSearchOptions.add(new Option(labelsNames.filterStrictMatch, 'StrictMatch', false, false));
picturesSearchOptions.add(new Option(labelsNames.filterAnyLetterCase, 'AnyLetterCase', false, false));
picturesSearchOptions.add(new Option(labelsNames.filterInAnyPlace, 'InAnyPlace', false, false));
SearchBarPanel.append(picturesSearchOptions)
emojisPanel.insertBefore(SearchBarPanel, emojisPanel.firstChild);
// Adds imgs preview
let elementList = document.createElement('div');
let folderSection = document.createElement('div');
elementList.setAttribute('class', elementNames.elementList);
emojisPanel.append(elementList); // Adds list to panel
folderSection.setAttribute('class', elementNames.folderSection);
let elementRow = document.createElement('ul');
let rowIndex = 1;
let colIndex = 1;
let currentSection;
async function setCurrentSection(folder)
{ // Sets name to section with uses variables above
currentSection = folder.name;
if(currentSection === mainFolderName) { currentSection = Configuration.mainFolderNameDisplay.Value; }
let textEl = document.createElement('text');
textEl.innerText = currentSection;
folderSection.append(textEl);
}
async function setImagesSRC(newPicture, elementCol, file)
{
try
{
if(file.link.includes('file:///'))
{
async function loadImagesSRC(newPicture)
{ // Convert local file to base64 for preview
let filePath = newPicture.getAttribute('path').replace('file:///', ''); // both "path" attribute and "file.link" variable contains "file:///path..."
funcs_.readLocalFileAsync(filePath, 'base64') // Async creating base64 data
.then(data => { newPicture.setAttribute('src', `data:image/${path_.extname(filePath).slice(1)};base64,${data}`); })
.catch(err => { console.warn(err); newPicture.setAttribute('src', NotFoundIMG); });
}
let emojisPanel = document.querySelector(searchNames.emojisPanel);
var GodForgiveMeObserver = new IntersectionObserver((entries) =>
{ // I was very tired and couldn't think of a better solution
entries.forEach((entry) =>
{
// If user not see this element on screen
if(!entry.isIntersecting) { return elementCol.removeAttribute('waitload'); }
elementCol.setAttribute('waitload', '');
loadImagesSRC(newPicture);
GodForgiveMeObserver.disconnect();