Repository navigation
Expand file tree
/
Copy pathanrfc-lister.js
More file actions
491 lines (417 loc) · 16.6 KB
/
Copy pathanrfc-lister.js
File metadata and controls
491 lines (417 loc) · 16.6 KB
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
// {{Wikipedia:USync |repo=https://github.com/NovemLinguae/UserScripts |ref=refs/heads/master |path=anrfc-lister.js}}
/*
Forked from https://en.wikipedia.org/wiki/User:Ajbura/anrfc-lister.js. A big thanks to the original author, Ajbura.
HOW TO USE:
- go to a talk page
- click More -> ANRFC Lister
- there will now be "List on ANRFC" links next to each section. click one
- fill out the form
- press "Submit"
- the script will add a listing to WP:ANRFC for you :)
SKINS IT WORKS IN:
- vector
- vector-2022
- timeless
- monobook
- modern
SKINS IT DOESNT WORK IN:
- minerva
CHANGES BY NOVEM LINGUAE:
- Linted code. Added comments. Refactored.
- Works on testwiki now (gives a local WP:ANRFC link instead of an enwiki WP:ANRFC link).
- Fixed bug where the script was always in an endless loop
- Fixed bug where the RFC would always get placed at the bottom of the page, not in its proper section
- Fixed bug where section heading (the # part of the wikilink) was not getting added to WP:ANRFC
- Fixed bug where More -> ANRFC Lister link was the wrong size and did not match the style of the skin
- Fixed bug where no signature or a signature too far down caused it to hang forever
- Added a "Cancel" button to the form
- No longer displays on special pages, diffs, editing a page, etc.
- Clicking "Would you like to see it?" now takes you to exact section, instead of top of page.
- Fixed duplicate RFC listing detection.
- Titles shouldn't have underscores
- Fixed bug where the script would always give "signature not found" error if you had MediaWiki:Gadget-CommentsInLocalTime.js gadget installed
- Handles the WP:ANRFC renaming of "Deletion discussions" to "XfD discussions"
- Better error handling for when the algorithm can't find the section in WP:ANRFC's wikitext
CHANGES BY OTHERS SINCE THIS WAS FORKED
- Added dark mode support
NOVEM LINGUAE TODO:
- test unicode titles
- test titles with weird punctuation in section names, e.g. ending in ?
- get it working in Minerva
*/
// <nowiki>
const style = `.anrfc-box {
margin: 16px 0px;
padding: 16px;
background-color: var(--background-color-neutral-subtle, #f8f9fa);
color: inherit;
border: 1px solid #a2a9b1;
font-size: 14px;
font-family: sans-serif;
}
.anrfc-box > h3 {
margin: 0 0 16px;
}
.anrfc-box .anrfc-box-margins {
margin-top: 8px;
}
.mw-ANRFC {
margin-left: 8px;
font-size: small;
font-family: sans-serif;
}
#ca-anrfc .anrfc-link-active {
color: var(--color-destructive, #bf3c2c);
}
#ca-anrfc .anrfc-link-active:hover {
color: var(--color-destructive--hover, #9f3526);
}
`;
mw.util.addCSS( style );
class ANRFC {
constructor( document, mw, $ ) {
this.document = document;
this.mw = mw;
// eslint-disable-next-line no-jquery/variable-pattern
this.$ = $;
this.sections = [
'Administrative discussions',
'Requests for comment',
'XfD discussions',
'Requested moves',
'Other types of closing requests'
];
}
async execute() {
const isNotViewing = this.mw.config.get( 'wgAction' ) !== 'view';
if ( isNotViewing ) {
return;
}
const isDiff = this.mw.config.get( 'wgDiffNewId' );
if ( isDiff ) {
return;
}
const isVirtualNamespace = this.mw.config.get( 'wgNamespaceNumber' ) < 0;
if ( isVirtualNamespace ) {
return;
}
this.mw.util.addPortletLink( 'p-cactions', '#', 'ANRFC lister', 'ca-anrfc' );
this.$( '#ca-anrfc' ).on( 'click', () => {
this.toggle();
} );
}
toggle() {
const $anrfcListerLinkInMoreMenu = this.$( '#ca-anrfc a' );
if ( $anrfcListerLinkInMoreMenu.hasClass( 'anrfc-link-active' ) ) {
$anrfcListerLinkInMoreMenu.removeClass( 'anrfc-link-active' );
this.removeLabels();
} else {
$anrfcListerLinkInMoreMenu.addClass( 'anrfc-link-active' );
this.addLabels();
}
}
removeLabels() {
const that = this;
this.$( 'a.mw-ANRFC' ).each( function () {
this.remove();
const keyId = this.getAttribute( 'indexKey' ) + '-anrfcBox';
if ( that.document.getElementById( keyId ) !== null ) {
return that.document.getElementById( keyId ).remove();
}
} );
}
addLabels() {
// Target the [ vedit | edit source ] buttons by each section heading
const that = this;
this.$( 'span.mw-editsection' ).each( function ( index ) {
// Add it
that.$( this.parentElement ).append( '<a indexKey=' + index + " class='mw-ANRFC'>List on ANRFC</a>" );
// Style it
that.$( 'a[indexkey="' + index + '"]' ).on( 'click', function () {
that.addForm( this );
} );
} );
}
/**
* @param el HTML element span.mw-editsection
*/
addForm( el ) {
// If there's a form already created, delete it. (This makes the "List on ANRFC" link a toggle that opens the form or closes the form, based on current state.)
const keyId = el.getAttribute( 'indexKey' ) + '-anrfcBox';
if ( this.document.getElementById( keyId ) !== null ) {
return this.document.getElementById( keyId ).remove();
}
const $anrfcBox = this.getFormHtmlAndSetFormListeners( keyId );
// el (span.mw-editsection) -> parent (h2) -> after
this.$( el ).parent().after( $anrfcBox );
}
getFormHtmlAndSetFormListeners( keyId ) {
const $anrfcBox = this.$( '<div>', {
id: keyId,
class: 'anrfc-box'
} );
const items = [];
let i = 0;
for ( const section of this.sections ) {
items.push( new OO.ui.MenuOptionWidget( {
data: i,
label: section
} ) );
i++;
}
const dropDown = new OO.ui.DropdownWidget( {
label: 'Dropdown menu: Select discussion section',
menu: {
items: items
}
} );
const messageInput = new OO.ui.MultilineTextInputWidget( {
placeholder: 'Custom message (optional)',
multiline: true,
autosize: true,
maxRows: 4
} );
const submitButton = new OO.ui.ButtonWidget( {
label: 'Submit',
flags: [
'progressive',
'primary'
]
} );
const cancelButton = new OO.ui.ButtonWidget( {
label: 'Cancel'
} );
$anrfcBox.append( '<h3>List this discussion on <a href="/wiki/Wikipedia:Closure_requests" target="_blank">Wikipedia:Closure requests</a></h3>' );
let wrapper = this.document.createElement( 'div' );
this.$( wrapper ).append( '<p>Under section: </p>' );
this.$( wrapper ).append( dropDown.$element );
$anrfcBox.append( wrapper );
wrapper = this.document.createElement( 'div' );
this.$( wrapper ).addClass( 'anrfc-box-margins' );
this.$( wrapper ).append( messageInput.$element );
this.$( wrapper ).append( this.$( submitButton.$element ).addClass( 'anrfc-box-margins' ) );
this.$( wrapper ).append( this.$( cancelButton.$element ).addClass( 'anrfc-box-margins' ) );
$anrfcBox.append( wrapper );
submitButton.on( 'click', () => {
this.onSubmit( dropDown, messageInput, keyId );
} );
cancelButton.on( 'click', function () {
this.document.getElementById( keyId ).remove();
} );
return $anrfcBox;
}
/**
* @param {OO.ui.DropdownWidget} dropDown The discussion section the user selected.
* @param {OO.ui.MultilineTextInputWidget} messageInput The message the user typed.
* @param {string} keyId The section number (starting at zero), concatenated with -anrfcBox. Example: 0-anrfcBox. This will eventually be used to do $('#0-anrfcBox'), which is the HTML created by addForm()
*/
async onSubmit( dropDown, messageInput, keyId ) {
// Dropdown is required.
if ( dropDown.getMenu().findSelectedItem() === null ) {
return OO.ui.alert( 'Please select discussion section from dropdown menu!' ).then( () => {
dropDown.focus();
} );
}
// Grab what the user typed into the form.
// For the targetSection dropdown list, the values are 0, 1, 2, etc.
const targetSection = dropDown.getMenu().findSelectedItem().getData();
const message = messageInput.getValue();
// Grab page title
const pageName = this.mw.config.get( 'wgPageName' ).replaceAll( '_', ' ' );
// Grab section title
const sectionTitle = this.$( '#' + keyId ).prev().find( 'h2, h3, h4, h5, h6' ).text();
if ( !sectionTitle ) {
return OO.ui.alert( 'Unable to find the section heading name. This is a bug. Please report the bug at User talk:Novem Linguae/Scripts/anrfc-lister.js. Aborting.' );
}
// Grab RFC date by looking for user signature timestamps
const initDateMatches = this.getRFCDate( keyId );
if ( !initDateMatches ) {
return OO.ui.alert( 'Unable to find a signature in this section. Unsure what date this RFC occurred. Aborting.' );
}
const initiatedDate = initDateMatches[ 0 ];
// Get ready to write some WP:ANRFC wikicode
const heading = '=== [[' + pageName + '#' + sectionTitle + ']] ===';
const initiatedTemplate = '{{initiated|' + initiatedDate + '|done=no}}';
const wikitextToWrite = heading + '\n' + initiatedTemplate + ' ' + message + ' ~~~~';
const api = new this.mw.Api();
let result = await api.get( {
action: 'parse',
page: 'Wikipedia:Closure_requests',
prop: 'wikitext'
} );
let wikitext = result.parse.wikitext[ '*' ];
if ( wikitext.replaceAll( ' ', '_' ).match( ( pageName + '#' + sectionTitle ).replaceAll( ' ', '_' ) ) !== null ) {
return OO.ui.alert( 'This discussion is already listed.' );
}
wikitext = this.makeWikitext( wikitext, wikitextToWrite, initiatedDate, targetSection );
result = await api.postWithEditToken( {
action: 'edit',
title: 'Wikipedia:Closure_requests',
text: wikitext,
summary: '/* ' + this.sections[ targetSection ] + ' */ Listing [[' + pageName + '#' + sectionTitle + ']] using [[User:Novem Linguae/Scripts/anrfc-lister.js|anrfc-lister]]',
nocreate: true
} );
if ( result && result.edit && result.edit.result && result.edit.result === 'Success' ) {
const confirmed = await OO.ui.confirm( 'This discussion has been listed on WP:ANRFC. Would you like to see it?' );
if ( confirmed ) {
let sectionPartOfUri = pageName + '#' + sectionTitle;
sectionPartOfUri = sectionPartOfUri.replaceAll( ' ', '_' );
sectionPartOfUri = encodeURI( sectionPartOfUri );
window.open( '/wiki/Wikipedia:Closure_requests#' + sectionPartOfUri, '_blank' );
}
}
}
dateToObj( dateString ) {
const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
const oDate = dateString.split( /, | / );
oDate[ 0 ] = oDate[ 0 ].match( /[\d]{1,2}:[\d]{1,2}/ )[ 0 ];
const time = {
hh: oDate[ 0 ].match( /([\d]{1,2}):/ )[ 1 ],
mm: oDate[ 0 ].match( /:([\d]{1,2})/ )[ 1 ]
};
return {
time: time,
day: parseInt( oDate[ 1 ] ),
month: months.indexOf( oDate[ 2 ] ),
year: parseInt( oDate[ 3 ] )
};
}
getRFCDate( keyId ) {
// Grab initiated date (the first signature in the section will have the initiated date)
// Looks for a standard signature: 03:31, 11 January 2024 (UTC)
const dateRegex = /([\d]{1,2}:[\d]{1,2},\s[\d]{1,2}\s[\w]+\s[\d]{4}\s\([\w]+\))/;
// Looks for a MediaWiki:Gadget-CommentsInLocalTime.js signature: 10:55 am, 29 November 2016, Tuesday (7 years, 1 month, 13 days ago) (UTC−8)
const dateRegexForCommentsInLocalTimeGadget = /([\d]{1,2}:[\d]{1,2}(?: am| pm)?,\s[\d]{1,2}\s[\w]+\s[\d]{4}.*?\(UTC[^)]+\))/;
let initDateMatches = null;
let textToCheck = '';
let $nextEl = this.$( '#' + keyId ); // #0-anrfcBox
// TODO: Only check elements between anrfcBox and the next H2 (or end of page). Right now it checks the entire page until it runs out of .next() elements.
do {
if ( $nextEl.next().hasClass( 'boilerplate' ) ) {
$nextEl = $nextEl.next().children( 'p' );
} else {
$nextEl = $nextEl.next();
}
textToCheck = $nextEl.text();
initDateMatches = textToCheck.match( dateRegex );
if ( !initDateMatches ) {
// Maybe the user has MediaWiki:Gadget-CommentsInLocalTime.js installed, which changes the format of signature dates. Try the other regex.
initDateMatches = textToCheck.match( dateRegexForCommentsInLocalTimeGadget );
if ( initDateMatches ) {
initDateMatches[ 0 ] = this.convertUtcWhateverToUtcZero( initDateMatches[ 0 ] );
}
}
if ( !$nextEl.length ) {
// We're out of siblings to check at this level. Try the parent's siblings.
$nextEl = $nextEl.prevObject.parent().next();
}
} while ( !initDateMatches && $nextEl.length );
return initDateMatches;
}
/**
* Convert MediaWiki:Gadget-CommentsInLocalTime.js date strings to regular date strings
*
* @param {string} dateString 10:55 am, 29 November 2016, Tuesday (7 years, 1 month, 13 days ago) (UTC−8)
* @return {string} 18:55, 29 November 2016
*/
convertUtcWhateverToUtcZero( dateString ) {
const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
// chop out unnecessary info in the middle of the string
const dateStringShort = dateString.replace( /(\d{4}),.+( \(UTC)/, '$1$2' ); // 10:55 am, 29 November 2016 (UTC−8)
const unixTimestampWithMilliseconds = Date.parse( dateStringShort ); // 1480445700000
const date = new Date( unixTimestampWithMilliseconds );
const dateStringConverted = date.getUTCHours() + ':' +
date.getUTCMinutes() + ', ' +
date.getUTCDate() + ' ' +
months[ date.getUTCMonth() ] + ' ' +
date.getUTCFullYear();
return dateStringConverted; // 18:55, 29 November 2016
}
isInitDateLatest( matchDate, initDate ) {
if ( initDate.year > matchDate.year ) {
return true;
} else if ( initDate.year < matchDate.year ) {
return false;
} else if ( initDate.month > matchDate.month ) {
return true;
} else if ( initDate.month < matchDate.month ) {
return false;
} else if ( initDate.day > matchDate.day ) {
return true;
} else if ( initDate.day < matchDate.day ) {
return false;
} else if ( initDate.time.hh > matchDate.time.hh ) {
return true;
} else if ( initDate.time.hh < matchDate.time.hh ) {
return false;
} else if ( initDate.time.mm > matchDate.time.mm ) {
return true;
} else if ( initDate.time.mm < matchDate.time.mm ) {
return false;
}
return true;
}
stripHtmlFromHeading( headingText ) {
return headingText
.replace( /<!--[\s\S]*?-->/g, '' )
.replace( /<[^>]*>/g, '' )
.replace( /\s+/g, ' ' )
.trim();
}
findDiscussionSectionIndex( wikitext, sectionName, fromIndex = 0 ) {
const headingRegex = /^==\s*(.*?)\s*==\s*$/gm;
headingRegex.lastIndex = fromIndex;
let headingMatch;
while ( ( headingMatch = headingRegex.exec( wikitext ) ) !== null ) {
// Handle headings with anchors, e.g. <span id="anchor1"></span>
if ( this.stripHtmlFromHeading( headingMatch[ 1 ] ) === sectionName ) {
return headingMatch.index;
}
}
return -1;
}
makeWikitext( wikitext, wikitextToWrite, initiatedDate, targetSection ) {
// Make sure we can find the target section. If not, error out.
const targetSectionIndex = this.findDiscussionSectionIndex( wikitext, this.sections[ targetSection ] );
if ( targetSectionIndex === -1 ) {
this.mw.notify( 'Target section not found in wikitext', { type: 'error' } );
throw new Error( 'Target section not found in wikitext' );
}
const firstPart = wikitext.slice( 0, targetSectionIndex );
wikitext = wikitext.slice( targetSectionIndex );
const isLastDiscussion = targetSection === this.sections.length - 1;
const nextSectionIndex = isLastDiscussion ? -1 : this.findDiscussionSectionIndex( wikitext, this.sections[ targetSection + 1 ], 1 );
let relventDiscussion = isLastDiscussion ? wikitext : wikitext.slice( 0, nextSectionIndex );
wikitext = isLastDiscussion ? '' : wikitext.slice( nextSectionIndex );
const initMatches = relventDiscussion.match( /((i|I)nitiated\|[\d]{1,2}:[\d]{1,2},\s[\d]{1,2}\s[\w]+\s[\d]{4}\s\([\w]+\))/g );
const initDateObj = this.dateToObj( initiatedDate );
let matchIndex = ( initMatches !== null ) ? initMatches.length - 1 : -1;
if ( initMatches !== null ) {
for ( ; matchIndex >= 0; matchIndex-- ) {
if ( this.isInitDateLatest( this.dateToObj( initMatches[ matchIndex ] ), initDateObj ) ) {
break;
}
}
}
let left;
if ( matchIndex === -1 ) {
left = relventDiscussion.slice( 0, relventDiscussion.indexOf( '===' ) );
relventDiscussion = relventDiscussion.slice( relventDiscussion.indexOf( '===' ) );
relventDiscussion = left + wikitextToWrite + '\n\n' + relventDiscussion;
} else {
const afterDate = initMatches[ matchIndex ];
left = relventDiscussion.slice( 0, relventDiscussion.indexOf( afterDate ) );
relventDiscussion = relventDiscussion.slice( relventDiscussion.indexOf( afterDate ) );
left = left + relventDiscussion.slice( 0, relventDiscussion.indexOf( '===' ) );
relventDiscussion = relventDiscussion.slice( relventDiscussion.indexOf( '===' ) );
relventDiscussion = left + wikitextToWrite + '\n\n' + relventDiscussion;
}
return ( firstPart + relventDiscussion + wikitext );
}
}
$( async () => {
await mw.loader.using( [ 'oojs-ui-widgets', 'oojs-ui-windows', 'mediawiki.util', 'mediawiki.api' ], async () => {
await ( new ANRFC( document, mw, $ ) ).execute();
} );
} );
// </nowiki>