-
Notifications
You must be signed in to change notification settings - Fork 0
/
tbui.js.html
2318 lines (2030 loc) · 105 KB
/
tbui.js.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>tbui.js - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
<script src="scripts/nav.js" defer></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav >
<input type="text" id="nav-search" placeholder="Search" />
<h2><a href="index.html">Home</a></h2><h2><a href="https://github.com/toolbox-team/reddit-moderator-toolbox" target="_blank" class="menu-item" >Github</a></h2><h2><a href="https://www.reddit.com/r/toolbox" target="_blank" class="menu-item" >Subreddit</a></h2><h3>Classes</h3><ul><li><a href="Module.html">Module</a><ul class='methods'><li data-type='method'><a href="Module.html#get">get</a></li><li data-type='method'><a href="Module.html#getEnabled">getEnabled</a></li><li data-type='method'><a href="Module.html#init">init</a></li><li data-type='method'><a href="Module.html#set">set</a></li><li data-type='method'><a href="Module.html#setEnabled">setEnabled</a></li></ul></li><li><a href="TBListener.html">TBListener</a><ul class='methods'><li data-type='method'><a href="TBListener.html#clear">clear</a></li><li data-type='method'><a href="TBListener.html#on">on</a></li><li data-type='method'><a href="TBListener.html#start">start</a></li><li data-type='method'><a href="TBListener.html#stop">stop</a></li></ul></li></ul><h3>Global</h3><ul><li><a href="global.html#DISPLAY_BOTTOM">DISPLAY_BOTTOM</a></li><li><a href="global.html#DISPLAY_CENTER">DISPLAY_CENTER</a></li><li><a href="global.html#FEEDBACK_NEGATIVE">FEEDBACK_NEGATIVE</a></li><li><a href="global.html#FEEDBACK_NEUTRAL">FEEDBACK_NEUTRAL</a></li><li><a href="global.html#FEEDBACK_POSITIVE">FEEDBACK_POSITIVE</a></li><li><a href="global.html#ModNotesBadge">ModNotesBadge</a></li><li><a href="global.html#ModNotesPager">ModNotesPager</a></li><li><a href="global.html#ModNotesPopup">ModNotesPopup</a></li><li><a href="global.html#NoteTableRow">NoteTableRow</a></li><li><a href="global.html#RandomFeedback">RandomFeedback</a></li><li><a href="global.html#RandomQuote">RandomQuote</a></li><li><a href="global.html#TBsettingsObject">TBsettingsObject</a></li><li><a href="global.html#actionButton">actionButton</a></li><li><a href="global.html#addModSubsToSidebar">addModSubsToSidebar</a></li><li><a href="global.html#addToSiteTable">addToSiteTable</a></li><li><a href="global.html#addTrophiesToSidebar">addTrophiesToSidebar</a></li><li><a href="global.html#alert">alert</a></li><li><a href="global.html#baseDomain">baseDomain</a></li><li><a href="global.html#browserName">browserName</a></li><li><a href="global.html#buildSha">buildSha</a></li><li><a href="global.html#buildType">buildType</a></li><li><a href="global.html#button">button</a></li><li><a href="global.html#checkForActions">checkForActions</a></li><li><a href="global.html#cleanSubredditName">cleanSubredditName</a></li><li><a href="global.html#clearCache">clearCache</a></li><li><a href="global.html#colorNameToHex">colorNameToHex</a></li><li><a href="global.html#contextTrigger">contextTrigger</a></li><li><a href="global.html#createDeferredProcessQueue">createDeferredProcessQueue</a></li><li><a href="global.html#daysToMilliseconds">daysToMilliseconds</a></li><li><a href="global.html#debounce">debounce</a></li><li><a href="global.html#debugInformation">debugInformation</a></li><li><a href="global.html#defaultNoteLabelValueToLabelType">defaultNoteLabelValueToLabelType</a></li><li><a href="global.html#delay">delay</a></li><li><a href="global.html#displayNotes">displayNotes</a></li><li><a href="global.html#domain">domain</a></li><li><a href="global.html#escapeHTML">escapeHTML</a></li><li><a href="global.html#fetchModSubs">fetchModSubs</a></li><li><a href="global.html#fetchNewsNotes">fetchNewsNotes</a></li><li><a href="global.html#figureOutMulti">figureOutMulti</a></li><li><a href="global.html#filterModdable">filterModdable</a></li><li><a href="global.html#getActions">getActions</a></li><li><a href="global.html#getAllModNotes">getAllModNotes</a></li><li><a href="global.html#getAnonymizedSettings">getAnonymizedSettings</a></li><li><a href="global.html#getCache">getCache</a></li><li><a href="global.html#getContextURL">getContextURL</a></li><li><a href="global.html#getLastVersion">getLastVersion</a></li><li><a href="global.html#getLatestModNote">getLatestModNote</a></li><li><a href="global.html#getModSubs">getModSubs</a></li><li><a href="global.html#getModlog">getModlog</a></li><li><a href="global.html#getRandomNumber">getRandomNumber</a></li><li><a href="global.html#getSetting">getSetting</a></li><li><a href="global.html#getSettingAsync">getSettingAsync</a></li><li><a href="global.html#getSettings">getSettings</a></li><li><a href="global.html#getSubmissionFullname">getSubmissionFullname</a></li><li><a href="global.html#getSubredditColors">getSubredditColors</a></li><li><a href="global.html#getTime">getTime</a></li><li><a href="global.html#getToolboxDevs">getToolboxDevs</a></li><li><a href="global.html#handleMessage">handleMessage</a></li><li><a href="global.html#handleTBThings">handleTBThings</a></li><li><a href="global.html#handleThing">handleThing</a></li><li><a href="global.html#hideModActionsThings">hideModActionsThings</a></li><li><a href="global.html#htmlDecode">htmlDecode</a></li><li><a href="global.html#htmlEncode">htmlEncode</a></li><li><a href="global.html#humaniseDays">humaniseDays</a></li><li><a href="global.html#init">init</a></li><li><a href="global.html#initialLoadPromise">initialLoadPromise</a></li><li><a href="global.html#isConfigValidVersion">isConfigValidVersion</a></li><li><a href="global.html#isEquivalent">isEquivalent</a></li><li><a href="global.html#isModSub">isModSub</a></li><li><a href="global.html#isNewModmail">isNewModmail</a></li><li><a href="global.html#isOldReddit">isOldReddit</a></li><li><a href="global.html#labelColors">labelColors</a></li><li><a href="global.html#labelNames">labelNames</a></li><li><a href="global.html#link">link</a></li><li><a href="global.html#listenerAliases">listenerAliases</a></li><li><a href="global.html#literalRegExp">literalRegExp</a></li><li><a href="global.html#makeCommentThread">makeCommentThread</a></li><li><a href="global.html#makeQueueOverlay">makeQueueOverlay</a></li><li><a href="global.html#makeSingleComment">makeSingleComment</a></li><li><a href="global.html#makeSubmissionEntry">makeSubmissionEntry</a></li><li><a href="global.html#makeUserSidebar">makeUserSidebar</a></li><li><a href="global.html#messageHandlers">messageHandlers</a></li><li><a href="global.html#millisecondsToDays">millisecondsToDays</a></li><li><a href="global.html#minutesToMilliseconds">minutesToMilliseconds</a></li><li><a href="global.html#modbarExists">modbarExists</a></li><li><a href="global.html#moveArrayItem">moveArrayItem</a></li><li><a href="global.html#newModmailSidebar">newModmailSidebar</a></li><li><a href="global.html#niceDateDiff">niceDateDiff</a></li><li><a href="global.html#notification">notification</a></li><li><a href="global.html#overlay">overlay</a></li><li><a href="global.html#pager">pager</a></li><li><a href="global.html#pagerForItems">pagerForItems</a></li><li><a href="global.html#parseComments">parseComments</a></li><li><a href="global.html#parser">parser</a></li><li><a href="global.html#popup">popup</a></li><li><a href="global.html#progressivePager">progressivePager</a></li><li><a href="global.html#purify">purify</a></li><li><a href="global.html#purifyObject">purifyObject</a></li><li><a href="global.html#regExpEscape">regExpEscape</a></li><li><a href="global.html#relativeTime">relativeTime</a></li><li><a href="global.html#reloadIframe">reloadIframe</a></li><li><a href="global.html#reloadToolbox">reloadToolbox</a></li><li><a href="global.html#remove">remove</a></li><li><a href="global.html#removeLastDirectoryPartOf">removeLastDirectoryPartOf</a></li><li><a href="global.html#removeQuotes">removeQuotes</a></li><li><a href="global.html#replaceAll">replaceAll</a></li><li><a href="global.html#replaceTokens">replaceTokens</a></li><li><a href="global.html#saneSort">saneSort</a></li><li><a href="global.html#saneSortAs">saneSortAs</a></li><li><a href="global.html#saveSettingsToBrowser">saveSettingsToBrowser</a></li><li><a href="global.html#searchProfile">searchProfile</a></li><li><a href="global.html#setCache">setCache</a></li><li><a href="global.html#setSetting">setSetting</a></li><li><a href="global.html#setSettingAsync">setSettingAsync</a></li><li><a href="global.html#settings">settings</a></li><li><a href="global.html#settingsToObject">settingsToObject</a></li><li><a href="global.html#shortVersion">shortVersion</a></li><li><a href="global.html#showNote">showNote</a></li><li><a href="global.html#sortBy">sortBy</a></li><li><a href="global.html#standardColors">standardColors</a></li><li><a href="global.html#stringToColor">stringToColor</a></li><li><a href="global.html#submissionFullnamesCache">submissionFullnamesCache</a></li><li><a href="global.html#tbRedditEvent">tbRedditEvent</a></li><li><a href="global.html#textFeedback">textFeedback</a></li><li><a href="global.html#timeConverterRead">timeConverterRead</a></li><li><a href="global.html#title_to_url">title_to_url</a></li><li><a href="global.html#toolboxVersion">toolboxVersion</a></li><li><a href="global.html#toolboxVersionName">toolboxVersionName</a></li><li><a href="global.html#typeNames">typeNames</a></li><li><a href="global.html#unescapeHTML">unescapeHTML</a></li><li><a href="global.html#unescapeJSON">unescapeJSON</a></li><li><a href="global.html#verifiedSettingsSave">verifiedSettingsSave</a></li><li><a href="global.html#watchForURLChanges">watchForURLChanges</a></li><li><a href="global.html#wrapWithLastValue">wrapWithLastValue</a></li><li><a href="global.html#zlibDeflate">zlibDeflate</a></li><li><a href="global.html#zlibInflate">zlibInflate</a></li></ul>
</nav>
<div id="main">
<h1 class="page-title">tbui.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import $ from 'jquery';
import {createRoot} from 'react-dom/client';
import tinycolor from 'tinycolor2';
import browser from 'webextension-polyfill';
import * as TBApi from './tbapi.ts';
import * as TBCore from './tbcore.js';
import * as TBHelpers from './tbhelpers.js';
import * as TBStorage from './tbstorage.js';
import {onDOMAttach} from './util/dom.ts';
import {reactRenderer} from './util/ui_interop.tsx';
import {showTextFeedback, TextFeedbackKind, TextFeedbackLocation} from './store/textFeedbackSlice.ts';
import store from './store/index.ts';
import {icons} from './tbconstants.ts';
export {icons};
const $body = $('body');
export const longLoadArray = [];
export const longLoadArrayNonPersistent = [];
// We don't want brack-buttons to propagate to parent elements as that often triggers the reddit lightbox
$body.on('click', '.tb-bracket-button', event => {
event.stopPropagation();
});
let subredditColorSalt;
let contextMenuLocation = 'left';
let contextMenuAttention = 'open';
let contextMenuClick = false;
(async () => {
subredditColorSalt = await TBStorage.getSettingAsync('QueueTools', 'subredditColorSalt', 'PJSalt');
contextMenuLocation = await TBStorage.getSettingAsync('GenSettings', 'contextMenuLocation', 'left');
contextMenuAttention = await TBStorage.getSettingAsync('GenSettings', 'contextMenuAttention', 'open');
contextMenuClick = await TBStorage.getSettingAsync('GenSettings', 'contextMenuClick', false);
})();
// Icons NOTE: string line length is ALWAYS 152 chars
export const logo64 =
`iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAAAsRAAALEQF/ZF+R
AAAAGHRFWHRTb2Z0d2FyZQBwYWludC5uZXQgNC4wLjVlhTJlAAAD1ElEQVR4Xu1ZS0hUURg+WY0tNFy0qCiCGpoaC8fXqBEZPWfRsgdRtCgkKBfRIqpFmZugAisLd9YiQsw2thGtsDYVQURBSRQ9FxER
FaRm5vT9+h853DmT3uE4Vzzng++e4/863/nvY+44wsFh6qG8vHx9aWnpLfBVSUnJG4xPi4uLz8A+l0MmF8rKyjZA5FmI3QLOY7NvoM5i1LkPJnVE7V/gCYTmjGRMEkDUdUXoX/zdg/EaxhqctRjmMzk0
LYqKigoR94VrjMWbSJk2khkwotFoCIK+ewR6+Q28jYbUg5sxn8Ppw4hEIvmwveNYyVbEbqd48BBITVX9pzg9WEDYJikK817wqyJSS8QMgs8xb8a9vRvjZcXfRzW5/CgSiUQufFdkHGL+4JZZyO7gACFN
iqimcDici7ECfx8G2zH/LP3jZC2X1iEH9ahxMraO7YEhByI+SUE4mwm2q5gO0SvBGsS0YHwr472E7yedac7TAnH7lPhONgcDCKhUxPwYS7wEGhVG/C7kNWN8rdR4zCFpgbi4Et/N5mAAAaelGLCFzb6A
vNWyBur1sDktELdRib/H5mAAAS+lGDyQdrDZF3A1zJc1wCFwGbu0QHyDjMf6bWzOPmKxWFQKAfvj8fhsdvkGNvJQ2VQXTNoXHTR5BWJ+y1hwD7uyDwg9rgjpYHNGQDO3KrWoCZ3gEnYT6GFLMaMvSvB/
oE8c9mcfEPBIisFluZ/NGQP1bsh6vEF6V3iC+R3wo+oDh+Bbx6nZBy73BSRCiqH7mF0Zo7q6ehZqtXPNtMTG+zDu5LRgABEHFFEP2GwEqFeL+u+V+pLU8A56DnBocICQLkXYUTYbA66GGdjoKnAvmnEQ
a2zDVbaI3cEC39oKIGpANgDClrPLDmDz9AYnz/4LNtuDpVVVbYWVlckoGKmoCPzLiDgvxN2LQnRni/V5eQP1+flJ4rlQ6FmjJiZbpL0LTPrBpKXsdw2gg8doE10DXAPo4DHaxIwacPWCEHU6ks8TOxE0
ub7/BlwSYg2/QqSAfLockzS8/nADemkyXuLFZS2vlwLy6XJM0vD6vaJViJAfnvzP72rk0+WYpOn1OdVi0H3TgEvHBws4NQXk88ROBI2tP/w8wdNzEPeC7gGhJeJTfneTIJ8uxyRNrk979/0pQJ3j9VJA
Pl2OSRpe3//HoPUNMPw57JuG13dvgpk0YCrRNcA1gA4eo010DXANoIPHaBNdA1wD6OAx2kTXANcAOniMNtE1wDWADh6jTXQNcA2gg8doE10DfP8wMpVIe6cr4EijEMdsJO2d/6Pu4GAnhPgH06SDEG5p
qnUAAAAASUVORK5CYII=`;
export const iconBot =
`iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACz0lEQVQ4T3VTXUhTYRh+zzbdNHZ0E5sjdLOiLnTahQaCFGiIwSK9iIGhGQjOM3GgN0MENYTJYGKiG91kPxe5qxkJk0jQ7EKwvHAarMTM
tvYD+2XqnHPr/Q4Jm60PDt95v/f7nvM8z/ccCs4NrVY7I5FIng4ODn5Lb+n1ernX69VNTk6q09ep8wAjIyOcvb09o0wm04+OjvpIX6PR3OJyuU1isfgJ9uP/BZiYmLgUDAYtqVTqSjKZFOKhMM5crGl8
D+LBHyKRSNXf3+86A8lgYDAYOuRy+UuFQgFutwdKS0tBIBDAzs4OFBTQ7Ly7u/tIp9O9ygowPm7oKSoSmQKBAJSVlYHP5wOhkMa9KQiFQsDhcCAWizEIYM4KYDQaew4PD01VVVXQ2HgHTKYZODqKQW+v
BhwOB9hsNigsLGQGBgayA0xNTfXQNG3yeDzA4/EA9UJ+/gXY3/8J6APKKICTkxOmr6/vXwCz2VzpcrneV1YqpHV1dSxloVDIMo1Go4DAsLa2Bltbdjf61NTV1bVFeqyJeLfX/X7/SnPzXcnq6kc4PT0F
dD3jhgmDRCIBDQ2NsLho80ql0tsMwzio6enpa0h5Wam8JyXuz829gerqG2iijNBlqefk5MDBQRTm563Q3a0Gu90OCwvv3Bi4GmpoaGgVDauvra2B7e2vpAEtLS1QXn6ZBSCD+BEOh2F29jkolUqoqKiA
9fXPsLT04RM1PDzsV6lU4ng8DlarNcLn82kMDxwfH2dIwHUgD/qRaG1t5eXm5oLFYglQY2Nj9filtxRFEe3a4uLi1+3tHZBMpmBlZRmczl+QXm9sfHmGjB78lXafNRHzLUCXKdR6FRubbW0PWQBiqMvl
hPTa7f7NINsXkUgkhediGVHGf0HB5fI2Ozs70TwgGpGBE9JrBMyeA8IEg8TH69zPy8u7SGqMbQgZxdPrkhLZTbX68fczg/4A1KNbXBApXrkAAAAASUVORK5CYII=`;
/** Map of commonly used color names to CSS color values. */
export const standardColors = {
red: '#FF0000',
softred: '#ED4337',
green: '#347235',
lightgreen: '#00F51E',
blue: '#0082FF',
magenta: '#DC00C8',
cyan: '#00F0F0',
yellow: '#EAC117',
softyellow: '#FFFC7F',
black: '#000000',
};
/** @deprecated Use {@linkcode TextFeedbackKind.NEUTRAL} */
export const FEEDBACK_NEUTRAL = TextFeedbackKind.NEUTRAL;
/** @deprecated Use {@linkcode TextFeedbackKind.POSITIVE} */
export const FEEDBACK_POSITIVE = TextFeedbackKind.POSITIVE;
/** @deprecated Use {@linkcode TextFeedbackKind.NEGATIVE} */
export const FEEDBACK_NEGATIVE = TextFeedbackKind.NEGATIVE;
/** @deprecated Use {@linkcode TextFeedbackLocation.CENTER} */
export const DISPLAY_CENTER = TextFeedbackLocation.CENTER;
/** @deprecated Use {@linkcode TextFeedbackLocation.BOTTOM} */
export const DISPLAY_BOTTOM = TextFeedbackLocation.BOTTOM;
/**
* Generates HTML for a general button.
* @param {string} text Raw HTML string rendered inside the button
* @param {string} classes Extra text added to the button's `class` attribute
* @returns {string}
*/
export const button = (text, classes) => `
<button class="tb-general-button ${classes}">${text}</button>
`;
/**
* Generates HTML for an action button.
* @param {string} text Raw HTML string rendered inside the button
* @param {string} classes Extra text added to the button's `class` attribute
* @returns {string}
*/
export const actionButton = (text, classes) => `
<button class="tb-action-button ${classes}">${text}</button>
`;
/**
* Generate a popup.
* @function
* @param {object} options Options for the popup
* @param {string} options.title The popup's title (raw HTML)
* @param {object[]} options.tabs The tabs for the popup
* @param {string} [options.footer] The popup footer (used for all tabs; if
* provided, tab footers are ignored)
* @param {string} [options.cssClass] Extra CSS class to add to the popup
* @param {string} [options.meta] Raw HTML to add to a "meta" container
* @param {boolean} [options.draggable=true] Whether the user can move the
* popup
* @param {string} [options.defaultTabID] If provided, the tab with this ID
* will be displayed initially; otherwise, the first tab will be shown
* @returns {jQuery}
*/
export function popup ({
title,
tabs,
footer,
cssClass = '',
meta,
draggable = true,
closable = true,
defaultTabID,
}) {
// tabs = [{id:"", title:"", tooltip:"", help_text:"", help_url:"", content:"", footer:""}];
const $popup = $(`
<div class="tb-window ${draggable ? 'tb-window-draggable' : ''} ${cssClass}">
${meta ? `<div class="meta" style="display: none;">${meta}</div>` : ''}
<div class="tb-window-header">
<div class="tb-window-title">${title}</div>
<div class="buttons">
<a class="close" href="javascript:;">
<i class="tb-icons">${icons.close}</i>
</a>
</div>
</div>
</div>
`);
if (tabs.length === 1) {
// We don't use template literals here as the content can be a jquery object.
$popup.append($('<div class="tb-window-content"></div>').append(tabs[0].content));
$popup.append($('<div class="tb-window-footer"></div>').append(footer || tabs[0].footer));
} else {
const $tabs = $('<div class="tb-window-tabs"></div>');
$popup.append($tabs);
for (let i = 0; i < tabs.length; i++) {
const tab = tabs[i];
if (tab.id === 'undefined' || !tab.id) {
tab.id = tab.title.trim().toLowerCase().replace(/\s/g, '_');
}
// Check whether this is the tab that will be shown first. If
// defaultTabID is given, compare that to this tab's ID; otherwise,
// just check if this is the first tab.
const isDefaultTab = defaultTabID == null ? i === 0 : tab.id === defaultTabID;
// Create tab button
const $button = $(`
<a class="${tab.id}" title="${tab.tooltip || ''}">
${tab.title}
</a>
`);
$button.click({tab}, function (e) {
const tab = e.data.tab;
// hide others
$tabs.find('a').removeClass('active');
$popup.find('.tb-window-tab').hide();
// show current
$popup.find(`.tb-window-tab.${tab.id}`).show();
$(this).addClass('active');
e.preventDefault();
});
// Activate the default tab
if (isDefaultTab) {
$button.addClass('active');
}
$button.appendTo($tabs);
// We don't use template literals here as the content can be a jquery object.
const $tab = $(`<div class="tb-window-tab ${tab.id}"></div>`);
$tab.append($('<div class="tb-window-content"></div>').append(tab.content));
if (!footer) {
// Only display tab footer if whole-popup footer not set
$tab.append($('<div class="tb-window-footer""></div>').append(tab.footer));
}
// Only show the default tab
if (isDefaultTab) {
$tab.show();
} else {
$tab.hide();
}
$tab.appendTo($popup);
}
// If we have a whole-popup footer, add it underneath the tabbed portion
if (footer) {
$popup.append($('<div class="tb-window-footer"></div>').append(footer));
}
}
if (draggable) {
$popup.drag($popup.find('.tb-window-header'));
// Don't let people drag by the buttons, that gets confusing
$popup.find('.buttons a').on('mousedown', e => e.stopPropagation());
}
if (closable) {
$popup.on('click', '.close', event => {
event.stopPropagation();
$popup.remove();
});
}
return $popup;
}
export function drawPosition (event) {
const positions = {
leftPosition: '',
topPosition: '',
};
const $overlay = $(event.target).closest('.tb-page-overlay');
if (document.documentElement.clientWidth - event.pageX < 400) {
positions.leftPosition = event.pageX - 600;
} else {
positions.leftPosition = event.pageX - 50;
}
if (document.documentElement.clientHeight - event.pageY < 200 && location.host === 'mod.reddit.com') {
const topPosition = event.pageY - 600;
if (topPosition < 0) {
positions.topPosition = 5;
} else {
positions.topPosition = event.pageY - 600;
}
} else {
positions.topPosition = event.pageY - 50;
}
if ($overlay.length) {
const scrollTop = $overlay.scrollTop();
positions.topPosition = event.clientY + scrollTop;
}
if (positions.topPosition < 0) {
positions.topPosition = 5;
}
return positions;
}
export function switchOverlayTab (overlayClass, tabName) {
const $overlay = $body.find(`.${overlayClass}`);
const $tab = $overlay.find(`[data-module="${tabName}"]`);
$overlay.find('.tb-window-tabs a').removeClass('active');
$tab.addClass('active');
$('.tb-window .tb-window-tab').hide();
$(`.tb-window .tb-window-tab.${tabName}`).show();
}
/**
* Generates an overlay containing a single large window.
* @param {object} options
* @param {string} options.title The title of the window
* @param {object[]} options.tabs An array of tab objects
* @param {string} [options.buttons] Additional buttons to add to the window's
* header as an HTML string
* @param {string} [options.footer] If provided, a single footer to use for all
* tabs rather than relying on the footer data from each provided tab object
* @param {object} [options.details] An object of metadata attached to the
* overlay, where each key:val of the object is mapped to a `data-key="val"`
* attribute
* @param {'vertical' | 'horizontal'} [options.tabOrientation='vertical']
* Orientation of the tab bar
*/
export function overlay ({
title,
tabs,
buttons = '',
footer,
details,
tabOrientation = 'vertical',
}) {
// If we have React components as tab contents, wrap them in renderers
tabs.forEach(tab => {
if (typeof tab.content === 'string' || tab.content instanceof $ || tab.content instanceof Element) {
// This is a normal thing we can pass to jQuery append no problem
return;
}
// This is some special React stuff
tab.content = reactRenderer(tab.content);
});
// tabs = [{id:"", title:"", tooltip:"", help_page:"", content:"", footer:""}];
const $overlay = $(`
<div class="tb-page-overlay">
<div class="tb-window tb-window-large ${tabOrientation === 'vertical' ? 'tb-window-vertical-tabs' : ''}">
<div class="tb-window-header">
<div class="tb-window-title">${title}</div>
<div class="buttons">
${buttons}
<a class="close" href="javascript:;">
<i class="tb-icons">${icons.close}</i>
</a>
</div>
</div>
</div>
</div>
`);
if (details) {
Object.entries(details).forEach(([key, value]) => {
$overlay.attr(`data-${key}`, value);
});
}
// we need a way to handle closing the overlay with a default, but also with use-specific cleanup code to run
// NOTE: Click handler binds should be attached to the parent element of the relevant object, not $(body).
// $overlay.on('click', '.buttons .close', function () {});
if (tabs.length === 1) {
$overlay.find('.tb-window').append($('<div class="tb-window-content"></div>').append(tabs[0].content));
$overlay.find('.tb-window').append($('<div class="tb-window-footer"></div>').append(footer ?? tabs[0].footer));
} else if (tabs.length > 1) {
$overlay.find('.tb-window').append($('<div class="tb-window-tabs"></div>'));
$overlay.find('.tb-window').append($('<div class="tb-window-tabs-wrapper"></div>'));
for (let i = 0; i < tabs.length; i++) {
const tab = tabs[i];
tab.disabled = typeof tab.disabled === 'boolean' ? tab.disabled : false;
tab.help_page = typeof tab.help_page !== 'undefined' ? tab.help_page : '';
if (!TBStorage.getSetting('Utils', 'advancedMode', false) && tab.advanced) {
continue;
}
if (tab.id === 'undefined' || !tab.id) {
tab.id = tab.title.trim().toLowerCase();
tab.id = tab.id.replace(/\s/g, '_');
}
const $button = $(
`<a${tab.tooltip ? ` title="${tab.tooltip}"` : ''} ${
tab.id ? ` data-module="${tab.id}"` : ''
} class="${tab.id}" >${tab.title} </a>`,
);
$button.data('help_page', tab.help_page);
if (tab.disabled) {
$button.addClass('tb-module-disabled');
$button.attr('title', 'This module is not active, you can activate it in the "Toggle Modules" tab.');
}
// click handler for tabs
$button.click({tab}, function (e) {
const tab = e.data.tab;
// hide others
$overlay.find('.tb-window-tabs a').removeClass('active');
$overlay.find('.tb-window-tab').hide();
// show current
$overlay.find(`.tb-window-tab.${tab.id}`).show();
// Only hide and show the footer if we have multiple options for it.
if (!footer) {
$overlay.find('.tb-window-footer').hide();
$overlay.find(`.tb-window-footer.${tab.id}`).show();
}
$(this).addClass('active');
e.preventDefault();
});
$button.appendTo($overlay.find('.tb-window-tabs'));
const $tab = $(`<div class="tb-window-tab ${tab.id}"></div>`);
// $tab.append($('<div class="tb-window-content">' + tab.content + '</div>'));
$tab.append($('<div class="tb-window-content"></div>').append(tab.content));
// individual tab footers (as used in .tb-config)
if (!footer) {
$overlay.find('.tb-window').append(
$(`<div class="tb-window-footer ${tab.id}"></div>`).append(tab.footer),
);
const $footer = $overlay.find(`.tb-window-footer.${tab.id}`);
if (i === 0) {
$footer.show();
} else {
$footer.hide();
}
}
// default first tab is active = visible; hide others
if (i === 0) {
$button.addClass('active');
$tab.show();
} else {
$tab.hide();
}
$tab.appendTo($overlay.find('.tb-window .tb-window-tabs-wrapper'));
}
}
// single footer for all tabs (as used in .tb-settings)
if (footer) {
$overlay.find('.tb-window').append($('<div class="tb-window-footer"></div>').append(footer));
}
return $overlay;
}
export function selectSingular (choices, selected) {
const $selector = $(`
<div class="select-single">
<select class="selector tb-action-button"></select>
</div>`);
const $selector_list = $selector.find('.selector');
// Add values to select
choices.forEach(keyValue => {
const value = keyValue.toLowerCase().replace(/\s/g, '_');
$selector_list.append($('<option>').attr('value', value).text(keyValue));
});
// Set selected value
$selector_list.val(selected).prop('selected', true);
return $selector;
}
export function selectMultiple (available, selected) {
available = available instanceof Array ? available : [];
selected = selected instanceof Array ? selected : [];
const $select_multiple = $(`
<div class="select-multiple">
<select class="selected-list left tb-action-button"></select>&nbsp;<button class="remove-item right tb-action-button">remove</button>&nbsp;
<select class="available-list left tb-action-button"></select>&nbsp;<button class="add-item right tb-action-button">add</button>&nbsp;
<div style="clear:both"></div>
</div>
`);
const $selected_list = $select_multiple.find('.selected-list');
const $available_list = $select_multiple.find('.available-list');
$select_multiple.on('click', '.remove-item', e => {
const $select_multiple = $(e.delegateTarget);
$select_multiple.find('.selected-list option:selected').remove();
});
$select_multiple.on('click', '.add-item', e => {
const $select_multiple = $(e.delegateTarget);
const $add_item = $select_multiple.find('.available-list option:selected');
// Don't add the sub twice.
let exists = false;
$selected_list.find('option').each(function () {
if (this.value === $add_item.val()) {
exists = true;
return false;
}
});
if (!exists) {
$selected_list.append($add_item.clone()).val($add_item.val());
}
});
available.forEach(value => {
$available_list.append($('<option>').attr('value', value).text(value));
});
selected.forEach(value => {
$selected_list.append($('<option>').attr('value', value).text(value));
});
return $select_multiple;
}
export function mapInput (labels, items) {
const keyLabel = labels[0];
const valueLabel = labels[1];
const $mapInput = $(`<div>
<table class="tb-map-input-table">
<thead><tr>
<td>${keyLabel}</td>
<td>${valueLabel}</td>
<td class="tb-map-input-td-remove">remove</td>
</tr></thead>
<tbody></tbody>
</table>
<a class="tb-map-input-add tb-icons tb-icons-positive" href="javascript:void(0)">${icons.addBox}</a></div>`);
const emptyRow = `
<tr class="tb-map-input-tr">
<td><input type="text" class="tb-input" name="key"></td>
<td><input type="text" class="tb-input" name="value"></td>
<td class="tb-map-input-td-remove">
<a class="tb-map-input-td-remove" href="javascript:void(0)"></a>
</td>
</tr>`;
// remove item
$mapInput.on('click', '.tb-map-input-remove', function () {
$(this).closest('.tb-map-input-tr').remove();
});
// add empty item
$mapInput.on('click', '.tb-map-input-add', () => {
$(emptyRow).appendTo($mapInput.find('.tb-map-input-table tbody'));
});
// populate items
if ($.isEmptyObject(items)) {
$(emptyRow).appendTo($mapInput.find('.tb-map-input-table tbody'));
} else {
Object.entries(items).forEach(([key, value]) => {
const $item = $(`
<tr class="tb-map-input-tr">
<td><input type="text" class="tb-input" value="${
TBHelpers.htmlEncode(unescape(key))
}" name="key"></td>
<td><input type="text" class="tb-input" value="${
TBHelpers.htmlEncode(unescape(value))
}" name="value"></td>
<td class="tb-map-input-td-remove">
<a class="tb-map-input-remove tb-icons tb-icons-negative tb-icons-align-middle" href="javascript:void(0)">${icons.delete}</a>
</td>
</tr>`);
$item.appendTo($mapInput.find('.tb-map-input-table tbody'));
});
}
return $mapInput;
}
/**
* Displays a feedback message on the screen which disappears after a time. Only
* one such message can be shown at a time, and calling this method will
* overwrite any message currently being shown.
* @param {string} feedbackText Message to display
* @param {TextFeedbackKind} feedbackKind Nature of the message (positive,
* neutral, negative) to affect the color of the message window
* @param {number} [displayDuration] How long the message should be displayed
* before being hidden, in milliseconds. Defaults to 3000. Pass `Infinity` to
* force the message to never disappear unless dismissed with a
* @param {TextFeedbackLocation} [displayLocation] The location on the screen
* where the message should be shown - center screen is the default, but
* long-lived messages can be moved to the bottom instead
*/
export function textFeedback (
feedbackText,
feedbackKind,
displayDuration = 3000,
displayLocation = TextFeedbackLocation.CENTER,
) {
store.dispatch(showTextFeedback({
message: feedbackText,
kind: feedbackKind,
location: displayLocation,
}, displayDuration));
}
// re-export related enums so they can be used without importing twice
// TODO: needing to do this kind of thing probably indicates we should structure
// our source folders better - e.g. putting all the things related to text
// feedback in a single `features/textFeedback` folder with an aggregated-export
// `index.js` that's friendly for consumers
export {TextFeedbackKind, TextFeedbackLocation};
// Our awesome long load spinner that ended up not being a spinner at all. It will attend the user to ongoing background operations with a warning when leaving the page.
export function longLoadSpinner (createOrDestroy, feedbackText, feedbackKind, feedbackDuration, displayLocation) {
if (createOrDestroy !== undefined) {
// if requested and the element is not present yet
if (createOrDestroy && longLoadArray.length === 0) {
$('head').append(`<style id="tb-long-load-style">
.mod-toolbox-rd #tb-bottombar, .mod-toolbox-rd #tb-bottombar-hidden {
bottom: 10px !important
}
</style>`);
$body.append(
`<div id="tb-loading-stuff"><span class="tb-loading-content"><img src="${
browser.runtime.getURL('data/images/snoo_running.gif')
}" alt="loading"> <span class="tb-loading-text">${TBCore.RandomFeedback}</span></span></div>`,
);
$body.append('<div id="tb-loading"></div>');
const $randomFeedbackWindow = $body.find('#tb-loading-stuff');
const randomFeedbackLeftMargin = $randomFeedbackWindow.outerWidth() / 2;
const randomFeedbackTopMargin = $randomFeedbackWindow.outerHeight() / 2;
$randomFeedbackWindow.css({
'margin-left': `-${randomFeedbackLeftMargin}px`,
'margin-top': `-${randomFeedbackTopMargin}px`,
});
longLoadArray.push('load');
// if requested and the element is already present
} else if (createOrDestroy && longLoadArray.length > 0) {
longLoadArray.push('load');
// if done and the only instance
} else if (!createOrDestroy && longLoadArray.length === 1) {
$('head').find('#tb-long-load-style').remove();
$body.find('#tb-loading').remove();
$body.find('#tb-loading-stuff').remove();
longLoadArray.pop();
// if done but other process still running
} else if (!createOrDestroy && longLoadArray.length > 1) {
longLoadArray.pop();
}
// Support for text feedback removing the need to fire two function calls from a module.
if (feedbackText !== undefined && feedbackKind !== undefined) {
textFeedback(feedbackText, feedbackKind, feedbackDuration, displayLocation);
}
}
}
// Our awesome long load spinner that ended up not being a spinner at all. It will attend the user to ongoing background operations, this variant will NOT warn when you leave the page.
export function longLoadNonPersistent (createOrDestroy, feedbackText, feedbackKind, feedbackDuration, displayLocation) {
if (createOrDestroy !== undefined) {
// if requested and the element is not present yet
if (createOrDestroy && longLoadArrayNonPersistent.length === 0) {
$('head').append(`<style id="tb-long-load-style-non-persistent">
.mod-toolbox-rd #tb-bottombar, .mod-toolbox-rd #tb-bottombar-hidden {
bottom: 10px !important
}
</style>`);
$body.append('<div id="tb-loading-non-persistent"></div>');
longLoadArrayNonPersistent.push('load');
// if requested and the element is already present
} else if (createOrDestroy && longLoadArrayNonPersistent.length > 0) {
longLoadArrayNonPersistent.push('load');
// if done and the only instance
} else if (!createOrDestroy && longLoadArrayNonPersistent.length === 1) {
$('head').find('#tb-long-load-style-non-persistent').remove();
$body.find('#tb-loading-non-persistent').remove();
longLoadArrayNonPersistent.pop();
// if done but other process still running
} else if (!createOrDestroy && longLoadArrayNonPersistent.length > 1) {
longLoadArrayNonPersistent.pop();
}
// Support for text feedback removing the need to fire two function calls from a module.
if (feedbackText !== undefined && feedbackKind !== undefined) {
textFeedback(feedbackText, feedbackKind, feedbackDuration, displayLocation);
}
}
}
export function beforeunload () {
if (longLoadArray.length > 0) {
return 'toolbox is still busy!';
}
}
let contextTimeout;
/**
* Add or remove a menu element to the context aware menu. Makes the menu
* shows if it was empty before adding, hides menu if it is empty after removing.
* @function
* @param {string} triggerId This will be part of the id given to the element.
* @param {object} options
* @param {boolean} options.addTrigger Indicates of the menu item needs to
* be added or removed.
* @param {string} options.triggerText Text displayed in menu. Not needed
* when addTrigger is false.
* @param {string} options.triggerIcon The material icon that needs to be
* displayed before the menu item. Defaults to 'label'
* @param {string} options.title Title to be used in title attribute. If no
* title is given the triggerText will be used.
* @param {object} options.dataAttributes Any data attribute that might be
* needed. Object keys will be used as the attribute name and value as value.
*/
export function contextTrigger (triggerId, options) {
// We really don't need two context menus side by side.
if (TBCore.isEmbedded) {
return;
}
const addTrigger = options.addTrigger;
// These elements we will need in the future.
let $tbContextMenu = $body.find('#tb-context-menu');
if (!$tbContextMenu.length) {
// Toolbox context action menu.
$tbContextMenu = $(`
<div id="tb-context-menu" class="show-context-${contextMenuLocation}">
<div id="tb-context-menu-wrap">
<div id="tb-context-header">Toolbox context menu</div>
<ul id="tb-context-menu-list"></ul>
</div>
<i class="tb-icons tb-context-arrow" href="javascript:void(0)">${
contextMenuLocation === 'left' ? icons.arrowRight : icons.arrowLeft
}</i>
</div>
`).appendTo($body);
$body.addClass(`tb-has-context-${contextMenuLocation}`);
if (contextMenuClick) {
$tbContextMenu.addClass('click-activated');
$tbContextMenu.on('click', () => {
if ($tbContextMenu.hasClass('open')) {
$tbContextMenu.removeClass('open');
} else {
$tbContextMenu.addClass('open');
}
});
} else {
$tbContextMenu.addClass('hover-activated');
}
}
const $tbContextMenuList = $body.find('#tb-context-menu-list');
// We are adding a menu item.
if (addTrigger) {
const triggerText = options.triggerText;
let triggerIcon = 'label';
if (options.triggerIcon) {
triggerIcon = options.triggerIcon;
}
const title = options.triggerText;
// Check if there are currently items in the menu.
const lengthBeforeAdd = $tbContextMenuList.find('li').length;
// Build the new menu item.
const $newMenuItem = $(`
<li id="${triggerId}" title="${title}">
<i class="tb-icons">${triggerIcon}</i>
<span>${triggerText}<span>
</li>
`);
// Add data attributes if needed.
if (options.dataAttributes) {
Object.entries(options.dataAttributes).forEach(([name, value]) => {
$newMenuItem.attr(`data-${name}`, value);
});
}
const $checkExists = $tbContextMenuList.find(`#${triggerId}`);
// Check if an item with the same id is already in the menu. If so we will replace it.
if ($checkExists.length) {
$checkExists.replaceWith($newMenuItem);
} else {
// Add the item to the menu.
$tbContextMenuList.append($newMenuItem);
// We are going a bit annoying here to draw attention to the fact that there is a new item in the menu.
// The alternative would be to always show the entire menu.
$tbContextMenu.addClass(contextMenuAttention);
clearTimeout(contextTimeout);
contextTimeout = setTimeout(() => {
$tbContextMenu.removeClass(contextMenuAttention);
}, contextMenuAttention === 'fade' ? 6000 : 1000);
}
// If the menu was empty it was hidden and we need to show it.
if (!lengthBeforeAdd) {
$tbContextMenu.addClass('show-tb-context');
}
} else {
// We are removing a menu item.
$tbContextMenuList.find(`#${triggerId}`).remove();
// Check the new menu length
const newLength = $tbContextMenuList.find('li').length;
// If there is nothing to show anymore we hide the menu.
if (newLength < 1) {
$tbContextMenu.removeClass('show-tb-context');
}
}
}
/**
* Handles toolbox generated `thing` items as they become visible in the viewport.
* @function
* @param {IntersectionObserverEntry[]} entries
* @param {IntersectionObserver} observer
*/
function handleTBThings (entries, observer) {
entries.forEach(entry => {
// The observer fires for everything on page load.
// This makes sure that we really only act on those items that are visible.
if (!entry.isIntersecting) {
return;
}
// Element is visible, we only want to handle it once. Stop observing.
observer.unobserve(entry.target);
const $element = $(entry.target);
if ($element.hasClass('tb-comment')) {
const $jsApiPlaceholderComment = $element.find('> .tb-comment-entry > .tb-jsapi-comment-container');
$jsApiPlaceholderComment.append('<span data-name="toolbox">');
const jsApiPlaceholderComment = $jsApiPlaceholderComment[0];
const $jsApiPlaceholderAuthor = $element.find(
'> .tb-comment-entry > .tb-tagline .tb-jsapi-author-container',
);
const jsApiPlaceholderAuthor = $jsApiPlaceholderAuthor[0];
$jsApiPlaceholderAuthor.append('<span data-name="toolbox">');
const commentAuthor = $element.attr('data-comment-author');
const postID = $element.attr('data-comment-post-id');
const commentID = $element.attr('data-comment-id');
const subredditName = $element.attr('data-subreddit');
const subredditType = $element.attr('data-subreddit-type');
// Comment
if (!$jsApiPlaceholderComment.hasClass('tb-frontend-container')) {
const detailObject = {
type: 'TBcomment',
data: {
author: commentAuthor,
post: {
id: postID,
},
id: commentID,
subreddit: {
name: subredditName,
type: subredditType,
},
},
};
const tbRedditEventComment = new CustomEvent('tbReddit', {detail: detailObject});
jsApiPlaceholderComment.dispatchEvent(tbRedditEventComment);
}
// Author
// We don't want to send events for things already handled.
if (!$jsApiPlaceholderAuthor.hasClass('tb-frontend-container')) {
const detailObject = {
type: 'TBcommentAuthor',
data: {
author: commentAuthor,
post: {
id: postID,
},
comment: {
id: commentID,
},
subreddit: {
name: subredditName,
type: subredditType,
},
},
};
const tbRedditEventAuthor = new CustomEvent('tbReddit', {detail: detailObject});
jsApiPlaceholderAuthor.dispatchEvent(tbRedditEventAuthor);
}
}
if ($element.hasClass('tb-submission')) {
const $jsApiPlaceholderSubmission = $element.find('.tb-jsapi-submission-container');
$jsApiPlaceholderSubmission.append('<span data-name="toolbox">');
const jsApiPlaceholderSubmission = $jsApiPlaceholderSubmission[0];
const $jsApiPlaceholderAuthor = $element.find('.tb-jsapi-author-container');
$jsApiPlaceholderAuthor.append('<span data-name="toolbox">');
const jsApiPlaceholderAuthor = $jsApiPlaceholderAuthor[0];
const submissionAuthor = $element.attr('data-submission-author');
const postID = $element.attr('data-post-id');
const subredditName = $element.attr('data-subreddit');
const subredditType = $element.attr('data-subreddit-type');
if (!$jsApiPlaceholderSubmission.hasClass('tb-frontend-container')) {
const detailObject = {
type: 'TBpost',
data: {
author: submissionAuthor,
id: postID,
permalink: `https://www.reddit.com/r/${subredditName}/comments/${postID.substring(3)}/`,
subreddit: {
name: subredditName,
type: subredditType,
},
},
};
const tbRedditEventSubmission = new CustomEvent('tbReddit', {detail: detailObject});
jsApiPlaceholderSubmission.dispatchEvent(tbRedditEventSubmission);
}
// We don't want to send events for things already handled.
if (!$jsApiPlaceholderAuthor.hasClass('tb-frontend-container')) {
const detailObject = {
type: 'TBpostAuthor',
data: {
author: submissionAuthor,
post: {
id: postID,
},
subreddit: {
name: subredditName,
type: subredditType,
},
},
};
const tbRedditEventAuthor = new CustomEvent('tbReddit', {detail: detailObject});
jsApiPlaceholderAuthor.dispatchEvent(tbRedditEventAuthor);
}
}
});
}
const viewportObserver = new IntersectionObserver(handleTBThings, {
rootMargin: '200px',
});
/**
* Will send out events similar to the reddit jsAPI events for the elements given.
* Only support 'comment' for now and will only send the commentAuthor event.
* @function
* @param {object} $elements jquery object containing the elements for which jsAPI events need to be send.