-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodules_profile.js.html
1071 lines (943 loc) · 49.4 KB
/
modules_profile.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>modules/profile.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#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#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#escapeHTML">escapeHTML</a></li><li><a href="global.html#exportSettings">exportSettings</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#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#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#importSettings">importSettings</a></li><li><a href="global.html#init">init</a></li><li><a href="global.html#isConfigValidVersion">isConfigValidVersion</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#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#searchProfile">searchProfile</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#syntaxHighlighterThemeSelect">syntaxHighlighterThemeSelect</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#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">modules/profile.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import $ from 'jquery';
import * as TBApi from '../tbapi.ts';
import * as TBCore from '../tbcore.js';
import * as TBHelpers from '../tbhelpers.js';
import TBListener from '../tblistener.js';
import {Module} from '../tbmodule.jsx';
import * as TBui from '../tbui.js';
import {icons} from '../util/icons.ts';
import createLogger from '../util/logging.ts';
import {purifyObject} from '../util/purify.js';
import {getSettingAsync} from '../util/settings.ts';
const log = createLogger('Profile');
export default new Module({
name: 'Profile Pro',
id: 'Profile',
enabledByDefault: true,
settings: [
{
id: 'alwaysTbProfile',
type: 'boolean',
default: false,
description: 'Always open toolbox profile overlay on reddit profiles.',
},
{
id: 'profileButtonEnabled',
type: 'boolean',
default: true,
description:
'Show profile button next to usernames in subs you mod. Allows you to quickly open the toolbox profile on that page.',
},
{
id: 'directProfileToLegacy',
type: 'boolean',
default: false,
description: 'Open legacy user overview when clicking on profile links.',
},
{
id: 'subredditColor',
type: 'boolean',
default: () => getSettingAsync('QueueTools', 'subredditColor', false),
hidden: true,
},
{
id: 'onlyshowInhover',
type: 'boolean',
default: () => getSettingAsync('GenSettings', 'onlyshowInhover', true),
hidden: true,
},
],
}, ({
alwaysTbProfile,
directProfileToLegacy,
subredditColor,
profileButtonEnabled,
onlyshowInhover,
}) => {
const $body = $('body');
let filterModThings = false;
let hideModActions = false;
let cancelSearch = true;
const listingTypes = ['overview', 'submitted', 'comments'];
// When profile links are clicked open them in the legacy view directly
if (directProfileToLegacy) {
$body.on('click', 'a', function (event) {
const userProfileRegex = /(?:\.reddit\.com)?\/(?:user|u)\/[^/]*?\/?$/;
const thisHref = $(this).attr('href');
// If the url matches and we are not on an old style profile already.
if (userProfileRegex.test(thisHref) && !userProfileRegex.test(window.location.href)) {
event.preventDefault();
const lastChar = thisHref.substr(-1);
const newHref = `${thisHref}${lastChar === '/' ? '' : '/'}overview`;
if (event.ctrlKey || event.metaKey) {
window.open(newHref, '_blank');
} else {
window.location.href = newHref;
}
}
});
}
/**
* Will hide or reveal mod actions in the toolbox profile overlay.
* @function hideModActionsThings
* @param {boolean} hide determines if actions should be shown or hidden.
*/
function hideModActionsThings (hide) {
const $things = $('.tb-thing');
if (hide) {
TBCore.forEachChunkedDynamic($things, thing => {
const $thing = $(thing);
const modAction = $thing.find('.tb-moderator').length;
if (modAction) {
$thing.addClass('tb-mod-hidden');
}
}, {framerate: 40});
} else {
TBCore.forEachChunkedDynamic($things, thing => {
const $thing = $(thing);
const modAction = $thing.find('.tb-moderator').length;
if (modAction) {
$thing.removeClass('tb-mod-hidden');
}
}, {framerate: 40});
}
}
/**
* Will hide or reveal items in the profile overlay that can't be modded.
* @function filterModdable
* @param {boolean} hide determines if items should be shown or hidden.
*/
async function filterModdable (hide) {
const $things = $('.tb-thing');
if (hide) {
const mySubs = await TBCore.getModSubs();
TBCore.forEachChunkedDynamic($things, thing => {
const $thing = $(thing);
const subreddit = TBHelpers.cleanSubredditName($thing.attr('data-subreddit'));
if (!mySubs.includes(subreddit)) {
$thing.addClass('tb-mod-filtered');
}
}, {framerate: 40});
} else {
TBCore.forEachChunkedDynamic($things, thing => {
const $thing = $(thing);
$thing.removeClass('tb-mod-filtered');
}, {framerate: 40});
}
}
/**
* Adds items to the toolbox profile overlay siteTable element
* @function addToSiteTable
* @param {array} data array of reddit things to be added in reddit API format
* @param {jqueryObject} $siteTable jquery object representing the siteTable
* @param {string} after reddit thing ID representing the start of the next page. If present will add a "load more" at the end of the siteTable
* @param {callback} callback callback function
* @returns {callback} returned when done
*/
function addToSiteTable (data, $siteTable, after, callback) {
// prepare comment options for TBUi comment creator.
const commentOptions = {
parentLink: true,
contextLink: true,
contextPopup: true,
fullCommentsLink: true,
overviewData: true,
};
const submissionOptions = {};
// Add subredditColor if applicable.
if (subredditColor) {
commentOptions.subredditColor = true;
submissionOptions.subredditColor = true;
}
// Use dynamic chuncking to add all things to the sitetable.
TBCore.forEachChunkedDynamic(data, entry => {
// Comment
if (entry.kind === 't1') {
const $comment = TBui.makeSingleComment(entry, commentOptions);
if (entry.highlight) {
$comment.find('.md').highlight(entry.highlight, '', true);
}
$siteTable.append($comment);
}
// Submission
if (entry.kind === 't3') {
const $submission = TBui.makeSubmissionEntry(entry, submissionOptions);
if (entry.highlight) {
$submission.find('.tb-title, .md').highlight(entry.highlight, '', true);
}
$siteTable.append($submission);
}
}).then(() => {
// More items available on a next page. Add load more element
if (after) {
$siteTable.append(`<div data-after="${after}" class="tb-load-more">load more</div>`);
}
// Fire jsAPI events and apply profile overlay filters where needed.
setTimeout(() => {
TBui.tbRedditEvent($siteTable);
if (filterModThings) {
filterModdable(true);
}
if (hideModActions) {
hideModActionsThings(true);
}
// Done, return callback.
return callback();
}, 1000);
});
}
/**
* Adds the user's trophies to the given sidebar element.
* @function addTrophiesToSidebar
* @param {string} user reddit username
* @param {jqueryObject} $sidebar jquery sidebar element to which the trophies need to be added
*/
function addTrophiesToSidebar (user, $sidebar) {
const inputURL = `/user/${user}/trophies.json`;
TBApi.getJSON(inputURL).then(data => {
if (Object.keys(data).length > 0 && data.constructor === Object) {
purifyObject(data);
const $userTrophies = $(`<div class="tb-user-trophies">
<h3> Trophies </h3>
</div>`).appendTo($sidebar);
data.data.trophies.forEach(trophy => {
let tropyHTML;
const trophyInnerHTML = `
<img class="tb-trophy-icon" src="${trophy.data.icon_40}">
<br>
<span class="tb-trophy-name">${trophy.data.name}</span>
<br>
${
trophy.data.description
? `<span class="tb-trophy-description">${trophy.data.description}</span>`
: ''
}
<br>`;
if (trophy.data.url) {
tropyHTML = `
<div class="tb-trophy-info">
<a href="${trophy.data.url}">
${trophyInnerHTML}
</a>
</div>`;
} else {
tropyHTML = `
<div class="tb-trophy-info">
${trophyInnerHTML}
</div>`;
}
$userTrophies.append(tropyHTML);
});
}
});
}
/**
* Adds the user's moderated subs to the given sidebar element.
* @function addModSubsToSidebar
* @param {string} user reddit username
* @param {jqueryObject} $sidebar jquery sidebar element to which the subreddits need to be added
*/
function addModSubsToSidebar (user, $sidebar) {
const inputURL = `/user/${user}/moderated_subreddits.json`;
TBApi.getJSON(inputURL).then(data => {
if (Object.keys(data).length > 0 && data.constructor === Object) {
purifyObject(data);
const $userModSubs = $(`<div class="tb-user-modsubs">
<h3> ${data.data.length} Moderated subreddits </h3>
</div>`).appendTo($sidebar);
const $moderatedSubListVisible = $('<ul class="tb-user-modsubs-ul"></ul>').appendTo($userModSubs);
const $moderatedSubListExpanded = $('<ul class="tb-user-modsubs-expand-ul"></ul>').appendTo(
$userModSubs,
);
let subCount = 0;
TBCore.forEachChunkedDynamic(data.data, subreddit => {
subCount++;
const subredditName = subreddit.sr;
const iconImage = subreddit.icon_img;
const over18 = subreddit.over_18;
const subscribers = subreddit.subscribers;
const liElement = `<li>
<a href="${
TBCore.link(`/r/${subredditName}`)
}" title="${subscribers} subscribers">/r/${subredditName}</a>
${
over18
? '<span class="tb-nsfw-stamp tb-stamp"><acronym title="Adult content: Not Safe For Work">NSFW</acronym></span>'
: ''
}
${iconImage ? `<img src="${iconImage}" class="tb-subreddit-icon">` : ''}
</li>`;
if (subCount < 10) {
$moderatedSubListVisible.append(liElement);
} else {
$moderatedSubListExpanded.append(liElement);
}
}, {framerate: 40}).then(() => {
if (subCount > 10) {
$moderatedSubListVisible.after(
`<button class="tb-general-button tb-sidebar-loadmod tb-more" data-action="more">${
subCount - 10
} more ...</button>`,
);
$moderatedSubListExpanded.after(
`<button class="tb-general-button tb-sidebar-loadmod tb-less" data-action="less">show ${
subCount - 10
} less</button>`,
);
$body.on('click', '.tb-sidebar-loadmod', function () {
const $this = $(this);
const action = $this.attr('data-action');
if (action === 'more') {
$moderatedSubListExpanded.show();
$sidebar.find('.tb-sidebar-loadmod.tb-less').show();
$this.hide();
} else if (action === 'less') {
$moderatedSubListExpanded.hide();
$sidebar.find('.tb-sidebar-loadmod.tb-more').show();
$this.hide();
}
});
}
addTrophiesToSidebar(user, $sidebar);
});
} else {
addTrophiesToSidebar(user, $sidebar);
}
});
}
/**
* Creates a user sidebar element for the given overlay
* @function makeUserSidebar
* @param {string} user reddit username
* @param {jqueryObject} $overlay jquery overlay element to which the sidebar needs to be added
*/
function makeUserSidebar (user, $overlay) {
const $tabWrapper = $overlay.find('.tb-window-tabs-wrapper');
const inputURL = `/user/${user}/about.json`;
TBApi.getJSON(inputURL).then(data => {
purifyObject(data);
const userThumbnail = data.data.icon_img;
const userCreated = data.data.created_utc;
const verifiedMail = data.data.has_verified_email;
const linkKarma = data.data.link_karma;
const commentKarma = data.data.comment_karma;
const displayName = data.data.subreddit.title;
const publicDescription = data.data.subreddit.public_description;
const createdAt = new Date(userCreated * 1000);
const $sidebar = $(`<div class="tb-profile-sidebar">
${userThumbnail ? `<img src="${userThumbnail}" class="tb-user-thumbnail">` : ''}
<ul class="tb-user-detail-ul">
<li><a href="${TBCore.link(`/user/${user}`)}">/u/${user}</a></li>
${displayName ? `<li>Display name: ${displayName}</li>` : ''}
<li>Link karma: ${linkKarma}</li>
<li>Comment karma: ${commentKarma}</li>
<li class="tb-user-detail-join-date">Joined </li>
<li>${verifiedMail ? 'Verified mail' : 'No verified mail'}</li>
</ul>
${
publicDescription
? `
<div class="tb-user-description">
${publicDescription}
</div>
`
: ''
}
</div>`);
$sidebar.find('.tb-user-detail-join-date').append(TBui.relativeTime(createdAt));
$tabWrapper.after($sidebar);
addModSubsToSidebar(user, $sidebar);
}).catch(error => {
log.error('Error fetching user information:', inputURL, error);
// This CSS uses inline-block and having whitespace screws it
// up, so this HTML has to start immediately after the quote :|
$tabWrapper.after(`<div class="tb-profile-sidebar">
<ul class="tb-user-detail-ul">
<li>No user information found - shadowbanned or deleted?</li>
</ul>
</div>`);
});
}
/**
* Searches a user profile for the given subreddit and/or string
* @function searchProfile
* @param {string} user reddit username
* @param {string} type the listing type that is to be searched
* @param {string} sortMethod the listing type that is to be searched
* @param {jqueryObject} $siteTable jquery siteTable element to which the search results need to be added
* @param {object} options search options
* @param {string} after reddit thing id indicating the next page
* @param {boolean} match indicates if there are previous
* @param {integer} pageCount what page we are on
* @param {callback} callback callback function
* @returns {callback} returns true when results have been found, false when none are found
*/
function searchProfile (user, type, sortMethod, $siteTable, options, after, match, pageCount, callback) {
pageCount++;
let hits = match || false;
const results = [];
const subredditPattern = options.subredditPattern || false;
const searchPattern = options.searchPattern || false;
if (!subredditPattern && !searchPattern) {
return callback(false);
}
// Cancel search if needed.
if (cancelSearch) {
TBui.textFeedback('Search canceled', TBui.FEEDBACK_NEUTRAL);
return callback(hits);
}
const inputURL = `/user/${user}/${type}.json`;
TBApi.getJSON(inputURL, {
raw_json: 1,
after,
sort: sortMethod,
limit: 100,
t: 'all',
}).then(data => {
// Also cancel search here as we really don't need to go over these results.
if (cancelSearch) {
TBui.textFeedback('Search canceled', TBui.FEEDBACK_NEUTRAL);
return callback(hits);
}
TBui.textFeedback(
`Searching profile page ${pageCount} with ${data.data.children.length} items`,
TBui.FEEDBACK_NEUTRAL,
);
purifyObject(data);
data.data.children.forEach(value => {
let hit = false;
let subredditMatch = false;
let patternMatch = false;
if (value.kind === 't1') {
subredditMatch = subredditPattern && subredditPattern.test(value.data.subreddit);
patternMatch = searchPattern && searchPattern.test(value.data.body);
}
if (value.kind === 't3') {
subredditMatch = subredditPattern && subredditPattern.test(value.data.subreddit);
patternMatch = searchPattern
&& (value.data.selftext && searchPattern.test(value.data.selftext)
|| searchPattern.test(value.data.title));
}
if (
subredditMatch && !searchPattern
|| patternMatch && !subredditPattern
|| subredditMatch && patternMatch
) {
hit = true;
}
if (hit) {
if (searchPattern) {
value.highlight = options.searchString;
}
results.push(value);
hits = true;
}
});
if (!data.data.after) {
if (results.length > 0) {
addToSiteTable(results, $siteTable, false, () => callback(hits));
} else {
return callback(hits);
}
} else {
if (results.length > 0) {
addToSiteTable(results, $siteTable, false, () => {
searchProfile(
user,
type,
sortMethod,
$siteTable,
options,
data.data.after,
hits,
pageCount,
found => callback(found),
);
});
} else {
searchProfile(
user,
type,
sortMethod,
$siteTable,
options,
data.data.after,
hits,
pageCount,
found => callback(found),
);
}
}
});
}
/**
* Escapes a string so it is suitable to be inserted in to a regex match
* @function regExpEscape
* @param {string} query reddit username
* @returns {string} string escaped for regex use
*/
function regExpEscape (query) {
return query.trim().replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}
// Initate user search
$body.on('submit', '.tb-searchuser', function () {
TBui.longLoadSpinner(true);
const $this = $(this);
const $windowContent = $this.closest('.tb-window-content');
const $siteTable = $windowContent.find('.tb-sitetable');
const typeListing = $siteTable.attr('data-listing');
let subredditsearch = $this.find('.tb-subredditsearch').val();
const usersearch = $this.closest('.tb-page-overlay').attr('data-user');
const contentsearch = $this.find('.tb-contentsearch').val();
const useSort = $this.find('.tb-search-sort').is(':checked');
let sortMethod = 'new';
if (useSort) {
sortMethod = $siteTable.attr('data-sort');
}
subredditsearch = subredditsearch.replace(/\/?r\//g, '');
subredditsearch = TBHelpers.htmlEncode(subredditsearch);
$siteTable.removeClass('tb-sitetable-processed');
$siteTable.empty();
const searchOptions = {};
if (subredditsearch) {
searchOptions.subredditPattern = new RegExp(`^${regExpEscape(subredditsearch)}$`, 'i');
}
if (contentsearch) {
searchOptions.searchPattern = TBHelpers.literalRegExp(contentsearch, 'gi');
searchOptions.searchString = contentsearch;
}
cancelSearch = false;
$('.tb-cancel-profile-search').show();
searchProfile(usersearch, typeListing, sortMethod, $siteTable, searchOptions, null, false, 0, results => {
$('.tb-cancel-profile-search').hide();
TBui.textFeedback('Search complete', TBui.FEEDBACK_POSITIVE);
if (results) {
TBui.longLoadSpinner(false);
} else {
TBui.longLoadSpinner(false);
$siteTable.append('<div class="error">no results found</div>');
}
if (cancelSearch) {
$siteTable.append('<div class="error">Search was canceled, results might be incomplete</div>');
}
});
return false;
});
// Cancel search
$body.on('click', '.tb-cancel-profile-search', () => {
TBui.textFeedback('Canceling search', TBui.FEEDBACK_NEUTRAL);
cancelSearch = true;
});
async function populateSearchSuggestion (subreddit) {
const mySubs = await TBCore.getModSubs(false);
if (subreddit && mySubs.includes(subreddit)) {
$body.find('#tb-search-suggest table#tb-search-suggest-list').append(
`<tr data-subreddit="${subreddit}"><td>${subreddit}</td></td></tr>`,
);
}
$(mySubs).each(function () {
if (this !== subreddit) {
$body.find('#tb-search-suggest table#tb-search-suggest-list').append(
`<tr data-subreddit="${this}"><td>${this}</td></td></tr>`,
);
}
});
}
function liveSearch (liveSearchValue) {
$body.find('#tb-search-suggest table#tb-search-suggest-list tr').each(function () {
const $this = $(this);
const subredditName = $this.attr('data-subreddit');
if (subredditName.toUpperCase().indexOf(liveSearchValue.toUpperCase()) < 0) {
$this.hide();
} else {
$this.show();
}
});
}
function initSearchSuggestion (subreddit) {
if (!$body.find('#tb-search-suggest').length) {
$body.append(
'<div id="tb-search-suggest" style="display: none;"><table id="tb-search-suggest-list"></table></div>',
);
populateSearchSuggestion(subreddit);
}
$body.on('focus', '.tb-subredditsearch', function () {
const offset = $(this).offset();
const offsetLeft = offset.left;
const offsetTop = offset.top + 26;
$body.find('#tb-search-suggest').css({
left: `${offsetLeft}px`,
top: `${offsetTop}px`,
});
if (!$body.find('#tb-search-suggest').is(':visible')) {
$body.find('#tb-search-suggest').show();
}
const liveSearchValue = $(this).val();
liveSearch(liveSearchValue);
});
$body.find('.tb-subredditsearch').keyup(function () {
const liveSearchValue = $(this).val();
liveSearch(liveSearchValue);
});
$(document).on('click', event => {
if (
!$(event.target).closest('#tb-search-suggest').length
&& !$(event.target).closest('.tb-subredditsearch').length
) {
$body.find('#tb-search-suggest').hide();
}
});
$body.on('click', '#tb-search-suggest-list tr', function () {
const subSuggestion = $(this).attr('data-subreddit');
$body.find('.tb-subredditsearch:visible').val(subSuggestion);
$body.find('#tb-search-suggest').hide();
});
}
function makeProfile (user, type, options) {
const sort = options.sort || 'new';
const renew = options.renew || false;
const after = options.after || '';
const subreddit = options.subreddit || '';
const content = options.content || '';
const search = options.search || false;
const searchSort = options.searchSort || false;
TBui.longLoadSpinner(true);
let $overlay = $body.find('.tb-profile-overlay');
if (!$overlay.length) {
$overlay = TBui.overlay({
title: `Toolbox profile for /u/${user}`,
tabs: [
{
title: 'overview',
tooltip: 'Overview profile.',
content: `
<div class="tb-profile-options tb-profile-options-overview"></div>
<div class="tb-sitetable tb-sitetable-overview"></div>
`,
footer: '',
},
{
title: 'submitted',
tooltip: 'submitted profile.',
content: `
<div class="tb-profile-options tb-profile-options-submitted"></div>
<div class="tb-sitetable tb-sitetable-submitted"></div>
`,
footer: '',
},
{
title: 'comments',
tooltip: 'comment profile.',
content: `
<div class="tb-profile-options tb-profile-options-comments"></div>
<div class="tb-sitetable tb-sitetable-comments"></div>
`,
footer: '',
},
],
tabOrientation: 'horizontal',
details: {
user,
},
})
.addClass('tb-profile-overlay')
.appendTo('body');
$body.css('overflow', 'hidden');
makeUserSidebar(user, $overlay);
$body.on('click', '.tb-profile-overlay .tb-window-header .close', () => {
// Cancel any ongoing search
cancelSearch = true;
$('.tb-profile-overlay').remove();
$body.css('overflow', 'auto');
filterModThings = false;
});
}
const $siteTable = $overlay.find(`.tb-sitetable-${type}`);
const $options = $overlay.find(`.tb-profile-options-${type}`);
$siteTable.attr({
'data-user': user,
'data-sort': sort,
'data-listing': type,
't': 'all',
});
if ($siteTable.hasClass('tb-sitetable-processed') && !renew && !after) {
TBui.longLoadSpinner(false);
return;
}
// Prevent some issues with people selecting a new sort method while toolbox is still busy.
$options.hide();
// Filter options
let $filterOptions = $options.find('.tb-filter-options');
if (!$filterOptions.length) {
$filterOptions = $(`
<div class="tb-filter-options">
<select class="tb-sort-select tb-general-button" data-type="${type}">
<option value="new">new</option>
<option value="top">top</option>
<option value="controversial">controversial</option>
<option value="hot">hot</option>
</select>
<button class="tb-general-button tb-filter-moddable">${
filterModThings ? 'Show unmoddable' : 'Hide unmoddable'
}</button>
<button name="hideModComments" class="tb-hide-mod-comments tb-general-button">${
hideModActions ? 'Show mod actions' : 'Hide mod actions'
}</a>
</div>`).appendTo($options);
$options.append(`
<form class="tb-searchuser">
search: <input type="text" placeholder="subreddit" class="tb-subredditsearch tb-input tb-search-input"> <input type="text" placeholder="content (optional)" class="tb-contentsearch tb-input tb-search-input">
<label> <input type="checkbox" class="tb-search-sort"> use sort selection </label>
<input type="submit" value=" search " class="tb-action-button">
</form>
${TBui.actionButton('cancel search', 'tb-cancel-profile-search')}
`);
initSearchSuggestion(subreddit);
}
const $sortSelect = $filterOptions.find('.tb-sort-select');
$sortSelect.val(sort);
if (!after) {
$siteTable.addClass('tb-sitetable-processed');
$siteTable.empty();
}
TBui.switchOverlayTab('tb-profile-overlay', type);
if (search) {
const $subreddit = $options.find('.tb-searchuser .tb-subredditsearch');
const $content = $options.find('.tb-searchuser .tb-contentsearch');
const $searchSort = $options.find('.tb-searchuser .tb-search-sort');
const $searchForm = $options.find('.tb-searchuser');
$subreddit.val(subreddit);
$content.val(content);
$searchSort.prop('checked', searchSort);
// Stop spinner to rpevent from duplicating.
TBui.longLoadSpinner(false);
// Show options and submit the search query.
$options.show();
$searchForm.submit();
} else {
const inputURL = `/user/${user}/${type}.json`;
TBApi.getJSON(inputURL, {
raw_json: 1,
after,
sort,
limit: 25,
}).then(data => {
purifyObject(data);
let after = false;
if (data.data.after) {
after = data.data.after;
}
addToSiteTable(data.data.children, $siteTable, after, () => {
TBui.longLoadSpinner(false);
$options.show();
});
}).catch(error => {
log.error('Error fetching profile activity:', inputURL, error);
$('.tb-profile-overlay .tb-window-content').html(`
<h1>No activity found</h1>
<p>Reddit doesn't seem to have anything for this account. Try checking your subreddit's moderation log to find posts and comments from them.</p>
`);
TBui.longLoadSpinner(false);
});
}
}
$body.on('click', '.tb-load-more', function () {
const $this = $(this);
const $siteTable = $this.closest('.tb-sitetable');
const after = $this.attr('data-after');
const user = $siteTable.attr('data-user');
const listing = $siteTable.attr('data-listing');
const sort = $siteTable.attr('data-sort');
makeProfile(user, listing, {sort, renew: false, after});
$this.remove();
});
$body.on('change keydown', '.tb-sort-select', function () {
const $this = $(this);
const newSort = $this.val();
const user = $this.closest('.tb-page-overlay').attr('data-user');
const listing = $this.attr('data-type');
makeProfile(user, listing, {sort: newSort, renew: true});
});
$body.on('click', '.tb-filter-moddable', () => {
const $filterMod = $body.find('.tb-filter-moddable');
if (filterModThings) {
filterModdable(false);
$filterMod.text('Hide unmoddable');
filterModThings = false;
} else {
filterModdable(true);
$filterMod.text('Show unmoddable');
filterModThings = true;
}
});
$body.on('click', '.tb-hide-mod-comments', () => {
const $hideMod = $('.tb-hide-mod-comments');
if (hideModActions) {
hideModActionsThings(false);
$hideMod.text('Hide mod actions');
hideModActions = false;
} else {
hideModActionsThings(true);
$hideMod.text('Show mod actions');
hideModActions = true;
}
});
$body.on('click', '.tb-profile-overlay .tb-window-tabs a', function () {
// Cancel any ongoing profile search first.
cancelSearch = true;
// Start creating specific listing overlay tab
const $this = $(this);
const listing = $this.attr('data-module');
const user = $this.closest('.tb-page-overlay').attr('data-user');
makeProfile(user, listing, {sort: 'new'});
});
window.addEventListener('TBNewPage', event => {
if (event.detail.pageType === 'userProfile' && listingTypes.includes(event.detail.pageDetails.listing)) {
const user = event.detail.pageDetails.user;
const listing = event.detail.pageDetails.listing;
TBui.contextTrigger('tb-user-profile', {
addTrigger: true,
triggerText: 'toolbox profile',
triggerIcon: icons.profile,
title: `Show toolbox profile for /u/${user}`,
dataAttributes: {
user,
listing,
},
});
if (alwaysTbProfile) {
// Prevent `alwaysTbProfile` from opening if there are hash params for opening a profile.
if (!event.detail.locationHref.includes('#?tbprofile')) {
makeProfile(user, listing, {sort: 'new', renew: false});
}
}
} else {
TBui.contextTrigger('tb-user-profile', {addTrigger: false});
}
});
if (profileButtonEnabled) {
TBListener.on('author', async e => {
const $target = $(e.target);
if (
!$target.closest('.tb-profile-overlay').length
&& (!onlyshowInhover || TBCore.isOldReddit || TBCore.isNewModmail)
) {
const author = e.detail.data.author;
const subreddit = e.detail.data.subreddit.name;
if (author === '[deleted]') {
return;
}
const isMod = await TBCore.isModSub(subreddit);
if (isMod) {
const profileButton =
`<a href="javascript:;" class="tb-user-profile tb-bracket-button" data-listing="overview" data-user="${author}" data-subreddit="${subreddit}" title="view & filter user's profile in toolbox overlay">P</a>`;
requestAnimationFrame(() => {
$target.append(profileButton);
});
}
}
});
TBListener.on('userHovercard', async e => {
const $target = $(e.target);
const subreddit = e.detail.data.subreddit.name;
const author = e.detail.data.user.username;
const isMod = await TBCore.isModSub(subreddit);
if (isMod) {
const profileButton =
`<a href="javascript:;" class="tb-user-profile tb-bracket-button" data-listing="overview" data-user="${author}" data-subreddit="${subreddit}" title="view & filter user's profile in toolbox overlay">Toolbox Profile View</a>`;
$target.append(profileButton);
}
});
}
$body.on('click', '#tb-user-profile, .tb-user-profile', function () {
const $this = $(this);
const user = $this.attr('data-user');
const listing = $this.attr('data-listing');
const subreddit = $this.attr('data-subreddit');
const options = {
sort: 'new',
renew: false,
};
if (subreddit) {
options.subreddit = subreddit;
}