-
Notifications
You must be signed in to change notification settings - Fork 12
/
MoreMenu.js
1244 lines (1106 loc) · 46.8 KB
/
MoreMenu.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
/** Script starts here, waiting for the DOM to be ready before calling init(). */
$(() => {
window.MoreMenu = window.MoreMenu || {};
if (window.moreMenuDebug) {
/* eslint-disable no-console */
console.info(
'[MoreMenu] Debugging enabled. To disable, check your personal JS and remove `MoreMenu.debug = true;`.',
);
}
const api = new mw.Api();
/**
* Flag to suppress warnings shown by the msg() function.
* This is set by the addItem() method, since user-provided messages may not be stored in `MoreMenu.messages`.
*/
let ignoreI18nWarnings = false;
/** RTL helpers. */
const isRtl = 'rtl' === $('html').prop('dir');
const leftKey = isRtl ? 'right' : 'left';
const rightKey = isRtl ? 'left' : 'right';
/** Configuration to be passed to MoreMenu.user.js, MoreMenu.page.js, and handlers of the 'moremenu.ready' hook. */
const config = new function () {
/** Project-level */
this.project = {
domain: mw.config.get('wgServerName'),
siteName: mw.config.get('wgSiteName'),
dbName: mw.config.get('wgDBname'),
noticeProject: mw.config.get('wgNoticeProject'),
contentLanguage: mw.config.get('wgContentLanguage'),
};
/** Page-level */
this.page = {
name: mw.config.get('wgPageName'),
nsId: mw.config.get('wgNamespaceNumber'),
protected: (!!mw.config.get('wgRestrictionEdit') && mw.config.get('wgRestrictionEdit').length)
|| (!!mw.config.get('wgRestrictionCreate') && mw.config.get('wgRestrictionCreate').length),
id: mw.config.get('wgArticleId'),
movable: !mw.config.get('wgIsMainPage') && !!$('#ca-move').length,
};
if (-1 === this.page.nsId
&& !!mw.config.get('wgRelevantPageName') && mw.config.get('wgRelevantPageName').length
&& this.page.name !== mw.config.get('wgRelevantPageName')
) {
$.extend(this.page, {
name: mw.config.get('wgRelevantPageName'),
id: mw.config.get('wgRelevantArticleId'),
});
this.page.nsId = mw.Title.newFromText(this.page.name).namespace;
}
$.extend(this.page, {
escapedName: this.page.name.replace(/[?!'"()*]/g, escape),
encodedName: encodeURIComponent(this.page.name),
});
/** Currently viewing user (you). */
this.currentUser = {
skin: mw.config.get('skin'),
groups: mw.config.get('wgUserGroups'),
groupsData: {}, // Keyed by user group name, values have keys 'rights' and 'canAddRemoveGroups'.
rights: [],
};
/**
* Target user (when viewing user pages, Special:Contribs, etc.).
* Also will contain data retrieved from the API such as their user groups and block status.
*/
this.targetUser = {
name: mw.config.get('wgRelevantUserName') || '',
groups: [],
rights: [],
blocked: false,
ipRange: false,
};
if (!this.targetUser.name
&& 'Contributions' === mw.config.get('wgCanonicalSpecialPageName')
&& !$('.mw-userpage-userdoesnotexist')[0]
) {
/**
* IP range at Special:Contribs, where wgRelevantUserName isn't set.
* @see https://phabricator.wikimedia.org/T206954
*/
this.targetUser.name = mw.config.get('wgTitle').split('/').slice(1).join('/');
this.targetUser.ipRange = true;
/** Some things don't work for IPv4 ranges (block log API), but do for IPv6 ranges... */
this.targetUser.ipv4Range = mw.util.isIPv4Address(this.targetUser.name.split('/')[0]);
}
$.extend(this.targetUser, {
escapedName: this.targetUser.name.replace(/[?!'"()*]/g, escape),
encodedName: encodeURIComponent(this.targetUser.name),
});
}();
/**
* Log a message to the console.
* @param {String} message
* @param {String} [level] Level accepted by `console`, e.g. 'debug', 'info', 'log', 'warn', 'error'.
*/
function log(message, level = 'debug') {
if (!(window.moreMenuDebug || 'debug' !== level)) {
return;
}
message = `[MoreMenu] ${message}`;
if (['', 'warn', 'error'].indexOf(level) >= 0) {
message += '\nSee https://w.wiki/9Se for documentation.';
}
/* eslint-disable no-console */
console[level](message);
}
/**
* Get a MoreMenu module.
* @param {String} name Title of module, such as 'user', which pulls in MoreMenu.user.js.
* @return {Object} All modules return Objects.
*/
function getModule(name) {
if (!MoreMenu[name]) {
log(`Missing module MoreMenu.${name}.js`, 'warn');
}
return MoreMenu[name];
}
/**
* Get translation for the given key.
* @param {String} key As defined in MoreMenu.messages.js
* @param {Boolean} [ignore] Set to true to suppress warnings if the message doesn't exist.
* This also can be prevented by setting `ignoreI18nWarnings`.
* @returns {String}
*/
function msg(key, ignore = false) {
const translation = getModule('messages')[key];
if (!translation && !ignore && !ignoreI18nWarnings) {
log(`Missing translation for "${key}" in MoreMenu.messages.en.js`, 'warn');
}
return getModule('messages')[key] || key;
}
/**
* Check whether the message exists.
* @param {String} key
* @returns {Boolean}
*/
function msgExists(key) {
return undefined !== getModule('messages')[key];
}
/**
* Normalize the given ID into the expected format.
* @param {String} id
* @returns {string}
*/
function normalizeId(id) {
return id.toLowerCase().replace(/\s+/g, '-');
}
/**
* Generate a unique ID for a menu item.
* @param {String} parentKey The message key for the parent menu ('user' or 'page').
* @param {String} [itemKey] The message key for the link itself.
* @param {String} [submenuKey] The message key for the submenu that the item is within, if applicable.
* @returns {String} For example, 'c-user-user-logs-block-log' for User > User logs > Block log.
*/
function getItemId(parentKey, itemKey, submenuKey = null) {
/* eslint-disable prefer-template */
return `mm-${normalizeId(parentKey)}`
+ (submenuKey ? `-${normalizeId(submenuKey)}` : '')
+ ('string' === typeof itemKey ? `-${normalizeId(itemKey)}` : '');
}
/**
* Load translations if viewing in non-English. MoreMenu first looks for translations on Meta,
* at MediaWiki:Gadget-MoreMenu.messages.en.js (replacing 'en' with the requested language).
* To override locally, define it before MoreMenu.js in your wiki's gadget definition.
* See [[meta:MoreMenu#Localization]] for more.
* @returns {jQuery.Promise}
*/
function loadTranslations() {
const dfd = $.Deferred();
const lang = mw.config.get('wgUserLanguage');
if ('en' === lang) {
return dfd.resolve();
}
/** Check Metawiki. */
mw.loader.getScript(
'https://meta.wikimedia.org/w/index.php?action=raw&ctype=text/javascript'
+ `&title=MediaWiki:Gadget-MoreMenu.messages.${lang}.js`,
).then(() => dfd.resolve());
return dfd;
}
/**
* Get promises needed for initializing the script, such as user rights and block status.
* @returns {jQuery.Promise[]}
*/
function getPromises() {
const promises = new Array(4);
/** Note that the blocks API doesn't work for IPv4 ranges. */
if (config.targetUser.name && !config.targetUser.ipv4Range) {
promises[0] = api.get({
action: 'query',
list: 'users|blocks',
ususers: config.targetUser.name,
bkusers: config.targetUser.name,
usprop: 'blockinfo|groups|rights|emailable',
bkprop: 'id',
});
}
config.currentUser.rights = JSON.parse(mw.storage.session.getObject('mmUserRights'));
if (!config.currentUser.rights) {
promises[1] = mw.user.getRights();
}
config.currentUser.groupsData = JSON.parse(mw.storage.session.getObject('mmMetaUserGroups'));
if (!config.currentUser.groupsData) {
promises[2] = api.get({
action: 'query',
meta: 'siteinfo',
siprop: 'usergroups',
});
}
promises[3] = loadTranslations();
return promises;
}
/**
* Do the given groups and/or rights indicate the user is allowed to change and other user's groups?
* @param {Array} groups
* @param {Array} rights
* @returns {Boolean}
*/
function canAddRemoveGroups(groups, rights) {
if (rights && rights.indexOf('userrights') >= 0) {
/** User explicitly has rights to change user groups. */
return true;
}
/* eslint-disable arrow-body-style */
const valid = groups.some(group => {
return config.currentUser.groupsData[group] && config.currentUser.groupsData[group].canAddRemoveGroups;
});
if (!valid) {
/** Clear cache and fall back to false. */
mw.storage.remove('metaUserGroups');
}
return valid;
}
/**
* Check if any of the given values are present in the permitted values.
* @param {Number|String|Array} permitted
* @param {Number|String|Array} given
* @returns {Boolean}
*/
function hasConditional(permitted, given) {
/** Convert to arrays if non-array. */
permitted = $.makeArray(permitted);
given = $.makeArray(given);
if (!permitted.length) {
/** No requirements, so validations pass. */
return true;
}
if (!given.length) {
/** Nothing given to compare to the permitted values, so validations fail. */
return false;
}
/** Loop through to see if a given value is present in the permitted values. */
return given.some(item => permitted.indexOf(item) >= 0);
}
/**
* Generate HTML for a menu item.
* @param {String} parentKey Message key for the parent menu ('user' or 'page').
* @param {String} itemKey Message key for menu item.
* @param {String} itemData Configuration for this menu item.
* @param {String} [submenuKey] The message key for the submenu that the item is within, if applicable.
* @return {String} The raw HTML.
*/
function getItemHtml(parentKey, itemKey, itemData, submenuKey = null) {
/* eslint-disable max-len */
const namespaceExclusion = itemData.namespaceExclude ? !hasConditional(itemData.namespaceExclude, config.page.nsId) : true;
const databaseExclusion = itemData.databaseExclude ? !hasConditional(itemData.databaseExclude, config.page.dbName) : true;
/**
* Keys are the name of the check, values are the expressions.
* This system is used only to make for easier debugging.
* @type {Object}
*/
const conditions = {
/** Project */
noticeProject: hasConditional(itemData.noticeProjectRestrict, config.project.noticeProject),
database: hasConditional(itemData.databaseRestrict, config.project.dbName) && databaseExclusion,
/** Page */
namespaceRestrict: hasConditional(itemData.namespaceRestrict, config.page.nsId) && namespaceExclusion,
pageExists: (itemData.pageExists && config.page.id > 0) || !itemData.pageExists,
pageDeleted: itemData.pageDeleted ? !config.page.id : true,
pageProtected: itemData.pageProtected ? config.page.protected : true,
pageMovable: itemData.pageMovable ? config.page.movable : true,
/** Current user */
currentUserGroups: hasConditional(itemData.currentUserGroups, config.currentUser.groups),
currentUserRights: hasConditional(itemData.currentUserRights, config.currentUser.rights),
currentUserChangeGroups: itemData.currentUserChangeGroups ? canAddRemoveGroups(config.currentUser.groups, config.currentUser.rights) : true,
/** Other */
visibility: undefined !== itemData.visible ? !!itemData.visible : true,
};
if (config.targetUser.name) {
/** Target user */
$.extend(conditions, {
targetUserGroups: hasConditional(itemData.targetUserGroups, config.targetUser.groups),
targetUserRights: hasConditional(itemData.targetUserRights, config.targetUser.rights),
targetUserBlocked: itemData.targetUserBlocked !== undefined ? config.targetUser.blocked === itemData.targetUserBlocked : true,
targetUserChangeGroups: itemData.targetUserChangeGroups ? canAddRemoveGroups(config.targetUser.groups, config.targetUser.rights) : true,
targetUserIp: itemData.targetUserIp
? mw.util.isIPAddress(config.targetUser.name) || (config.targetUser.ipRange && itemData.targetUserIpRange)
: true,
targetUserIpRange: config.targetUser.ipRange ? itemData.targetUserIpRange : true,
});
}
let passed = true;
/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
for (const condition in conditions) {
passed &= conditions[condition];
if (!passed) {
log(`${parentKey}/${itemKey} failed on ${condition}`);
/** Validations failed, no markup to return */
return '';
}
}
/** Markup for the menu item. */
const titleAttr = msgExists(`${itemKey}-desc`) || itemData.description
? ` title="${itemData.description ? itemData.description : msg(`${itemKey}-desc`)}"`
: '';
const styleAttr = itemData.style ? ` style="${itemData.style}"` : '';
return `
<li id="${getItemId(parentKey, itemKey, submenuKey)}" class="mm-item mw-list-item">
<a href="${itemData.url}"${titleAttr}${styleAttr}>
<span>${msg(itemData.title || itemKey)}</span>
</a>
</li>`;
}
/**
* Apply CSS based on the skin. This is done here because it is fast enough,
* not that much CSS, and saves users from having to import one more thing.
* @returns {CSSStyleSheet|null}
*/
function addCSS() {
switch (config.currentUser.skin) {
case 'vector':
case 'vector-2022':
// FIXME: first ruleset is a hotfix for T315418 / T319358
// FIXME: last two rulesets are for T337893
return mw.util.addCSS(`
.mm-tab .vector-menu-content {
height: initial;
overflow: initial !important;
}
.mm-menu .mw-list-item {
white-space: nowrap;
}
.mm-submenu {
background: #ffffff;
border: 1px solid #a2a9b1;
min-width: 120px !important;
${rightKey}: inherit !important;
top: -1px !important;
}
#p-views {
padding-left: inherit !important;
padding-right: inherit !important;
}
#p-views .vector-menu-content::after {
display: none !important;
}
.rtl #p-views .vector-menu-content::before {
display: none !important;
}
.mm-submenu .mm-item {
font-size: inherit !important;
}
.vector-feature-zebra-design-enabled .mm-menu {
background: white;
border: 1px solid #a2a9b1;
}
.vector-feature-zebra-design-enabled .mm-menu .mw-list-item {
padding: 8px;
}
`);
case 'timeless':
return mw.util.addCSS(`
.mm-submenu-wrapper {
cursor: default;
}
.mm-submenu {
background: #f8f9fa;
border: 1px solid rgb(200, 204, 209);
box-shadow: 0 2px 3px 1px rgba(0, 0, 0, 0.05);
padding: 1.2em 1.5em !important;
top: -1.2em;
white-space: nowrap;
z-index: 95;
}
.mm-submenu::after {
border-bottom: 8px solid transparent;
border-top: 8px solid transparent;
border-${leftKey}: 8px solid rgb(200, 204, 209);
content: '';
height: 0;
padding-${rightKey}: 4px;
position: absolute;
top: 20px;
width: 0;
${rightKey}: -13px;
}
@media screen and (max-width: 1339px) and (min-width: 1100px) {
.mm-submenu::after {
border-${leftKey}: none;
border-${rightKey}: 8px solid rgb(200, 204, 209);
padding-${leftKey}: 4px;
padding-${rightKey}: inherit;
${rightKey}: inherit;
${leftKey}: -35px;
}
}
@media screen and (max-width: 850px) {
.mm-submenu {
top: -2.2em;
}
}
`);
case 'monobook':
return mw.util.addCSS(`
.mm-tab {
position: relative;
}
.mm-menu {
background: #fff;
border-bottom: 1px solid #aaa;
${leftKey}: -1px;
margin: 0;
position: absolute;
z-index: 99;
}
.mm-menu ~ a {
z-index: 99 !important;
}
.mm-submenu {
background: #fff;
border-bottom: 1px solid #aaa;
border-top: 1px solid #aaa;
font-size: inherit;
margin: 0;
min-width: 75px;
top: -1px;
z-index: 95;
}
.mm-item, .mm-submenu-wrapper {
background: #fff !important;
border-top: 0 !important;
display: block !important;
margin: 0 !important;
padding: 0 !important;
width: 100%;
}
.mm-item a, .mm-submenu-wrapper a {
background: transparent !important;
text-transform: none !important;
}
.mm-menu a:hover {
text-decoration: underline !important;
}
`);
case 'modern':
return mw.util.addCSS(`
.mm-menu, .mm-submenu {
background: #f0f0f0 !important;
border: solid 1px #666;
}
.mm-menu {
border-top: none;
position: absolute;
z-index: 99;
}
.mm-submenu-wrapper > a {
cursor: default !important;
}
.mm-item, .mm-submenu-wrapper {
display: block !important;
float: none !important;
height: inherit !important;
margin: 0 !important;
padding: 0 !important;
}
.mm-menu a {
display: inline-block;
padding: 3px 10px !important;
text-transform: none !important;
text-decoration: none !important;
white-space: nowrap;
width: 100%;
}
.mm-menu a:hover {
text-decoration: underline !important;
}
.mm-submenu {
${leftKey}: 100%;
min-width: 120px !important;
top: 0;
}
`);
default:
return null;
}
}
/**
* Get CSS for the submenu.
* @param $element
* @returns {Object} To be passed to $.css()
*/
function getSubmenuCss($element) {
switch (config.currentUser.skin) {
case 'vector':
case 'vector-2022':
return { [leftKey]: $element.outerWidth() };
case 'timeless':
return {
[$(window).width() <= 1339 && $(window).width() >= 1100 ? leftKey : rightKey]:
$element.outerWidth() + 11,
};
case 'monobook':
return { [leftKey]: $element.outerWidth() - 2 };
default:
return {};
}
}
/**
* Add hover listeners to the submenus. This may be re-called as many times as needed.
*/
function addListeners() {
$('.mm-submenu-wrapper').each(function hoverMenus() {
$(this).off('mouseenter').on('mouseenter', function hoverMenusMouseenter() {
$(this).find('.mm-submenu')
.css(getSubmenuCss($(this)))
.show();
}).off('mouseleave').on('mouseleave', function hoverMenusMouseleave() {
$(this).find('.mm-submenu').hide();
});
});
}
/**
* Sort alphabetically by translation.
* @param {Array} i18nKeys
* @returns {Array}
*/
function sortByTranslation(i18nKeys) {
return i18nKeys.sort((a, b) => {
const nameA = msg(a).toLowerCase();
const nameB = msg(b).toLowerCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
}
/**
* Sort given menu items alphabetically, leaving submenus at the top (unsorted),
* and respecting the 'insertAfter' option for each item, if present.
* @param {Object} items
* @return {string[]} Item IDs.
*/
function sortItems(items) {
const itemKeys = Object.keys(items);
/** The labels for the submenus are not sorted. */
const submenus = itemKeys.filter(itemKey => !items[itemKey].url);
/** All other menu items (top-level) are sorted alphabetically. */
const sortedItemKeys = sortByTranslation(itemKeys.filter(itemKey => !!items[itemKey].url));
/** Loop through again, rearranging based on the 'insertAfter' option. */
const newItemKeys = sortedItemKeys;
sortedItemKeys.forEach(itemKey => {
const target = items[itemKey].insertAfter;
let newIndex;
if (false === target) {
/** False means put at the top. */
newIndex = 0;
} else if (true === target) {
/** True means put at the bottom. */
newIndex = itemKeys.length;
} else if (!target) {
/** Nothing to do. */
return;
} else {
newIndex = newItemKeys.indexOf(target);
/**
* Insert at end if target wasn't found.
* The +1 is because it goes after the target.
*/
newIndex = -1 === newIndex ? newItemKeys.length : newIndex + 1;
}
/** Remove the original placement, and insert after the target. */
newItemKeys.splice(newItemKeys.indexOf(itemKey), 1);
newItemKeys.splice(newIndex, 0, itemKey);
});
/** Combine and return, with the submenus coming first. */
return submenus.concat(newItemKeys);
}
/**
* Get the markup for the menu based on the given data.
* @param {String} parentKey Message key for the parent menu ('user' or 'page').
* @param {Object} items Menu items, as provided by MoreMenu.user.js and MoreMenu.page.js
* @param {String} [submenuKey] Used to ensure the generated IDs include the submenu name.
* @return {String} Raw HTML.
*/
function getMenuHtml(parentKey, items, submenuKey) {
let html = '';
const submenuClasses = 'vector' === config.currentUser.skin || 'vector-2022' === config.currentUser.skin
? 'vector-menu-content-list'
: '';
sortItems(items).forEach(itemKey => {
const item = items[itemKey];
let itemHtml = '';
if (!item.url) {
/** This is a submenu. */
itemHtml += `
<li style="position:relative;" id="${getItemId(parentKey, itemKey)}" class="mm-submenu-wrapper mw-list-item">
<a style="font-weight: bold"><span>${msg(itemKey)}…</span></a>
<ul class="menu mm-submenu ${submenuClasses}" style="display: none; position: absolute;">`;
sortItems(item).forEach(submenuItemKey => {
itemHtml += getItemHtml(parentKey, submenuItemKey, item[submenuItemKey], itemKey);
});
itemHtml += '</ul></li>';
if (0 === $(itemHtml).last().find('.mm-submenu li').length) {
/** No items in the submenu, so don't show the submenu at all. */
itemHtml = '';
}
} else {
itemHtml += getItemHtml(parentKey, itemKey, item, submenuKey);
}
html += itemHtml;
});
return html;
}
/**
* Draw menu for the Vector skin.
* @param {String} parentKey Message key for the parent menu ('user' or 'page').
* @param {String} html As generated by getMenuHtml().
*/
function drawMenuVector(parentKey, html) {
html = `<div id="p-${parentKey}" class="mw-portlet mw-portlet-${parentKey} vector-menu vector-dropdown vector-menu-dropdown vector-has-collapsible-items mm-${parentKey} mm-tab" `
+ `aria-labelledby="p-${parentKey}-label">`
+ `<input id="p-${parentKey}-dropdown-checkbox" class="vector-menu-checkbox vector-dropdown-checkbox" type="checkbox" role="button" aria-haspopup="true" aria-labelledby="p-${parentKey}-label">`
+ `<label id="p-${parentKey}-label" class="vector-menu-heading vector-dropdown-label" for="p-${parentKey}-dropdown-checkbox"><span class="vector-menu-heading-label">${msg(parentKey)}</span></label>`
+ '<div class="vector-menu-content vector-dropdown-content">'
+ `<ul class="menu vector-menu-content-list mm-menu">${html}</ul>`
+ '</div></div>';
$(html).insertAfter($('#p-views, .mm-page').last());
}
/**
* Draw menu for the Timeless skin.
* @param {String} parentKey Message key for the parent menu ('user' or 'page').
* @param {String} html As generated by getMenuHtml().
*/
function drawMenuTimeless(parentKey, html) {
html = `<div role="navigation" class="mw-portlet mm-${parentKey} mm-tab" id="p-${parentKey}" aria-labelledby="p-${parentKey}-label">`
+ `<h3 id="p-${parentKey}-label">${msg(parentKey)}</h3>`
+ `<div class="mw-portlet-body"><ul class="mm-menu">${html}</ul></div></div>`;
if ($('#p-cactions').length) {
$(html).insertBefore($('#p-cactions'));
} else {
$('#page-tools .sidebar-inner').prepend(html);
}
}
/**
* Draw menu for the Monobook skin.
* @param {String} parentKey Message key for the parent menu ('user' or 'page').
* @param {String} html As generated by getMenuHtml().
*/
function drawMenuMonobook(parentKey, html) {
html = `<li id="ca-${parentKey}" class="mm-${parentKey} mm-tab">`
+ `<a href="javascript:void(0)">${msg(parentKey)}</a>`
+ `<ul class="mm-menu" style="display:none">${html}</ul>`
+ '</li>';
const $tab = $(html).insertAfter(
$('#ca-nstab-special, #ca-edit, #ca-ve-edit, #ca-page, #ca-viewsource, #ca-talk').last(),
);
const $menu = $tab.find('.mm-menu');
/** Add hover listeners. */
$tab.on('mouseenter', () => {
$menu.show();
$tab.find('> a').css({ 'z-index': 99 });
}).on('mouseleave', () => {
$menu.hide();
$tab.find('> a').css({ 'z-index': 'inherit' });
});
}
/**
* Draw menu for the Modern skin.
* @param {String} parentKey Message key for the parent menu ('user' or 'page').
* @param {String} html As generated by getMenuHtml().
*/
function drawMenuModern(parentKey, html) {
html = `<li id="ca-${parentKey}" class="mm-${parentKey} mm-tab">`
+ `<a href="javascript:void(0)">${msg(parentKey)}</a>`
+ `<ul class="mm-menu" style="display:none">${html}</ul>`
+ '</li>';
const $tab = $(html).insertAfter(
$('#ca-nstab-special, #ca-edit, #ca-ve-edit, #ca-page, #ca-viewsource, #ca-talk').last(),
);
const $menu = $tab.find('.mm-menu');
/** Position the menu. */
$menu.css({
left: isRtl ? $tab.position().left - $menu.width() + $tab.width() + 7 : $tab.position().left,
top: $tab.offset().top + $tab.outerHeight(),
});
/** Add hover listeners. */
$tab.on('mouseenter', () => {
$menu.show();
}).on('mouseleave', () => {
$menu.hide();
});
}
/**
* Determine which menus to display and insert them into the DOM.
*/
function drawMenus() {
const menus = {};
/** Determine which menus to draw. */
if (config.page.nsId >= 0) {
$.extend(menus, getModule('page')(config));
}
if (config.targetUser.name) {
$.extend(menus, getModule('user')(config));
}
/** Preemptively add the appropriate CSS. */
addCSS();
Object.keys(menus).forEach(key => {
const html = getMenuHtml(key, menus[key]);
switch (config.currentUser.skin) {
case 'vector-2022':
case 'vector':
drawMenuVector(key, html);
break;
case 'monobook':
drawMenuMonobook(key, html);
break;
case 'modern':
drawMenuModern(key, html);
break;
case 'timeless':
drawMenuTimeless(key, html);
break;
default:
log(`'${config.currentUser.skin}' is not a supported skin.`, 'error');
}
});
addListeners();
}
/**
* Monobook and Modern have 'History' and 'Watch' links as tabs. To conserve space, they are moved to the Page menu.
* This method is called before and after the menus are drawn, to ensure positioning is calculated correctly.
* Listeners on these links are preserved, but we do change the element IDs to our pattern (e.g. `mm-page-history`).
* @param {Boolean} [replace] True to replace the links in .mm-page with the native links, false just hides them.
*/
function handleHistoryAndWatchLinks(replace = false) {
const monobookModern = -1 !== ['monobook', 'modern'].indexOf(config.currentUser.skin);
const $histLink = $('#ca-history');
const $watchLink = $('.mw-watchlink');
const $moveLink = $('#ca-move');
if (replace) {
if (monobookModern) {
$('#mm-page-watch').replaceWith(
$watchLink.addClass('mm-item')
.prop('id', 'mm-page-watch')
.show(),
);
$('#mm-page-history').replaceWith(
$histLink.addClass('mm-item')
.prop('id', 'mm-page-history')
.show(),
);
}
$('#mm-page-move-page').replaceWith(
$moveLink.addClass('mm-item')
.prop('id', 'mm-page-move-page')
.show(),
);
return;
}
/** No need to ask for translations when these already live on the page. */
MoreMenu.messages.watch = $watchLink.text() || 'watch';
MoreMenu.messages.history = $histLink.text() || 'history';
/** Hide the links so that the positioning is calculated correctly in drawMenus() */
if (monobookModern) {
$watchLink.hide();
$histLink.hide();
}
$moveLink.hide();
}
/**
* Add a MutationObserver to look for items added/removed from the given menus.
* If they are empty, the container is hidden, otherwise it's unhidden.
* MutationObserver implementation courtesy of LunarTwilight. See https://github.com/wikimedia-gadgets/MoreMenu/pull/1
* @param {String|Array} ids Selector for the menu to observe (a parent of the <ul> element).
*/
function addMutationObserver(ids) {
if ('string' === typeof ids) {
ids = [ids];
}
ids.forEach(id => {
const $parent = $(id);
if (!$parent.length) {
return;
}
const $menu = $parent.find('ul');
const menuIsEmpty = () => '' === $menu.html().trim();
if (menuIsEmpty()) {
$parent.hide();
}
new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.addedNodes.length) {
$parent.show();
} else if (mutation.removedNodes.length) {
if (menuIsEmpty()) {
$parent.hide();
}
}
});
}).observe($menu.get(0), {
childList: true,
});
});
}
/**
* For Vector/Timeless's native More menu, we keep track of how many times it gets populated over time,
* to intelligently determine whether we should leave it upfront to make the script feel more responsive.
*/
function observeCactionsMenu() {
/** Check local storage to see if user continually has items added to the native menu. */
const reAddCount = parseInt(mw.storage.get('mmNativeMenuUsage'), 10) || 0;
/** Ignore for non-Vector/Timeless, if user disabled this feature, or if reAddCount is high. */
if (-1 === ['vector', 'vector-2022', 'timeless'].indexOf(config.currentUser.skin)
|| !!window.MoreMenu.disableAutoRemoval
|| reAddCount >= 5
) {
return;
}
addMutationObserver('#p-cactions');
/** Wait 5 seconds before checking the reAddCount, to give other scripts time to populate the menu */
setTimeout(() => {
if ($('#p-cactions').find('li').length) {
// Set expiry to 24 hours.
mw.storage.set('mmNativeMenuUsage', reAddCount + 1, 60 * 60 * 24);
}
}, 5000);
}
/**
* Remove redundant links from the native More menu, and from the "Page tools" and "Userpage tools" in Timeless.
* This uses mw.storage to keep track of whether the native menu usually gets items added to it
* after MoreMenu has loaded. If this is the case, it will not remove the menu at all. This is to avoid
* the irritating "jumping" effect you get due to race conditions.
*/
function removeNativeLinks() {
const linksToRemove = [
'#ca-protect',
'#ca-unprotect',
'#ca-delete',
'#ca-undelete',
];
if ('timeless' === config.currentUser.skin) {
linksToRemove.push.apply(linksToRemove, [
'#t-contributions',
'#t-log',
'#t-blockip',
'#t-emailuser',
'#t-userrights',
'#t-info',
'#t-pagelog',
]);
}
$(linksToRemove.join(',')).remove();
handleHistoryAndWatchLinks();
observeCactionsMenu();
/** Remove empty userpage tools menu in Timeless */
if ('timeless' === config.currentUser.skin) {
addMutationObserver('#p-userpagetools');
}
}
/**
* Removes the link to the block log if the user has never been blocked.
*/
function removeBlockLogLink() {
api.get({
action: 'query',
list: 'logevents',
letype: 'block',
letitle: `User:${config.targetUser.name}`,
lelimit: 1,
}).done(data => {
if (!data.query.logevents.length) {
$('#mm-user-blocks-view-block-log').remove();
}
});
}
/**
* Remove unneeded links and empty submenus.
*/
function removeUnneededLinks() {
handleHistoryAndWatchLinks(true);
/** Following logic only applies to the User menu. */
if (!config.targetUser.name) {