-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodules_modnotes.jsx.html
746 lines (654 loc) · 32.9 KB
/
modules_modnotes.jsx.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>modules/modnotes.jsx - 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">modules/modnotes.jsx</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import {map, page, pipeAsync} from 'iter-ops';
import $ from 'jquery';
import {useEffect, useRef, useState} from 'react';
import {useFetched, useSetting} from '../hooks.ts';
import * as TBApi from '../tbapi.ts';
import {isModSub, isNewModmail, link} from '../tbcore.js';
import {escapeHTML} from '../tbhelpers.js';
import TBListener from '../tblistener.js';
import TBLog from '../tblog.ts';
import {Module} from '../tbmodule.jsx';
import {setSettingAsync} from '../tbstorage.js';
import {drawPosition, textFeedback, TextFeedbackKind} from '../tbui.js';
import {createBodyShadowPortal, reactRenderer} from '../util/ui_interop.tsx';
import {
ActionButton,
ActionSelect,
BracketButton,
Icon,
NormalInput,
RelativeTime,
} from '../components/controls/index.ts';
import {Pager} from '../components/Pager.tsx';
import {Window} from '../components/Window.tsx';
import {WindowTabs} from '../components/WindowTabs.tsx';
import css from './modnotes.module.css';
const log = TBLog('ModNotes');
/**
* An object mapping modnote types to human-friendly display names.
* @constant {object}
*/
const typeNames = {
NOTE: 'Note',
APPROVAL: 'Approve',
REMOVAL: 'Remove',
BAN: 'Ban',
MUTE: 'Mail Mute',
INVITE: 'Invite',
SPAM: 'Spam',
CONTENT_CHANGE: 'Update Post',
MOD_ACTION: 'Mod Action',
};
/**
* An object mapping modnote labels to display colors. All colors are from
* the default Toolbox usernote type colors, except the HELPFUL_USER label
* which doesn't have an analogue in Toolbox usernotes.
* @constant {object}
*/
const labelColors = {
BOT_BAN: 'black',
PERMA_BAN: 'darkred',
BAN: 'red',
ABUSE_WARNING: 'orange',
SPAM_WARNING: 'purple',
SPAM_WATCH: 'fuchsia',
SOLID_CONTRIBUTOR: 'green',
HELPFUL_USER: 'lightseagreen',
};
/**
* An object mapping modnote lavels to human-friendly display names.
* @constant {object}
*/
const labelNames = {
BOT_BAN: 'Bot Ban',
PERMA_BAN: 'Permaban',
BAN: 'Ban',
ABUSE_WARNING: 'Abuse Warning',
SPAM_WARNING: 'Spam Warning',
SPAM_WATCH: 'Spam Watch',
SOLID_CONTRIBUTOR: 'Solid Contributor',
HELPFUL_USER: 'Helpful User',
};
/**
* Mapping of possible values of the `defaultNoteLabelValue` setting to actual
* label type strings used by the API (or in the case of "none", `undefined`)
*/
const defaultNoteLabelValueToLabelType = {
none: undefined,
bot_ban: 'BOT_BAN',
permaban: 'PERMA_BAN',
ban: 'BAN',
abuse_warning: 'ABUSE_WARNING',
spam_warning: 'SPAM_WARNING',
spam_watch: 'SPAM_WATCH',
solid_contributor: 'SOLID_CONTRIBUTOR',
helpful_user: 'HELPFUL_USER',
};
// A queue of users and subreddits whose latest note will be fetched in the next
// bulk call, alongside the associated resolve and reject functions so we can
// pass the individual results back to their callers; used by `getLatestModNote`
let pendingLatestNoteRequests = [];
// The ID of the timeout for performing the bulk API request; used by
// `getLatestModNote` to debounce the request
let fetchLatestNotesTimeout;
/**
* Fetches the most recent mod note on the given user in the given subreddit.
* @param {string} subreddit The name of the subreddit
* @param {string} user The name of the user
* @returns {Promise} Resolves to a note object or `null`, or rejects an error
*/
function getLatestModNote (subreddit, user) {
return new Promise((resolve, reject) => {
// Add this user/subreddit to the queue to be included in the next call,
// alongside this promise's resolve and reject functions so we can pass
// the result back to the caller
pendingLatestNoteRequests.push({
subreddit,
user,
resolve,
reject,
});
// Each time this function is called, we set a timeout to process the
// queue 500ms later. However, if the function is called again in that
// time, that should be cancelled and rescheduled for 500ms after the
// later call.
// Cancel any existing timeout
clearTimeout(fetchLatestNotesTimeout);
fetchLatestNotesTimeout = null;
// If we have 500 users/subs queued, that's the max the API can handle
// at once, so process the queue now rather than waiting longer
if (pendingLatestNoteRequests.length === 500) {
processQueue();
return;
}
// Otherwise, set a timeout to process the queue in 500ms
fetchLatestNotesTimeout = setTimeout(processQueue, 500);
});
// This function executes the API request to fetch the latest note for all
// the users/subreddits queued, and distributes results (or errors) to their
// corresponding callers.
async function processQueue () {
// Store a copy of the queue as it is right now, then immediately clear
// the queue, so additional requests can be queued for the next batch
// while we handle the current batch
const queuedRequests = pendingLatestNoteRequests;
pendingLatestNoteRequests = [];
try {
// The API takes separate arrays of subs and users, so build those
const subreddits = queuedRequests.map(entry => entry.subreddit);
const users = queuedRequests.map(entry => entry.user);
// Perform the request to fetch the notes
const notes = await TBApi.getRecentModNotes(subreddits, users);
// We now have to pass each note to the appropriate caller's promise
// resolver; since the arrays are in the same order, we can loop
// over all the resolve functions and call them, passing the note at
// the corresponding index in the notes array
for (const [i, {resolve}] of Object.entries(queuedRequests)) {
resolve(notes[i]);
}
} catch (error) {
// If there was an error, reject all the the promises
for (const {reject} of queuedRequests) {
reject(error);
}
}
}
}
/**
* Creates a generator which lazily fetches all mod notes for a user in a
* subreddit that match the given filter.
* @param {string} subreddit The name of the subreddit
* @param {string} user The name of the user
* @param {string} filter Criteria for filtering notes
* @returns {AsyncGenerator<any, void>}
*/
async function* getAllModNotes (subreddit, user, filter) {
// Starts with the latest page of notes
let before = undefined;
while (true) {
// Fetch the next page of notes
const {notes, endCursor, hasNextPage} = await TBApi.getModNotes({
subreddit,
user,
filter,
before,
});
// Yield each note we fetched
for (const note of notes) {
yield note;
}
// End the generator if there's no next page to fetch
if (!hasNextPage) {
return;
}
// Set `before` so the next page is fetched next pass
before = endCursor;
}
}
/**
* In-page cache of comment fullnames to the fullnames of their submissions.
* Values of this object are promises which resolve to fullnames, rather than
* bare strings - we keep the promises around after they're resolved, and always
* deal with this cache asynchronously.
* @constant {Record<string, Promise<string>>}
*/
const submissionFullnamesCache = Object.create(null);
/**
* Gets the fullname of a comment's corresponding submission.
* @param {string} commentFullname Fullname of a comment
* @returns {Promise<string>} Fullname of the comment's submission
*/
export function getSubmissionFullname (commentFullname) {
// If it's in cache, return that
const cached = submissionFullnamesCache[commentFullname];
if (cached) {
return cached;
}
// Fetch the submission fullname fresh
// Note that we're not awaiting this - we want the full promise
const submissionFullnamePromise = TBApi.getInfo(commentFullname)
.then(info => info.data.link_id);
// Write to cache and return
submissionFullnamesCache[commentFullname] = submissionFullnamePromise;
return submissionFullnamePromise;
}
/**
* Gets a link to the context item of a note.
* @param {object} note A mod note object
* @returns {Promise<string | null>} Resolves to a URL that points to the note's
* context item, or `null` if there is none
*/
async function getContextURL (note) {
const itemFullname = note.user_note_data?.reddit_id || note.mod_action_data?.reddit_id;
// Can't link to something that isn't there
if (!itemFullname) {
return null;
}
// Split fullname into type and ID
const [itemType, itemID] = itemFullname.split('_');
// Post links only require the ID of the post itself, which we have
if (itemType === 't3') {
return link(`/comments/${itemID}`);
}
// Comment links require the link ID of their submission, which we need to fetch
if (itemType === 't1') {
const submissionFullname = await getSubmissionFullname(itemFullname);
return link(`/comments/${submissionFullname.replace('t3_', '')}/_/${itemID}`);
}
// This ID is for some other item type which we can't process
return null;
}
/**
* Creates a mod note badge for the given information.
* @param {object} data Data associated with the badge
* @param {string} data.user Name of the relevant user
* @param {string} data.subreddit Name of the relevant subreddit
* @param {string} data.label Text shown in the badge if there are no notes
* @param {object} [data.note] The most recent mod note left on the user
* @returns {jQuery} The created badge
*/
function ModNotesBadge ({
label = 'NN',
user,
subreddit,
note,
onClick,
}) {
let badgeContents = label;
if (note && note.user_note_data) {
const label = note.user_note_data.label;
const noteColor = label && labelColors[label];
badgeContents = (
<b style={{color: noteColor}}>
{note.user_note_data.note}
</b>
);
}
return (
<BracketButton
className='tb-bracket-button tb-modnote-badge'
tabIndex='0'
title={`Mod notes for /u/${user} in /r/${subreddit}`}
onClick={onClick}
>
{badgeContents}
</BracketButton>
);
}
/** Returns a pager for mod notes on the user in the subreddit matching the filter. */
function ModNotesPager ({user, subreddit, filter: noteFilter}) {
async function deleteNote (noteID) {
try {
await TBApi.deleteModNote({
user,
subreddit,
id: noteID,
});
// TODO: present note deletion visibly to user
textFeedback('Note removed!', TextFeedbackKind.POSITIVE);
} catch (error) {
log.error('Failed to delete note:', error);
textFeedback('Failed to delete note', TextFeedbackKind.NEGATIVE);
}
}
return (
<Pager
controlPosition='bottom'
emptyContent={<p>No notes</p>}
pages={pipeAsync(
// fetch mod notes that match this tab
getAllModNotes(subreddit, user, noteFilter),
// group into pages of 20 items each
page(20),
// construct the table and insert the generated rows for each
// page
map(pageItems => (
<table className={css.noteTable}>
<thead>
<tr>
<th>Author</th>
<th>Type</th>
<th>Details</th>
<th></th>
</tr>
</thead>
<tbody>
{pageItems.map(note => (
<NoteTableRow
key={note.id}
note={note}
onDelete={() => deleteNote(note.id)}
/>
))}
</tbody>
</table>
)),
)}
/>
);
}
/**
* Creates a mod note popup for the given information.
* @param {object} data Data associated with the popup
* @param {string} data.user Name of the relevant user
* @param {string} data.subreddit Name of the relevant subreddit
* @param {string} [data.contextID] Fullname of the item the popup was opened from, used to write note context
* @param {Function} data.onClose Close handler for the popup
* @returns {jQuery} The created popup
*/
function ModNotesPopup ({
user,
subreddit,
contextID,
defaultTabName,
defaultNoteLabel,
initialPosition,
onClose,
}) {
const tabs = [
{
title: 'All Activity',
content: <ModNotesPager user={user} subreddit={subreddit} />,
},
{
title: 'Notes',
content: <ModNotesPager user={user} subreddit={subreddit} filter='NOTE' />,
},
{
title: 'Mod Actions',
content: <ModNotesPager user={user} subreddit={subreddit} filter='MOD_ACTION' />,
},
];
let defaultTabIndex = 0;
if (defaultTabName === 'notes') {
defaultTabIndex = 1;
} else if (defaultTabName === 'actions') {
defaultTabIndex = 2;
}
// Handle note creation
async function submitNewNote (formData) {
try {
await TBApi.createModNote({
user,
subreddit,
redditID: contextID,
note: formData.get('note'),
label: formData.get('label'),
});
textFeedback('Note saved', TextFeedbackKind.POSITIVE);
// Close the popup after a successful save
onClose();
} catch (error) {
log.error('Failed to create mod note:', error);
textFeedback('Failed to create mod note', TextFeedbackKind.NEGATIVE);
}
}
// Using autoFocus on the note text input causes the page to jump around;
// manually focus it with `preventScroll` to avoid this
const noteInputRef = useRef(null);
useEffect(() => {
if (noteInputRef.current == null) {
return;
}
noteInputRef.current.focus({preventScroll: true});
}, []);
const popupFooter = (
<form className={css.modnoteCreateForm} action={submitNewNote}>
<ActionSelect
name='label'
defaultValue={defaultNoteLabelValueToLabelType[defaultNoteLabel]}
>
<option value=''>(no label)</option>
{Object.entries(labelNames).reverse().map(([value, name]) => (
<option key={value} value={value}>{name}</option>
))}
</ActionSelect>
<NormalInput
ref={noteInputRef}
type='text'
name='note'
inFooter
placeholder='Add a note...'
/>
<ActionButton type='submit'>
Create Note
</ActionButton>
</form>
);
// Create the base popup
return (
<Window
title={`Mod notes for /u/${user} in /r/${subreddit}`}
footer={popupFooter}
draggable
initialPosition={initialPosition}
onClose={onClose}
>
<WindowTabs
tabs={tabs}
defaultTabIndex={defaultTabIndex}
/>
</Window>
);
}
/**
* A row of the notes table displaying details about the given note.
* @param {object} props.note A note object
*/
function NoteTableRow ({note, onDelete}) {
const createdAt = new Date(note.created_at * 1000);
const mod = note.operator; // TODO: can [deleted] show up here?
const contextURL = useFetched(getContextURL(note));
return (
<tr>
<td>
<a href={link(`/user/${encodeURIComponent(mod)}`)}>
/u/{mod}
</a>
<br />
<small>
{contextURL
? (
<a href={contextURL}>
<RelativeTime date={createdAt} />
</a>
)
: <RelativeTime date={createdAt} />}
</small>
</td>
<td>
{typeNames[note.type]}
</td>
<td>
{note.mod_action_data?.action && (
<span className={css.actionSummary}>
Took action {'"'}
{note.mod_action_data.action}
{'"'}
{note.mod_action_data.details && ` (${note.mod_action_data.details})`}
{note.mod_action_data.description && `: ${note.mod_action_data.description}`}
</span>
)}
{note.user_note_data?.note && (
<blockquote>
{note.user_note_data.label && (
<span style={{color: labelColors[note.user_note_data.label]}}>
[{labelNames[note.user_note_data.label] || note.user_note_data.label}]
</span>
)} {note.user_note_data.note}
</blockquote>
)}
</td>
<td>
{note.type === 'NOTE' && (
<a
role='button'
title='Delete note'
data-note-id={escapeHTML(note.id)}
onClick={() => onDelete()}
>
<Icon mood='negative' icon='delete' />
</a>
)}
</td>
</tr>
);
}
const ModNotesUserRoot = ({user, subreddit, contextID}) => {
// Get settings
const defaultTabName = useSetting('ModNotes', 'defaultTabName', 'all_activity');
const defaultNoteLabel = useSetting('ModNotes', 'defaultNoteLabel', 'none');
// Fetch the latest note for the user
const note = useFetched(getLatestModNote(subreddit, user));
const [popupShown, setPopupShown] = useState(false);
const [popupClickEvent, setPopupClickEvent] = useState(null);
/** @type {{top: number; left: number} | undefined} */
let initialPosition = undefined;
if (popupClickEvent) {
const positions = drawPosition(popupClickEvent);
initialPosition = {
top: positions.topPosition,
left: positions.leftPosition,
};
}
function showPopup (event) {
setPopupShown(true);
setPopupClickEvent(event);
}
function hidePopup () {
setPopupShown(false);
setPopupClickEvent(null);
}
return (
<>
<ModNotesBadge
label='NN'
user={user}
subreddit={subreddit}
note={note}
onClick={showPopup}
/>
{popupShown && createBodyShadowPortal(
<ModNotesPopup
user={user}
subreddit={subreddit}
contextID={contextID}
defaultTabName={defaultTabName}
defaultNoteLabel={defaultNoteLabel}
initialPosition={initialPosition}
onClose={hidePopup}
/>,
)}
</>
);
};
export default new Module({
name: 'Mod Notes',
id: 'ModNotes',
enabledByDefault: true,
settings: [
{
id: 'defaultTabName',
description: 'Default tab for the modnotes window',
type: 'selector',
values: [
'All Activity',
'Notes',
'Actions',
],
default: 'all_activity',
},
{
id: 'defaultNoteLabel',
description: 'Default label for new notes',
type: 'selector',
values: [
'None',
...Object.values(labelNames),
],
default: 'none',
},
],
}, function () {
// Clean up old broken cache storage key
// TODO: Remove this a couple versions from now when people have reasonably
// probably updated past this
setSettingAsync(this.id, 'cachedParentFullnames', undefined);
// Handle authors showing up on the page
TBListener.on('author', async e => {
const subreddit = e.detail.data.subreddit.name;
const author = e.detail.data.author;
const contextID = isNewModmail ? undefined : e.detail.data.comment?.id || e.detail.data.post?.id;
// Deleted users can't have notes
if (author === '[deleted]') {
return;
}
// Can't fetch notes in a sub you're not a mod of
// TODO: What specific permissions are required to fetch notes?
const isMod = await isModSub(subreddit);
if (!isMod) {
return;
}
// Return early if we don't have the things we need
if (!e.detail.data.subreddit.name || !e.detail.data.author) {
return;
}
// Display badge for notes if not already present
const $target = $(e.target);
if ($target.find('.tb-modnote-badge-react-root').length) {
return;
}
const badgeRoot = reactRenderer(
<ModNotesUserRoot
user={author}
subreddit={subreddit}
contextID={contextID}
/>,
);
badgeRoot.classList.add('tb-modnote-badge-react-root');
$target.append(badgeRoot);
});
});
</code></pre>
</article>
</section>
</div>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 4.0.2</a> on Mon Dec 30 2024 00:15:02 GMT+0000 (Coordinated Universal Time) using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
</footer>
<script>prettyPrint();</script>
<script src="scripts/polyfill.js"></script>
<script src="scripts/linenumber.js"></script>
<script src="scripts/search.js" defer></script>
</body>
</html>