/
controller.js
1608 lines (1417 loc) · 49.9 KB
/
controller.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
/**
* A singleton that controls the overall state of the page, initiating boot processes and reacting
* to events.
*
* @module controller
*/
import BootProcess from './BootProcess';
import Comment from './Comment';
import CommentForm from './CommentForm';
import LiveTimestamp from './LiveTimestamp';
import Parser from './Parser';
import Thread from './Thread';
import Worker from './worker-gate';
import addCommentLinks from './addCommentLinks';
import cd from './cd';
import init from './init';
import navPanel from './navPanel';
import notifications from './notifications';
import pageNav from './pageNav';
import postponements from './postponements';
import sessions from './sessions';
import settings from './settings';
import toc from './toc';
import updateChecker from './updateChecker';
import { ElementsTreeWalker } from './treeWalker';
import { brsToNewlines, hideSensitiveCode } from './wikitext';
import {
getExtendedRect,
getLastArrayElementOrSelf,
getVisibilityByRects,
isCmdMofidicatorPressed,
isInline,
isInputFocused,
isProbablyTalkPage,
keyCombination,
skin$,
unhideText,
} from './util';
import { getUserInfo } from './apiWrappers';
/**
* Get the bottom offset of the table of contents.
*
* @returns {number}
* @private
*/
function getTocBottomOffset() {
return toc.$element.offset().top + toc.$element.outerHeight();
}
export default {
state: {},
content: {},
scrollData: { offset: null },
document: document.documentElement,
autoScrolling: false,
isUpdateThreadLinesHandlerAttached: false,
/**
* Assign some properties required by the controller - those which are not known from the
* beginning.
*/
setup() {
// Not constants: go() may run a second time, see addFooterLink().
const isEnabledInQuery = /[?&]cdtalkpage=(1|true|yes|y)(?=&|$)/.test(location.search);
const isDisabledInQuery = /[?&]cdtalkpage=(0|false|no|n)(?=&|$)/.test(location.search);
this.$content = this.$content || $('#mw-content-text');
// See controller.isDefinitelyTalkPage
this.definitelyTalkPage = Boolean(
isEnabledInQuery ||
cd.g.PAGE_WHITELIST_REGEXP?.test(cd.g.PAGE_NAME) ||
$('#ca-addsection').length ||
// .cd-talkPage is used as a last resort way to make CD parse the page, as opposed to using
// the list of supported namespaces and page white/black list in the configuration. With this
// method, there won't be "comment" links for edits on pages that list revisions such as the
// watchlist.
this.$content.find('.cd-talkPage').length
);
// See controller.isArticlePageTalkPage
this.articlePageTalkPage = (
(!mw.config.get('wgIsRedirect') || !this.isCurrentRevision()) &&
!this.$content.find('.cd-notTalkPage').length &&
(isProbablyTalkPage(cd.g.PAGE_NAME, cd.g.NAMESPACE_NUMBER) || this.definitelyTalkPage) &&
// Undocumented setting
!(typeof cdOnlyRunByFooterLink !== 'undefined' && window.cdOnlyRunByFooterLink)
);
// See controller.isDiffPage
this.diffPage = /[?&]diff=[^&]/.test(location.search);
this.talkPage = Boolean(
mw.config.get('wgIsArticle') &&
!isDisabledInQuery &&
(isEnabledInQuery || this.articlePageTalkPage)
);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleWindowResize = this.handleWindowResize.bind(this);
this.handleGlobalKeyDown = this.handleGlobalKeyDown.bind(this);
this.handleScroll = this.handleScroll.bind(this);
this.handlePopState = this.handlePopState.bind(this);
this.handleSelectionChange = this.handleSelectionChange.bind(this);
this.handlePageMutations = this.handlePageMutations.bind(this);
this.handleAddTopicButtonClick = this.handleAddTopicButtonClick.bind(this);
this.handleWikipageContentHookFirings = this.handleWikipageContentHookFirings.bind(this);
},
/**
* Reset the controller data and some page mechanisms (executed at every page reload).
*
* @param {string} htmlToLayOut HTML to update the page with.
*/
reset(htmlToLayOut) {
this.content = {};
LiveTimestamp.reset();
// RevisionSlider replaces the #mw-content-text element.
if (!this.$content.get(0).parentNode) {
this.$content = $('#mw-content-text');
}
if (htmlToLayOut) {
const div = document.createElement('div');
div.innerHTML = htmlToLayOut;
this.rootElement = div.firstChild;
this.$root = $(this.rootElement);
} else {
this.$root = this.$content.children('.mw-parser-output');
// 404 pages
if (!this.$root.length) {
this.$root = this.$content;
}
this.rootElement = this.$root.get(0);
}
// Do it immediately to prevent the issue when any unexpected error prevents this from being
// executed and then this.handleWikipageContentHookFirings is called with #mw-content-text
// element for some reason, and the page goes into an infinite reloading loop.
this.$root.data('cd-parsed', true);
},
/**
* Set whether the current page is a talk page.
*
* @param {boolean} value
*/
setTalkPageness(value) {
this.talkPage = Boolean(value);
},
/**
* Check whether the current page is likely a talk page. See {@link controller.isTalkPage} for the
* most strict criteria.
*
* @returns {boolean}
*/
isTalkPage() {
return this.talkPage;
},
/**
* Check whether the current page is a watchlist or recent changes page.
*
* @returns {boolean}
*/
isWatchlistPage() {
return ['Recentchanges', 'Watchlist'].includes(mw.config.get('wgCanonicalSpecialPageName'));
},
/**
* Check whether the current page is a contributions page.
*
* @returns {boolean}
*/
isContributionsPage() {
return mw.config.get('wgCanonicalSpecialPageName') === 'Contributions';
},
/**
* Check whether the current page is a history page.
*
* @returns {boolean}
*/
isHistoryPage() {
return (
mw.config.get('wgAction') === 'history' &&
isProbablyTalkPage(cd.g.PAGE_NAME, cd.g.NAMESPACE_NUMBER)
);
},
/**
* Check whether the current page is a diff page.
*
* This is not a constant: the diff may be removed from the page (and the URL updated, see
* {@link controller.cleanUpUrlAndDom}) when it's for the last revision and the page is reloaded
* using the script. `wgIsArticle` config value is not taken into account: if the "Do not show
* page content below diffs" MediaWiki setting is on, `wgIsArticle` is false.
*
* @returns {boolean}
*/
isDiffPage() {
return this.diffPage;
},
/**
* Check whether the current page meets strict criteria for classifying as a talk page. See
* {@link controller.isTalkPage} for approximate criteria.
*
* @returns {boolean}
*/
isDefinitelyTalkPage() {
return this.definitelyTalkPage;
},
/**
* Check if the _article_ page (the one with `wgIsArticle` being true) of the current page is a
* talk page eligible for CD. It can be `true` on edit, history pages etc. Although the
* assessments may be different on a history page and on an article page of the same title, since
* the page can contain elements with special classes that we can access only on the article page.
*
* @returns {boolean}
*/
isArticlePageTalkPage() {
return this.articlePageTalkPage;
},
/**
* Check whether the current page exists (is not 404).
*
* @returns {boolean}
*/
doesPageExist() {
return Boolean(mw.config.get('wgArticleId'));
},
/**
* Check whether the current page is an active talk page: existing, the current revision, not an
* archive page.
*
* This value isn't static:
* 1. A 404 page doesn't have an ID and is considered inactive, but if the user adds a topic to
* it, it will become active and get an ID.
* 2. The user may switch to another revision using RevisionSlider.
* 3. On a really rare occasion, an active page may become inactive if it becomes identified as
* an archive page. This possibility is currently switched off.
*
* @returns {boolean}
*/
isPageActive() {
return (
this.talkPage &&
this.doesPageExist() &&
!cd.page.isArchivePage() &&
this.isCurrentRevision()
);
},
/**
* Check whether the current page is eligible for submitting comments to.
*
* @returns {boolean}
*/
isPageCommentable() {
return this.talkPage && (this.isPageActive() || !this.doesPageExist());
},
/**
* Set whether the viewport is currently automatically scrolled to some position.
*
* @param {boolean} value
*/
toggleAutoScrolling(value) {
this.autoScrolling = Boolean(value);
},
/**
* Check whether the viewport is currently automatically scrolled to some position.
*
* @returns {boolean}
*/
isAutoScrolling() {
return this.autoScrolling;
},
/**
* Memorize the section button container element.
*
* @param {JQuery} $container
*/
setAddSectionButtonContainer($container) {
this.$addSectionButtonContainer = $container;
},
/**
* Memorize the active autocomplete menu element.
*
* @param {Element} menuElement
*/
setActiveAutocompleteMenu(menuElement) {
this.activeAutocompleteMenu = menuElement;
},
/**
* Get the active autocomplete menu element.
*
* @returns {Element}
*/
getActiveAutocompleteMenu() {
return this.activeAutocompleteMenu;
},
/**
* Forget the active autocomplete menu element (after it was deactivated).
*/
forgetActiveAutocompleteMenu() {
delete this.activeAutocompleteMenu;
},
/**
* Memorize the "Add section" form.
*
* @param {CommentForm} commentForm
*/
setAddSectionForm(commentForm) {
this.addSectionForm = commentForm;
},
/**
* Get the "Add section" form.
*
* @returns {CommentForm}
*/
getAddSectionForm() {
return this.addSectionForm;
},
/**
* Forget the "Add section" form (after it was torn down).
*/
forgetAddSectionForm() {
delete this.addSectionForm;
},
/**
* OOUI window manager.
*
* @class WindowManager
* @memberof external:OO.ui
* @see https://doc.wikimedia.org/oojs-ui/master/js/#!/api/OO.ui.WindowManager
*/
/**
* Create a OOUI window manager or return an existing one.
*
* @returns {external:OO.ui.WindowManager}
*/
getWindowManager() {
if (!this.windowManager) {
this.windowManager = new OO.ui.WindowManager().on('closing', async (win, closed) => {
// We don't have windows that can be reused.
await closed;
this.windowManager.clearWindows();
});
$(document.body).append(this.windowManager.$element);
}
return this.windowManager;
},
/**
* @class Api
* @see https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/mw.Api
* @memberof external:mw
*/
/**
* Get a
* {@link https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/mw.Api mw.Api} instance.
*
* @returns {external:mw.Api}
*/
getApi() {
if (!this.api) {
this.api = new mw.Api({
parameters: {
formatversion: 2,
uselang: cd.g.USER_LANGUAGE,
},
ajax: {
headers: {
'Api-User-Agent': 'c:User:Jack who built the house/Convenient Discussions',
},
},
});
}
return this.api;
},
/**
* Get the worker object.
*
* @returns {Worker}
*/
getWorker() {
if (!this.worker) {
this.worker = new Worker();
}
return this.worker;
},
/**
* _For internal use._ Memorize the state related to `controller.$contentColumn`.
*
* @param {boolean} setCssVar Whether to set the `--cd-content-start-margin` CSS variable.
*/
setContentColumnState(setCssVar) {
const prop = cd.g.CONTENT_DIR === 'ltr' ? 'padding-left' : 'padding-right';
let contentStartMargin = parseFloat(this.$contentColumn.css(prop));
if (contentStartMargin < cd.g.CONTENT_FONT_SIZE) {
contentStartMargin = cd.g.CONTENT_FONT_SIZE;
}
// The content column in Timeless has no _borders_ as such, so it's wrong to penetrate the
// surrounding area from the design point of view.
if (cd.g.SKIN === 'timeless') {
contentStartMargin--;
}
this.contentStartMargin = contentStartMargin;
if (setCssVar) {
$(this.document).css('--cd-content-start-margin', contentStartMargin + 'px');
}
const left = this.$contentColumn.offset().left;
const width = this.$contentColumn.outerWidth();
this.contentColumnStart = cd.g.CONTENT_DIR === 'ltr' ? left : left + width;
this.contentColumnEnd = cd.g.CONTENT_DIR === 'ltr' ? left + width : left;
},
/**
* Is the displayed revision the current (last known) revision of the page.
*
* @returns {boolean}
*/
isCurrentRevision() {
// RevisionSlider may show a revision newer than the revision in `wgCurRevisionId` (when
// navigating forward, at least twice, from a revision older than the revision in
// `wgCurRevisionId` after some revisions were added). Unfortunately, it doesn't update the
// `wgCurRevisionId` value.
return mw.config.get('wgRevisionId') >= mw.config.get('wgCurRevisionId');
},
/**
* Save the scroll position relative to the first element in the viewport looking from the top of
* the page.
*
* @param {?object} [switchToAbsolute=null] If an object with the `saveTocHeight` property and the
* viewport is above the bottom of the table of contents, then use
* {@link module:controller.saveScrollPosition} (this allows for better precision).
*/
saveRelativeScrollPosition(switchToAbsolute = null) {
// Look for a cached value to avoid reflow.
const scrollY = this.bootProcess.data('scrollY') || window.scrollY;
// The viewport has the TOC bottom or is above it.
if (switchToAbsolute && toc.isPresentClassic && scrollY < getTocBottomOffset()) {
this.saveScrollPosition(switchToAbsolute.saveTocHeight);
} else {
this.scrollData.element = null;
this.scrollData.elementTop = null;
this.scrollData.touchesBottom = false;
this.scrollData.offsetBottom = this.document.scrollHeight - (scrollY + window.innerHeight);
// The number 100 accounts for various content moves by scripts running on the page (like
// HotCat that may add an empty category list).
if (this.scrollData.offsetBottom < 100) {
this.scrollData.touchesBottom = true;
} else if (scrollY !== 0 && this.rootElement.getBoundingClientRect().top <= 0) {
const treeWalker = new ElementsTreeWalker(
this.rootElement.firstElementChild,
this.rootElement
);
while (true) {
const node = treeWalker.currentNode;
if (!isInline(node) && !this.getFloatingElements().includes(node)) {
const rect = node.getBoundingClientRect();
if (rect.bottom >= 0 && rect.height !== 0) {
this.scrollData.element = node;
this.scrollData.elementTop = rect.top;
if (treeWalker.firstChild()) {
continue;
} else {
break;
}
}
}
if (!treeWalker.nextSibling()) break;
}
}
}
},
/**
* Restore the scroll position saved in {@link module:controller.saveRelativeScrollPosition}.
*
* @param {boolean} [switchToAbsolute=false] Restore the absolute position using
* {@link module:controller.restoreScrollPosition} if
* {@link module:controller.saveScrollPosition} was previously used for saving the position.
*/
restoreRelativeScrollPosition(switchToAbsolute = false) {
if (switchToAbsolute && this.scrollData.offset !== null) {
this.restoreScrollPosition();
} else {
if (this.scrollData.touchesBottom && window.scrollY !== 0) {
const y = this.document.scrollHeight - window.innerHeight - this.scrollData.offsetBottom;
window.scrollTo(0, y);
} else if (this.scrollData.element) {
const rect = this.scrollData.element.getBoundingClientRect();
if (getVisibilityByRects(rect)) {
window.scrollTo(0, window.scrollY + rect.top - this.scrollData.elementTop);
}
}
}
},
/**
* _For internal use._ Replace the element used for restoring saved relative scroll position with
* a new element if it coincides with the provided element.
*
* @param {Element} element
* @param {Element} newElement
*/
replaceScrollAnchorElement(element, newElement) {
if (this.scrollData.element && element === this.scrollData.element) {
this.scrollData.element = newElement;
}
},
/**
* Save the scroll position to restore it later with
* {@link module:controller.restoreScrollPosition}.
*
* @param {boolean} [saveTocHeight=true] `false` is used for more fine control of scroll behavior
* when visits are loaded after a page reload.
*/
saveScrollPosition(saveTocHeight = true) {
this.scrollData.offset = window.scrollY;
this.scrollData.tocHeight = (
(saveTocHeight || this.scrollData.tocHeight) &&
toc.isPresentClassic &&
!toc.isFloating &&
window.scrollY !== 0 &&
// There is some content below the TOC in the viewport.
getTocBottomOffset() < window.scrollY + window.innerHeight
) ?
toc.$element.outerHeight() :
null;
},
/**
* Restore the scroll position saved in {@link module:controller.saveScrollPosition}.
*
* @param {boolean} [resetTocHeight=true] `false` is used for more fine control of scroll behavior
* after page reloads.
*/
restoreScrollPosition(resetTocHeight = true) {
if (this.scrollData.offset === null) return;
if (this.scrollData.tocHeight) {
this.scrollData.offset += (toc.$element.outerHeight() || 0) - this.scrollData.tocHeight;
}
window.scrollTo(0, this.scrollData.offset);
this.scrollData.offset = null;
if (resetTocHeight) {
this.scrollData.tocHeight = null;
}
},
/**
* Find closed discussions on the page.
*
* @returns {Element[]}
*/
getClosedDiscussions() {
if (!this.content.closedDiscussions) {
const closedDiscussionsSelector = cd.config.closedDiscussionClasses
.map((name) => `.${name}`)
.join(', ');
this.content.closedDiscussions = this.$root.find(closedDiscussionsSelector).get();
}
return this.content.closedDiscussions;
},
/**
* Find outdent templates on the page.
*
* @returns {boolean}
*/
areThereOutdents() {
if (!this.content.areThereOutdents) {
this.content.areThereOutdents = Boolean(this.$root.find('.' + cd.config.outdentClass).length);
}
return this.content.areThereOutdents;
},
/**
* Extract and memorize the classes mentioned in the TemplateStyles tags on the page.
*
* @private
*/
extractTemplateStylesSelectors() {
this.content.tsSelectorsFloating = [];
this.content.tsSelectorsHidden = [];
const filterRules = (rule) => {
if (rule instanceof CSSStyleRule) {
const style = rule.style;
if (style.float === 'left' || style.float === 'right') {
this.content.tsSelectorsFloating.push(rule.selectorText);
}
if (style.display === 'none') {
this.content.tsSelectorsHidden.push(rule.selectorText);
}
} else if (rule instanceof CSSMediaRule) {
[...rule.cssRules].forEach(filterRules);
}
};
[...document.styleSheets]
.filter((sheet) => sheet.href?.includes('site.styles'))
.forEach((el) => {
[...el.cssRules].forEach(filterRules);
});
[...this.rootElement.querySelectorAll('style')].forEach((el) => {
[...el.sheet.cssRules].forEach(filterRules);
});
},
/**
* Get the selectors for floating elements mentioned in the TemplateStyles tags on the page.
*
* @returns {string[]}
* @private
*/
getTsFloatingElementSelectors() {
if (!this.content.tsSelectorsFloating) {
this.extractTemplateStylesSelectors();
}
return this.content.tsSelectorsFloating;
},
/**
* Get the selectors for hidden elements mentioned in the TemplateStyles tags on the page.
*
* @returns {string[]}
* @private
*/
getTsHiddenElementSelectors() {
if (!this.content.tsSelectorsHidden) {
this.extractTemplateStylesSelectors();
}
return this.content.tsSelectorsHidden;
},
/**
* Find floating elements on the page.
*
* @returns {Element[]}
*/
getFloatingElements() {
if (!this.content.floatingElements) {
// Describe all floating elements on the page in order to calculate the correct border
// (temporarily setting "overflow: hidden") for all comments that they intersect with.
const floatingElementSelector = [
...cd.g.FLOATING_ELEMENT_SELECTORS,
...this.getTsFloatingElementSelectors(),
].join(', ');
// Can't use jQuery here anyway, as .find() doesn't take into account ancestor elements, such
// as .mw-parser-output, in selectors. Remove all known elements that never intersect comments
// from the collection.
this.content.floatingElements = [
...this.rootElement.querySelectorAll(floatingElementSelector)
].filter((el) => !el.classList.contains('cd-ignoreFloating'));
}
return this.content.floatingElements;
},
/**
* Find floating and hidden (`display: none`) elements on the page.
*
* @returns {Element[]}
*/
getHiddenElements() {
if (!this.hiddenElements) {
const hiddenElementSelector = this.getTsHiddenElementSelectors().join(', ');
this.hiddenElements = hiddenElementSelector ?
[...this.rootElement.querySelectorAll(hiddenElementSelector)] :
[];
}
return this.hiddenElements;
},
/**
* Check whether there are "LTR inside RTL" or "RTL inside LTR" situations on the page.
*
* @returns {boolean}
*/
areThereLtrRtlMixes() {
if (!this.content.areThereLtrRtlMixes) {
this.content.areThereLtrRtlMixes = Boolean(
document.querySelector('.sitedir-ltr .mw-content-rtl, .sitedir-rtl .mw-content-ltr')
);
}
return this.content.areThereLtrRtlMixes;
},
/**
* Get the popup overlay used for OOUI components.
*
* @param {boolean} create
* @returns {JQuery}
*/
getPopupOverlay(create = true) {
if (!this.$popupOverlay && create) {
this.$popupOverlay = $('<div>')
.addClass('cd-popupOverlay')
.appendTo(document.body);
}
return this.$popupOverlay;
},
/**
* Add a condition preventing page unload.
*
* @param {string} name
* @param {Function} condition
*/
addPreventUnloadCondition(name, condition) {
if (!this.beforeUnloadHandlers) {
this.beforeUnloadHandlers = {};
}
this.beforeUnloadHandlers[name] = (e) => {
if (condition()) {
e.preventDefault();
e.returnValue = '';
return '';
}
};
$(window).on('beforeunload', this.beforeUnloadHandlers[name]);
},
/**
* Remove a condition preventing page unload.
*
* @param {string} name
*/
removePreventUnloadCondition(name) {
if (this.beforeUnloadHandlers[name]) {
$(window).off('beforeunload', this.beforeUnloadHandlers[name]);
delete this.beforeUnloadHandlers[name];
}
},
/**
* _For internal use._ Handle a mouse move event (including `mousemove` and `mouseover`).
*
* @param {Event} e
*/
handleMouseMove(e) {
if (postponements.is('scroll') || this.isAutoScrolling() || this.isPageOverlayOn()) return;
Comment.highlightHovered(e);
},
/**
* _For internal use._ Handles the window `resize` event as well as `orientationchange`.
*/
handleWindowResize() {
// setTimeout, because it seems like sometimes it doesn't have time to update.
setTimeout(() => {
this.setContentColumnState(true);
Comment.redrawLayersIfNecessary(true);
Thread.updateLines();
pageNav.updateWidth();
});
navPanel.updateCommentFormButton();
cd.commentForms.forEach((commentForm) => {
commentForm.adjustLabels();
});
this.handleScroll();
},
/**
* _For internal use._ Handles the document `keydown` event.
*
* @param {Event} e
*/
handleGlobalKeyDown(e) {
if (this.isPageOverlayOn()) return;
if (
// Ctrl+Alt+Q
keyCombination(e, 81, ['ctrl', 'alt']) ||
// Q
(keyCombination(e, 81) && !isInputFocused())
) {
const lastActiveCommentForm = CommentForm.getLastActive();
if (lastActiveCommentForm) {
e.preventDefault();
lastActiveCommentForm.quote(isCmdMofidicatorPressed(e));
} else {
const comment = Comment.getSelectedComment();
if (comment?.isActionable) {
e.preventDefault();
comment.reply();
}
}
}
if (navPanel.isMounted()) {
// R
if (keyCombination(e, 82) && !isInputFocused()) {
navPanel.refreshClick();
}
// W
if (keyCombination(e, 87) && !isInputFocused()) {
navPanel.goToPreviousNewComment();
}
// S
if (keyCombination(e, 83) && !isInputFocused()) {
navPanel.goToNextNewComment();
}
// F
if (keyCombination(e, 70) && !isInputFocused()) {
navPanel.goToFirstUnseenComment();
}
// C
if (keyCombination(e, 67) && !isInputFocused()) {
e.preventDefault();
navPanel.goToNextCommentForm();
}
}
},
/**
* _For internal use._ Register seen comments, update the navigation panel's first unseen button,
* and update the current section block.
*/
handleScroll() {
// Scroll will be handled when the autoscroll is finished.
if (this.isAutoScrolling()) return;
const actuallyHandle = () => {
if (this.isAutoScrolling()) return;
if (this.isPageActive()) {
Comment.registerSeen();
navPanel.updateCommentFormButton();
}
pageNav.update();
};
// Don't run this more than once in some period, otherwise scrolling may be slowed down. Also,
// wait before running, otherwise comments may be registered as seen after a press of Page
// Down/Page Up. One scroll in Chrome, Firefox with Page Up/Page Down takes a little less than
// 200ms, but 200ms proved to be not enough, so we try 300ms.
postponements.add('scroll', actuallyHandle, 300);
},
/**
* _For internal use._ Handle a `popstate` event, including clicks on links pointing to comment
* anchors.
*/
handlePopState() {
let fragment = location.hash.slice(1);
if (Comment.isDtId(fragment) || Comment.isId(fragment)) {
// Don't jump to the comment if the user pressed Back/Forward in the browser or if
// history.pushState() is called from Comment#scrollTo() (after clicks on added (gray) items
// in the TOC).
if (history.state?.cdJumpedToComment) return;
try {
fragment = decodeURIComponent(fragment);
} catch (e) {
console.error(e);
return;
}
const comment = Comment.isDtId(fragment) ?
Comment.getByDtId(fragment) :
Comment.getById(fragment, true);
comment?.scrollTo();
}
},
/**
* _For internal use._ Handle a `selectionChange` event.
*/
handleSelectionChange() {
postponements.add('selectionChange', Comment.getSelectedComment, 200);
},
/**
* _For internal use._ Handle page (content area) mutations.
*/
handlePageMutations() {
if (this.booting) return;
const floatingRects = this.getFloatingElements().map(getExtendedRect);
Comment.redrawLayersIfNecessary(false, false, floatingRects);
const updateThreadLines = () => {
Thread.updateLines(floatingRects);
$(document).off('mousemove', updateThreadLines);
this.isUpdateThreadLinesHandlerAttached = false;
};
if (!this.isUpdateThreadLinesHandlerAttached && settings.get('enableThreads')) {
// Update only on mouse move to prevent short freezings of a page when there is a
// comment form in the beginning of a very long page and the input is changed so that
// everything below the form shifts vertically.
$(document).on('mousemove', updateThreadLines);
this.isUpdateThreadLinesHandlerAttached = true;
}
// Could also run handleScroll() here, but not sure, as it will double the execution
// time with rare effect.
},
/**
* Handle a click on an "Add topic" button.
*
* @param {Event} e
*/
handleAddTopicButtonClick(e) {
if (e.ctrlKey || e.shiftKey || e.metaKey) return;
const $button = $(e.currentTarget);
let preloadConfig;
let isNewTopicOnTop = false;
if ($button.is('a')) {
const href = $button.attr('href');
let query;
// May crash if the current URL contains undecodable "%" in the fragment.
try {
query = new mw.Uri(href).query;
} catch {
return;
}
preloadConfig = {
editIntro: getLastArrayElementOrSelf(query.editintro),
commentTemplate: getLastArrayElementOrSelf(query.preload),
headline: getLastArrayElementOrSelf(query.preloadtitle),
summary: getLastArrayElementOrSelf(query.summary)?.replace(/^.+?\*\/ */, ''),
noHeadline: Boolean(getLastArrayElementOrSelf(query.nosummary)),
omitSignature: Boolean(query.cdomitsignature),
};
isNewTopicOnTop = getLastArrayElementOrSelf(query.section) === '0';
} else {
// <input>
const $form = $button.closest('form');
preloadConfig = {
editIntro: $form.find('input[name="editintro"]').val(),
commentTemplate: $form.find('input[name="preload"]').val(),
headline: $form.find('input[name="preloadtitle"]').val(),
summary: $form.find('input[name="summary"]').val(),
noHeadline: Boolean($form.find('input[name="nosummary"]').val()),
omitSignature: false,
};
}
e.preventDefault();