forked from enterprisey/reply-link
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreply-link.js
2155 lines (1888 loc) · 96.6 KB
/
reply-link.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// vim: ts=4 sw=4 et
//<nowiki>
function loadReplyLink( $, mw ) {
var TIMESTAMP_REGEX = /\(UTC(?:(?:−|\+)\d+?(?:\.\d+)?)?\)\S*?\s*$/m;
var EDIT_REQ_REGEX = /^((Semi|Template|Extended-confirmed)-p|P)rotected edit request on \d\d? \w+ \d{4}/;
var EDIT_REQ_TPL_REGEX = /\{\{edit (template|fully|extended|semi)-protected\s*(\|.+?)*\}\}/;
var LITERAL_SIGNATURE = "~~" + "~~"; // split up because it might get processed
var ADVERT = " (using [[w:en:User:Enterprisey/reply-link|reply-link]])";
var PARSOID_ENDPOINT = "https:" + mw.config.get( "wgServer" ) + "/api/rest_v1/page/html/";
var HEADER_SELECTOR = "h1,h2,h3,h4,h5,h6";
// T:TDYK, used at the end of loadReplyLink
var TTDYK = "Template:Did_you_know_nominations";
var RFA_PG = "Wikipedia:Requests_for_adminship/";
// Threshold for indentation when we offer to outdent
var OUTDENT_THRESH = 8;
// All of the interface message keys that we explicitly load
var INT_MSG_KEYS = [ "mycontris" ];
// Date format regexes in signatures (i.e. the "default date format")
var DATE_FMT_RGX = {
"//en.wikipedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
"//pt.wikipedia.org": /\d\dh\d\dmin\sde \d{1,2} de \w+? de \d{4}/.source
}
// Shared API object
var api;
/*
* Regex *sources* for a "userspace" link. Basically the
* localized equivalent of User( talk)?|Special:Contributions/
* Initialized in buildUserspcLinkRgx, which is called near the top
* of the closure in handleWrapperClick.
*
* Three subproperties: und for underscores instead of spaces (e.g.
* "User_talk"), spc for spaces (e.g. "User talk"), and both for
* a regex combining the two (used for matching on wikitext).
*/
var userspcLinkRgx = null;
/**
* This dictionary is some global state that holds three pieces of
* information for each "(reply)" link (keyed by their unique IDs):
*
* - the indentation string for the comment (e.g. ":*::")
* - the header tuple for the parent section, in the form of
* [level, text, number], where:
* - level is 1 for a h1, 2 for a h2, etc
* - text is the text between the equal signs
* - number is the zero-based index of the heading from the top
* - sigIdx, or the zero-based index of the signature from the top
* of the section
*
* This dictionary is populated in attachLinks, and unpacked in the
* click handler for the links (defined in attachLinkAfterNode); the
* values are then passed to doReply.
*/
var metadata = {};
/**
* This global string flag is:
*
* - "AfD" if the current page is an AfD page
* - "MfD" if the current page is an MfD page
* - "TfD" if the current page is a TfD log page
* - "CfD" if the current page is a CfD log page
* - "FfD" if the current page is a FfD log page
* - "" otherwise
*
* This flag is initialized in onReady and used in attachLinkAfterNode
*/
var xfdType;
/**
* The current page name, including namespace, because we may be reading it
* a lot (especially in findUsernameInElem if we're on someone's user
* talk page)
*/
var currentPageName;
/**
* A map for signatures that contain redirects, so that they can still
* pass the sanity check. This will be updated manually, because I
* don't want the overhead of a whole 'nother API call in the middle
* of the reply process. If this map grows too much, though, I'll
* consider switching to either a toolforge-hosted API or the
* Wikipedia API. Used in doReply, for the username sanity check.
*/
var sigRedirectMapping = {
"Salvidrim": "Salvidrim!"
};
/**
* When the reply is saved via API, this flag is set to true to
* disable the onbeforeunload handler.
*/
var replyWasSaved = false;
/**
* Cache for getWikitext. Only useful in test mode.
*/
var getWikitextCache = {};
/**
* Get the formatted namespace name for a namespace ID.
* Quick ref: user = 2, proj = 4
*/
function fmtNs( nsId ) {
return mw.config.get( "wgFormattedNamespaces" )[ nsId ];
}
/**
* Escapes a string for inclusion in a regex.
*/
function escapeForRegex( s ) {
return s.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
}
/*
* MediaWiki turns spaces before certain punctuation marks
* into non-breaking spaces, so fix those. This is done by
* the armorFrenchSpaces function in Mediawiki, in the file
* /includes/parser/Sanitizer.php
*/
function deArmorFrenchSpaces( text ) {
return text.replace( /\xA0([?:;!%»›])/g, " $1" );
}
/**
* Capitalize the first letter of a string.
*/
function capFirstLetter( someString ) {
return someString.charAt( 0 ).toUpperCase() + someString.slice( 1 );
}
/**
* Namespace name ("Template") to ID (10).
*/
function nsNameToId( nsName ) {
return mw.config.get( "wgNamespaceIds" )[ nsName.toLowerCase().replace( / /g, "_" ) ];
}
/**
* Canonical-ize a namespace.
*/
function canonicalizeNs( ns ) {
return fmtNs( nsNameToId( ns ) );
}
/**
* This function converts any (index-able) iterable into a list.
*/
function iterableToList( nl ) {
var len = nl.length;
var arr = new Array( len );
for( var i = 0; i < len; i++ ) arr[i] = nl[i];
return arr;
}
/**
* Decode HTML entities. Used in the signature sanity check.
* Source: https://stackoverflow.com/a/1912522/1757964
*/
function htmlDecode( html ) {
var el = document.createElement( "span" );
el.innerHTML = html;
return el.childNodes[0].nodeValue;
}
/**
* Process HTML character entities.
* From https://stackoverflow.com/a/46851765
*/
function processCharEntities( text ) {
var el = document.createElement('div');
return text.replace( /\&[#0-9a-z]+;/gi, function ( enc ) {
el.innerHTML = enc;
return el.innerText
} );
}
/**
* When there's a panel being shown, this function sets the status
* in the panel to the first argument. The callback function is
* optional.
*/
function setStatus ( status, callback ) {
var statusElement = $( "#reply-dialog-status" );
statusElement.fadeOut( function () {
statusElement.html( status ).fadeIn( callback );
} );
}
/**
* Sets the panel status when an error happened. Good for use in
* catch blocks.
*/
function setStatusError( e ) {
console.error(e);
setStatus( "There was an error while replying! Please leave a note at " +
"<a href='https://en.wikipedia.org/wiki/User_talk:Enterprisey/reply-link'>the script's talk page</a>" +
" with any errors in <a href='https://en.wikipedia.org/wiki/WP:JSERROR'>the browser console</a>, if possible." );
if( e.message ) {
console.log( "Content request error: " + JSON.stringify( e.message ) );
}
console.log( "DEBUG INFORMATION: '"+currentPageName+"' @ " +
mw.config.get( "wgCurRevisionId" ),"parsoid",PARSOID_ENDPOINT+
encodeURIComponent(currentPageName).replace(/'/g,"%27")+"/"+mw.config.get("wgCurRevisionId") );
throw e;
}
/**
* Given some wikitext, processes it to get just the text content.
* This function should be identical to the MediaWiki function
* that gets the wikitext between the equal signs and comes up
* with the id's that anchor the headers.
*/
function wikitextToTextContent( wikitext ) {
return decodeURIComponent( processCharEntities( wikitext ) )
.replace( /\[\[:?(?:[^\|\]]+?\|)?([^\]\|]+?)\]\]/g, "$1" )
.replace( /\{\{\s*tl\s*\|\s*(.+?)\s*\}\}/g, "{{$1}}" )
.replace( /\{\{\s*[Uu]\s*\|\s*(.+?)\s*\}\}/g, "$1" )
.replace( /('''?)(.+?)\1/g, "$2" )
.replace( /<s>(.+?)<\/s>/g, "$1" )
.replace( /<span.*?>(.*?)<\/span>/g, "$1" );
}
/**
* Finds and returns the div that is the immediate parent of the
* first talk page header on the page, so that we can read all the
* sections by iterating through its child nodes.
*/
function findMainContentEl() {
// Which header are we looking for?
var targetHeader = "h2";
if( xfdType || currentPageName.startsWith( RFA_PG ) ) targetHeader = "h3";
if( currentPageName.startsWith( TTDYK ) ) targetHeader = "h4";
// The element itself will be the text span in the h2; its
// parent will be the h2; and the parent of the h2 is the
// content container that we want
var candidates = document.querySelectorAll( targetHeader + " > span.mw-headline" );
if( !candidates.length ) return null;
var candidate = candidates[candidates.length-1].parentElement.parentElement;
// Compatibility with User:Enterprisey/hover-edit-section
// That script puts each section in its own div, so we need to
// go out another level if it's running
if( candidate.className === "hover-edit-section" ) {
return candidate.parentElement;
} else {
return candidate;
}
}
/**
* Gets the wikitext of a page with the given title (namespace required).
* Returns an object with keys "content" and "timestamp".
*/
function getWikitext( title, useCaching ) {
if( useCaching === undefined ) useCaching = false;
if( useCaching && getWikitextCache[ title ] ) {
return $.when( getWikitextCache[ title ] );
}
return $.getJSON(
mw.util.wikiScript( "api" ),
{
format: "json",
action: "query",
prop: "revisions",
rvprop: "content",
rvslots: "main",
rvlimit: 1,
titles: title
}
).then( function ( data ) {
var pageId = Object.keys( data.query.pages )[0];
if( data.query.pages[pageId].revisions ) {
var revObj = data.query.pages[pageId].revisions[0];
var result = { timestamp: revObj.timestamp, content: revObj.slots.main["*"] };
getWikitextCache[ title ] = result;
return result;
}
return {};
} );
}
/**
* Creates userspcLinkRgx. Called in handleWrapperClick and the test
* runner at the bottom.
*/
function buildUserspcLinkRgx() {
var nsIdMap = mw.config.get( "wgNamespaceIds" );
var nsRgxFragments = [];
var contribsSecondFrag = ":" + escapeForRegex( mw.messages.get( "mycontris" ) ) + "\\/";
for( var nsName in nsIdMap ) {
if( !nsIdMap.hasOwnProperty( nsName ) ) continue;
switch( nsIdMap[nsName] ) {
case 2:
case 3:
nsRgxFragments.push( escapeForRegex( capFirstLetter( nsName ) ) + "\\s*:" );
break;
case -1:
nsRgxFragments.push( escapeForRegex( capFirstLetter( nsName ) ) + contribsSecondFrag );
break;
}
}
userspcLinkRgx = {};
userspcLinkRgx.spc = "(?:" + nsRgxFragments.join( "|" ).replace( /_/g, " " ) + ")";
userspcLinkRgx.und = userspcLinkRgx.spc.replace( / /g, "_" );
userspcLinkRgx.both = "(?:" + userspcLinkRgx.spc + "|" + userspcLinkRgx.und + ")";
}
/**
* Is there a signature (four tildes) present in the given text,
* outside of a nowiki element?
*/
function hasSig( text ) {
// no literal signature?
if( text.indexOf( LITERAL_SIGNATURE ) < 0 ) return false;
// if there's a literal signature and no nowiki elements,
// there must be a real signature
if( text.indexOf( "<nowiki>" ) < 0 ) return true;
// Save all nowiki spans
var nowikiSpanStarts = []; // list of ignored span beginnings
var nowikiSpanLengths = []; // list of ignored span lengths
var NOWIKI_RE = /<nowiki>.*?<\/nowiki>/g;
var spanMatch;
do {
spanMatch = NOWIKI_RE.exec( text );
if( spanMatch ) {
nowikiSpanStarts.push( spanMatch.index );
nowikiSpanLengths.push( spanMatch[0].length );
}
} while( spanMatch );
// So that we don't check every ignore span every time
var nowikiSpanStartIdx = 0;
var LIT_SIG_RE = new RegExp( LITERAL_SIGNATURE, "g" );
var sigMatch;
matchLoop:
do {
sigMatch = LIT_SIG_RE.exec( text );
if( sigMatch ) {
// Check that we're not inside a nowiki
for( var nwIdx = nowikiSpanStartIdx; nwIdx <
nowikiSpanStarts.length; nwIdx++ ) {
if( sigMatch.index > nowikiSpanStarts[nwIdx] ) {
if ( sigMatch.index + sigMatch[0].length <=
nowikiSpanStarts[nwIdx] + nowikiSpanLengths[nwIdx] ) {
// Invalid sig
continue matchLoop;
} else {
// We'll never encounter this span again, since
// headers only get later and later in the wikitext
nowikiSpanStartIdx = nwIdx;
}
}
}
// We aren't inside a nowiki
return true;
}
} while( sigMatch );
return false;
}
/**
* Given an Element object, attempt to recover a username from it.
* Also will check up to two elements prior to the passed element.
* Returns null if no username was found. Otherwise, returns an
* object with these properties:
*
* - username: The username that we found.
* - link: The DOM object for the link from which we got the
* username.
*/
function findUsernameInElem( el ) {
if( !el ) return null;
var links;
for( let i = 0; i < 3; i++ ) {
if( el === null ) break;
links = el.tagName.toLowerCase() === "a" ? [ el ]
: el.querySelectorAll( "a" );
//console.log(i,"top of outer for in findUsernameInElem ",el, " links -> ",links);
// Compatibility with "Comments in Local Time"
if( el.className.indexOf( "localcomments" ) >= 0 ) i--;
// If we couldn't get any links, try again with prev elem
if( !links ) continue;
var link; // his name isn't zelda
for( var j = 0; j < links.length; j++ ) {
link = links[j];
//console.log(link,decodeURIComponent(link.getAttribute("href")));
if( link.className.indexOf( "mw-selflink" ) >= 0 ) {
return { username: currentPageName.replace( /.+:/, "" )
.replace( /_/g, " " ), link: link };
}
// Also matches redlinks. Why people have redlinks in their sigs on
// purpose, I may never know.
//console.log( "^\\/(?:wiki\\/" + userspcLinkRgx.und + /(.+?)(?:\/.+?)?(?:#.+)?|w\/index\.php\?title=User(?:_talk)?:(.+?)&action=edit&redlink=1/.source + ")$" )
var sigLinkRe = new RegExp( "^\\/(?:wiki\\/" + userspcLinkRgx.und + /(.+?)(?:\/.+?)?(?:#.+)?|w\/index\.php\?title=/.source + userspcLinkRgx.und + /(.+?)&action=edit&redlink=1/.source + ")$" );
var usernameMatch = sigLinkRe.exec( decodeURIComponent( link.getAttribute( "href" ) ) );
if( usernameMatch ) {
//console.log("usernameMatch",usernameMatch)
var rawUsername = usernameMatch[1] ? usernameMatch[1] : usernameMatch[2];
return {
username: decodeURIComponent( rawUsername ).replace( /_/g, " " ),
link: link
};
}
}
// Go backwards one element and try again
el = el.previousElementSibling;
}
return null;
}
/**
* Given a reply-link-wrapper span, attempts to find who wrote
* the comment that precedes it. For information about the return
* value, see the documentation for findUsernameInElem.
*/
function getCommentAuthor( wrapper ) {
var sigNode = wrapper.previousSibling;
//console.log(sigNode,sigNode.style,sigNode.style ? sigNode.style.getPropertyValue("size"):"");
var smallOrFake = sigNode.nodeType === 1 &&
( sigNode.tagName.toLowerCase() === "small" ||
( sigNode.tagName.toLowerCase() === "span" &&
sigNode.style && sigNode.style.getPropertyValue( "font-size" ) === "85%" ) );
var possUserLinkElem = ( smallOrFake && sigNode.children.length > 1 )
? sigNode.children[sigNode.children.length-1]
: sigNode.previousElementSibling;
return findUsernameInElem( possUserLinkElem );
}
/**
* Given the wikitext of a section, attempt to find the first edit
* request template in it, and then mark that template as answered.
* Returns the modified section wikitext.
*/
function markEditReqAnswered( sectionWikitext ) {
var editReqMatch = EDIT_REQ_TPL_REGEX.exec( sectionWikitext );
if( !editReqMatch ) {
console.error( "Couldn't find an edit request!" );
return sectionWikitext;
}
var ansParamMatch = /ans(wered)?=.*?(\||\}\})/.exec( editReqMatch[0] );
if( !ansParamMatch ) {
sectionWikitext = sectionWikitext.replace(
editReqMatch[0],
editReqMatch[0].replace( "}}", "answered=yes}}" )
);
} else {
var newEditReqTpl = editReqMatch[0].replace( ansParamMatch[0],
"answered=yes" + ansParamMatch[2] );
sectionWikitext = sectionWikitext.replace(
editReqMatch[0],
newEditReqTpl
);
}
return sectionWikitext;
}
/**
* Ascend until dd or li, or a p directly under div.mw-parser-output.
* live is true if we're on the live DOM (and thus we have our own UI
* elements to deal with) and false if we're on the psd DOM.
*/
function ascendToCommentContainer( startNode, live, recordPath ) {
var currNode = startNode;
if( recordPath === undefined ) recordPath = false;
var path = [];
var lcTag;
function isActualContainer( node, nodeLcTag ) {
if( nodeLcTag === undefined ) nodeLcTag = node.tagName.toLowerCase();
return /dd|li/.test( nodeLcTag ) ||
( ( nodeLcTag === "p" || nodeLcTag === "div" ) &&
( node.parentNode.className === "mw-parser-output" ||
node.parentNode.className === "hover-edit-section" ||
( node.parentNode.tagName.toLowerCase() === "section" &&
node.parentNode.dataset.mwSectionId ) ) );
}
var smallContainerNodeLimit = live ? 3 : 1;
do {
currNode = currNode.parentNode;
lcTag = currNode.tagName.toLowerCase();
if( lcTag === "html" ) {
console.error( "ascendToCommentContainer reached root" );
break;
}
if( recordPath ) path.unshift( currNode );
//console.log( "checking isActualContainer for ", currNode, isActualContainer( currNode, lcTag ),
// lcTag === "small", isActualContainer( currNode.parentNode ),
// currNode.parentNode.childNodes,
// currNode.parentNode.childNodes.length );
} while( !isActualContainer( currNode, lcTag ) &&
!( lcTag === "small" && isActualContainer( currNode.parentNode ) &&
currNode.parentNode.childNodes.length <= smallContainerNodeLimit ) );
//console.log("ascendToCommentContainer from ",startNode," terminating, r.v. ",recordPath?path:currNode);
return recordPath ? path : currNode;
}
/**
* Given a Parsoid DOM and a link in the live DOM that is the link at the
* end of a signature, return the corresponding element in the Parsoid DOM
* that represents the same comment.
*
* psd = Parsoid, live = in the current, live page DOM.
*/
function getCorrCmt( psdDom, sigLinkElem ) {
// First, define some helper functions
// Does this node have a timestamp in it?
function hasTimestamp( node ) {
//console.log ("hasTimestamp ",node, node.nodeType === 3,node.textContent.trim(),
// TIMESTAMP_REGEX.test( node.textContent.trim() ),
// node.childNodes.length === 1,
// node.childNodes.length && TIMESTAMP_REGEX.test( node.childNodes[0].textContent.trim()),
// " => ",( node.nodeType === 3 &&
// TIMESTAMP_REGEX.test( node.textContent.trim() ) ) ||
// ( node.childNodes.length === 1 &&
// TIMESTAMP_REGEX.test( node.childNodes[0].textContent.trim() ) ) );
//console.log(node,node.textContent.trim(),TIMESTAMP_REGEX.test(node.textContent.trim()));
var validTag = node.nodeType === 3 || ( node.nodeType === 1 &&
( node.tagName.toLowerCase() === "small" ||
node.tagName.toLowerCase() === "span" ) );
return ( validTag && TIMESTAMP_REGEX.test( node.textContent.trim() ) ||
( node.childNodes.length === 1 &&
TIMESTAMP_REGEX.test( node.childNodes[0].textContent.trim() ) ) );
}
// Get prefix that's the actual comment
function getPrefixComment( theNodes ) {
var prefix = [];
for( var j = 0; j < theNodes.length; j++ ) {
prefix.push( theNodes[j] );
if( hasTimestamp( theNodes[j] ) ) break;
}
return prefix;
}
/**
* From a "container elem" (like the whole dd, li, or p that has a
* comment), get the prefix that ends in a timestamp (because other
* comments might be after the timestamp), and return the text content.
*/
function surrTextContentFromElem( elem ) {
var surrListElemNodes = elem.childNodes;
// nodeType 8 is for comments
return getPrefixComment( surrListElemNodes )
.map( function ( c ) { return ( c.nodeType !== 8 ) ? c.textContent : ""; } )
.join( "" ).trim();
}
/** From a "container elem" (dd, li, or p), remove all but the first comment. */
function onlyFirstComment( container ) {
//console.log("onlyFirstComment top container and container.childNodes",container,container.childNodes);
if( container.childNodes.length === 1 && container.children[0].tagName.toLowerCase() === "small" ) {
console.log( "[onlyFirstComment] container only had a small in it" );
container = container.children[0];
}
var i, autosignedIdx, autosigned = container.querySelector( "small.autosigned" );
if( autosigned && ( autosignedIdx = iterableToList(
container.childNodes ).indexOf( autosigned ) ) >= 0 ) {
i = autosignedIdx;
} else {
var childNodes = container.childNodes;
for( i = 0; i < childNodes.length; i++ ) {
if( hasTimestamp( childNodes[i] ) ) {
//console.log( "[oFC] found a timestamp in ",childNodes[i]);
break;
}
}
if( i === childNodes.length ) {
throw new Error( "[onlyFirstComment] No timestamp found" );
}
}
//console.log("[onlyFirstComment] killing all after ",i,container.childNodes[i]);
i++;
var elemToRemove;
while( elemToRemove = container.childNodes[i] ) {
container.removeChild( elemToRemove );
}
}
// End helper functions, begin actual code
// We dump this object for debugging in the event of an error
var corrCmtDebug = {};
// Convert live href to psd href
var newHref, liveHref = decodeURIComponent( sigLinkElem.getAttribute( "href" ) );
corrCmtDebug.liveHref = liveHref;
if( sigLinkElem.className.indexOf( "mw-selflink" ) >= 0 ) {
newHref = "./" + currentPageName;
} else {
if( /^\/wiki/.test( liveHref ) ) {
var hrefTokens = liveHref.split( ":" );
if( hrefTokens.length !== 2 ) throw new Error( "Malformed href" );
newHref = "./" + canonicalizeNs( hrefTokens[0].replace(
/^\/wiki\//, "" ) ).replace( / /g, "_" ) + ":" +
encodeURIComponent( hrefTokens[1] )
.replace( /^Contributions%2F/, "Contributions/" )
.replace( /%2F/g, "/" )
.replace( /%23/g, "#" )
.replace( /%26/g, "&" )
.replace( /%3D/g, "=" )
.replace( /%2C/g, "," );
} else {
var REDLINK_HREF_RGX = /^\/w\/index\.php\?title=(.+?)&action=edit&redlink=1$/;
newHref = "./" + REDLINK_HREF_RGX.exec( liveHref )[1];
}
}
var livePath = ascendToCommentContainer( sigLinkElem, /* live */ true, /* recordPath */ true );
corrCmtDebug.newHref = newHref; corrCmtDebug.livePath = livePath;
// Deal with the case where the comment has multiple links to
// sigLinkElem's href; we will store the index of the link we want.
// null means there aren't multiple links.
var liveDupeLinks = livePath[0].querySelectorAll( "a" +
( liveHref ? ( "[href='" + liveHref + "']" ) : ".mw-selflink" ) );
if( !liveDupeLinks ) throw new Error( "Couldn't select live dupe link" );
var liveDupeLinkIdx = ( liveDupeLinks.length > 1 )
? iterableToList( liveDupeLinks ).indexOf( sigLinkElem ) : null;
//console.log("liveDupeLinkIdx",liveDupeLinkIdx);
//console.log("livePath[0]",livePath[0],livePath[0].childNodes);
var liveClone = livePath[0].cloneNode( /* deep */ true );
// Remove our own UI elements
var ourUiSelector = ".reply-link-wrapper,#reply-link-panel";
iterableToList( liveClone.querySelectorAll( ourUiSelector ) ).forEach( function ( n ) {
n.parentNode.removeChild( n );
} );
//console.log("(BEFORE) liveClone",liveClone,liveClone.childNodes);
onlyFirstComment( liveClone );
//console.log("(AFTER) liveClone",liveClone,liveClone.childNodes);
// Process it a bit to make it look a bit more like the Parsoid output
var liveAutoNumberedLinks = liveClone.querySelectorAll( "a.external.autonumber" );
for( var i = 0; i < liveAutoNumberedLinks.length; i++ ) {
liveAutoNumberedLinks[i].textContent = "";
}
var liveSelflinks = liveClone.querySelectorAll( "a.mw-selflink.selflink" );
for( var i = 0; i < liveSelflinks.length; i++ ) {
liveSelflinks[i].href = "/wiki/" + currentPageName;
}
// "Comments in Local Time" compatibility: the text content is
// gonna contain the modified time stamp, but the original time
// stamp is still there
var localCommentsSpan = liveClone.querySelector( "span.localcomments" );
if( localCommentsSpan ) {
var dateNode = document.createTextNode( localCommentsSpan.getAttribute( "title" ) );
localCommentsSpan.parentNode.replaceChild( dateNode, localCommentsSpan );
}
// TODO: Optimization - surrTextContentFromElem does the prefixing
// operation a second time, even though we already called onlyFirstComment
// on it.
var liveTextContent = surrTextContentFromElem( liveClone );
console.log("liveTextContent >>>>>"+liveTextContent + "<<<<<");
function normalizeTextContent( tc ) {
return deArmorFrenchSpaces( tc );
}
liveTextContent = normalizeTextContent( liveTextContent );
var selector = livePath.map( function ( node ) {
return node.tagName.toLowerCase();
} ).join( " " ) + " a[href^='" + newHref + "']";
// TODO: Optimization opportunity - run querySelectorAll only on the
// section that we know contains the comment
var psdLinks = iterableToList( psdDom.querySelectorAll( selector ) );
console.log("(",liveDupeLinkIdx, ")",selector, " --> ", psdLinks);
var oldPsdLinks = psdLinks,
newHrefLen = newHref.length,
hrefSubstr;
psdLinks = [];
for( var i = 0; i < oldPsdLinks.length; i++ ) {
hrefSubstr = oldPsdLinks[i].getAttribute( "href" ).substring( newHrefLen );
if( !hrefSubstr || hrefSubstr.indexOf( "#" ) === 0 ) {
psdLinks.push( oldPsdLinks[i] );
}
}
// Narrow down by entire textContent of list element
var psdCorrLinks = []; // the corresponding link elem(s)
if( liveDupeLinkIdx === null ) {
for( var i = 0; i < psdLinks.length; i++ ) {
var psdContainer = ascendToCommentContainer( psdLinks[i], /* live */ false, true );
//console.log("psdContainer",psdContainer);
var psdTextContent = normalizeTextContent( surrTextContentFromElem( psdContainer[0] ) );
//console.log(i,">>>"+psdTextContent+"<<<");
if( psdTextContent === liveTextContent ) {
psdCorrLinks.push( psdLinks[i] );
} /* else {
//console.log(i,"len: psd live",psdTextContent.length,liveTextContent.length);
for(var j = 0; j < Math.min(psdTextContent.length, liveTextContent.length); j++) {
if(psdTextContent.charAt(j)!==liveTextContent.charAt(j)) {
//console.log(i,j,"psd live", psdTextContent.codePointAt(j), liveTextContent.codePointAt( j ) );
break;
}
}
} */
}
} else {
for( var i = 0; i < psdLinks.length; i++ ) {
var psdContainer = ascendToCommentContainer( psdLinks[i], /* live */ false );
if( psdContainer.dataset.replyLinkGeCorrCo ) continue;
var psdTextContent = normalizeTextContent( surrTextContentFromElem( psdContainer ) );
console.log(i,">>>"+psdTextContent+"<<<");
if( psdTextContent === liveTextContent ) {
var psdDupeLinks = psdContainer.querySelectorAll( "a[href='" + newHref + "']" );
psdCorrLinks.push( psdDupeLinks[ liveDupeLinkIdx ] );
}
// Flag to ensure we don't take a link from this container again
psdContainer.dataset.replyLinkGeCorrCo = true;
}
}
if( psdCorrLinks.length === 0 ) {
throw new Error( "Failed to find a matching comment in the Parsoid DOM." );
} else if( psdCorrLinks.length > 1 ) {
throw new Error( "Found multiple matching comments in the Parsoid DOM." );
}
return psdCorrLinks[0];
}
/**
* Given the Parsoid output (GET /page/html endpoint) on the current
* page and a DOM object in the current page corresponding to a
* link in a signature, locate the section containing that
* comment. That section may not be in the current page! Returns an
* object with four properties:
*
* - page: The full title of the page directly containing the
* comment (in its wikitext, not through transclusion).
* - sectionIdx: The anticipated wikitext section index containing
* the comment. That is, our best guess as to what the section
* index (in the wikitext, using ==wikitext headers==) will be,
* ignoring all of the wikitext headers that don't actually
* generate header elements (e.g. those inside nowikis, code
* blocks, etc).
* - sectionName: The anticipated wikitext section name. Should
* appear inside the equal signs at the above index.
* - sectionLevel: The anticipated wikitext section level (e.g.
* 2 for an h2)
*
* Parsoid is abbreviated here as "psd" in variables and comments.
*/
function findSection( psdDomString, sigLinkElem ) {
//console.log(psdDomString);
var domParser = new DOMParser(),
psdDom = domParser.parseFromString( psdDomString, "text/html" );
var corrLink = getCorrCmt( psdDom, sigLinkElem );
//console.log("STEP 1 SUCCESS",corrLink);
var corrCmt = ascendToCommentContainer( corrLink, /* live */ false );
// Ascend until we hit something in a transclusion
var currNode = corrLink;
var tsclnId = null;
do {
if( currNode.getAttribute( "about" ) &&
currNode.getAttribute( "about" ).indexOf( "#mwt" ) === 0 ) {
tsclnId = currNode.getAttribute( "about" );
break;
}
currNode = currNode.parentNode;
} while( currNode.tagName.toLowerCase() !== "html" );
//console.log( "tsclnId", tsclnId );
// Now, get the nearest header above us
function inPseudo( headerElement ) {
var currNodeIP = headerElement;
// This requires Parsoid HTML v 2.0.0
do {
if( currNodeIP.nodeType === 1 && currNodeIP.matches( "section" ) ) {
return currNodeIP.dataset.mwSectionId < 0;
break;
}
currNodeIP = currNodeIP.parentNode;
} while( currNodeIP );
return false;
}
var currNode = corrCmt;
var nearestHeader = null;
var HTML_HEADER_RGX = /^h\d$/;
do {
if( HTML_HEADER_RGX.exec( currNode.tagName.toLowerCase() ) ) {
if( !inPseudo( currNode ) ) {
nearestHeader = currNode;
break;
}
}
var containedHeaders = currNode.querySelectorAll( HEADER_SELECTOR );
if( containedHeaders.length ) {
var nearestHdrIdx = containedHeaders.length - 1;
while( nearestHdrIdx >= 0 && inPseudo( containedHeaders[ nearestHdrIdx ] ) ) {
nearestHdrIdx--;
}
if( nearestHdrIdx >= 0 ) {
nearestHeader = containedHeaders[ nearestHdrIdx ];
break;
}
}
if( currNode.previousElementSibling ) {
currNode = currNode.previousElementSibling;
continue;
}
currNode = currNode.parentNode;
} while( currNode.tagName.toLowerCase() !== "body" );
// Get the target page (page actually containing the comment)
var targetPage;
if( tsclnId !== null ) {
var tsclnInfoSel = "*[about='" + tsclnId + "'][typeof='mw:Transclusion']",
infoJson = JSON.parse( psdDom.querySelector( tsclnInfoSel ) .dataset.mw );
//console.log(infoJson);
for( var i = 0; i < infoJson.parts.length; i++ ) {
if( infoJson.parts[i].template &&
infoJson.parts[i].template.target ) {
var wtTarget =infoJson.parts[i].template.target.wt;
if( wtTarget && ( wtTarget.indexOf( ":" ) >= 0 || wtTarget.indexOf( "/" ) === 0 ) ) {
targetPage = infoJson.parts[i].template.target.wt;
}
}
}
}
if( targetPage && targetPage.charAt( 0 ) === "/" ) {
// Given relative to the current page
targetPage = currentPageName + targetPage;
} else if( !targetPage ) {
if( tsclnId !== null ) tsclnId = null;
targetPage = currentPageName;
}
// Finally, get the index of our nearest header
var allHeaders = iterableToList( psdDom.querySelectorAll( HEADER_SELECTOR ) );
var headerIdx = null, headerAbout;
var tIdx = 0; // "header index for headers inside tsclnId"
// Note that i is incremented at the end of the loop because
// sometimes we want to skip an index, such as when it comes
// from another template
for( var i = 0; i < allHeaders.length; ) {
if( allHeaders[i] === nearestHeader ) {
headerIdx = tIdx;
break;
}
headerAbout = allHeaders[i].getAttribute( "about" );
if( allHeaders[i].hasAttribute( "about" ) ) {
if( headerAbout === tsclnId ) {
tIdx++;
}
i++;
continue;
} else {
var currNode = allHeaders[i];
var container = null, containerAbout = null;
while( currNode.tagName.toLowerCase() !== "body" ) {
if( currNode.hasAttribute( "about" ) ) {
container = currNode;
containerAbout = currNode.getAttribute( "about" );
break;
}
currNode = currNode.parentNode;
}
if( container ) {
function hasDiscussionPage( dataMw ) {
dataMw = JSON.parse( dataMw );
if( dataMw.parts && dataMw.parts.length ) {
return dataMw.parts.some( function ( part ) {
if( part.template && part.template.target && part.template.target.href ) {
var href = part.template.target.href,
nsName = ( href.indexOf( ":" ) < 0 ) ? "" : href.substring( 2, href.indexOf( ":" ) ),
nsId = nsNameToId( nsName );
if( nsId === 10 ) {
return part.template.target.href.indexOf( "./Template:Did you know nominations" ) === 0;
} else {
return nsId % 2 === 1;
}
}
} );
}
return false;
}
// If the container has any other transcluded non-templates inside it,
// we can't use it, so treat this header normally and move on
var innerTransclusions = container.querySelectorAll( "*[typeof='mw:Transclusion']" );
if( innerTransclusions.length ) {
var transcludesNonTemplate = iterableToList(
innerTransclusions ).any( function ( transclusion ) {
return hasDiscussionPage( transclusion.dataset.mw );
} );
if( !transcludesNonTemplate && containerAbout === tsclnId ) {
tIdx++;
}
i++;
continue;
}
var containerHeaders = iterableToList( container.querySelectorAll( HEADER_SELECTOR ) );
if( container.contains( nearestHeader ) ) {
headerIdx = tIdx + containerHeaders.indexOf( nearestHeader );
break;
} else {
if( containerAbout === tsclnId ||
( tsclnId === null && container.dataset.mw && !hasDiscussionPage( container.dataset.mw ) ) ) {
tIdx += containerHeaders.length;
}
i += containerHeaders.length;
continue;
}
} else {
if( tsclnId === null ) {
tIdx++;
}
i++;
continue;
}
}
i++;
}
//console.log("headerIdx ",headerIdx);
var result = {
page: targetPage,
sectionIdx: headerIdx,
sectionName: nearestHeader.textContent,
sectionLevel: nearestHeader.tagName.substring( 1 )
};
return result;
}
/**
* Given some wikitext that's split into sections, return the full
* wikitext (including header and newlines until the next header)
* of the section with the given (zero-based) index. To get the content
* before the first header, sectionIdx should be -1 and sectionName
* should be null.
*
* Performs a sanity check with the given section name.
*/
function getSectionWikitext( wikitext, sectionIdx, sectionName ) {
var HEADER_RE = /^\s*=(=*)\s*(.+?)\s*\1=\s*$/gm;
console.log("In getSectionWikitext, sectionIdx = " + sectionIdx + ", sectionName = >" + sectionName + "<");
//console.log("wikitext (first 1000 chars) is " + dirtyWikitext.substring(0, 1000));
// There are certain locations where a header may appear in the
// wikitext, but will not be present in the HTML; such as code
// blocks or comments. So we keep track of those ranges
// and ignore headings inside those.
var ignoreSpanStarts = []; // list of ignored span beginnings
var ignoreSpanLengths = []; // list of ignored span lengths
var IGNORE_RE = /(<pre>[\s\S]+?<\/pre>)|(<source.+?>[\s\S]+?<\/source>)|(<!--[\s\S]+?-->)/g;
var ignoreSpanMatch;
do {
ignoreSpanMatch = IGNORE_RE.exec( wikitext );
if( ignoreSpanMatch ) {
//console.log("ignoreSpan ",ignoreSpanStarts.length," = ",ignoreSpanMatch);
ignoreSpanStarts.push( ignoreSpanMatch.index );
ignoreSpanLengths.push( ignoreSpanMatch[0].length );
}