This repository has been archived by the owner on Aug 26, 2022. It is now read-only.
/
wiki.js
748 lines (637 loc) · 27.1 KB
/
wiki.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
(function(win, doc, $) {
'use strict';
/*
Togglers within articles (i.e.)
*/
$('.toggleable').mozTogglers();
/*
Toggle for quick links show/hide
*/
(function() {
// Set up the quick links for the toggler
var $quickLinks = $('#quick-links');
setupTogglers($quickLinks.find('> ul > li, > ol > li'));
$quickLinks.find('.toggleable').mozTogglers();
var $columnContainer = $('#wiki-column-container');
var $quickLinksControl = $('#wiki-controls .quick-links');
var child = $('#wiki-left').get(0);
if(child) {
var parent = child.parentNode;
}
// Quick Link toggles
$('#quick-links-toggle, #show-quick-links').on('click', function(e) {
e.preventDefault();
$(child).toggleClass('column-closed');
$columnContainer.toggleClass('wiki-left-closed');
$quickLinksControl.toggleClass('hidden');
if($(child).hasClass('column-closed')) {
parent.removeChild(child);
}
else {
parent.appendChild(child);
}
mdn.analytics.trackEvent({
category: 'Wiki',
action: 'Sidebar',
label: (this.id === 'quick-links-toggle' ? 'Hide' : 'Show')
});
});
})();
/*
Set up the zone subnav accordion
*/
$('.subnav').each(function() {
var $subnav = $(this);
var $subnavList = $subnav.find(' > ol');
var minHeightFn = $('.zone-landing-header-preview-base').length ? setMinHeight : noop;
if(!$subnavList.length) return; // Exit if the subnav isn't set up properly
// Set the list items as togglers where needed
setupTogglers($subnavList.find('li'));
// Make them toggleable!
$subnavList.find('.toggleable').mozTogglers({
slideCallback: minHeightFn
});
// Try to find the current page in the list, if found, open it
// Need to keep track of the elements we've found so they aren't found twice
var used = [];
var $selected = $subnavList.find('a[href$="' + doc.location.pathname + '"]');
$selected.each(function() {
var self = this;
var $togglers = $(this).parents('.toggleable').find('.toggler');
$togglers.each(function() {
if($.contains($(this).parent('li').get(0), self) && used.indexOf(this) === -1) {
$(this).trigger('mdn:click');
used.push(this);
}
});
}).parent().addClass('current');
// Mark this is an accordion so the togglers open/close properly
$subnavList.addClass('accordion');
function noop(){}
function setMinHeight() {
if($('.zone-landing-header-preview-base').css('position') === 'absolute') {
$('.wiki-main-content').css('min-height', $subnav.height());
}
}
minHeightFn();
});
/*
Set up the "from search" buttons if user came from search
*/
var fromSearchNav = $('.from-search-navigate');
if(fromSearchNav.length) {
var fromSearchList = $('.from-search-toc');
fromSearchNav.mozMenu({
submenu: fromSearchList,
brickOnClick: true,
onOpen: function(){
mdn.analytics.trackEvent({
category: 'Search doc navigator',
action: 'Open on hover'
});
},
onClose: function() {
mdn.analytics.trackEvent({
category: 'Search doc navigator',
action: 'Close on blur'
});
}
});
fromSearchList.find('ol').mozKeyboardNav();
}
/*
Subscribe / unsubscribe to an article
*/
$('.page-watch a').on('click', function(e) {
e.preventDefault();
var $link = $(this);
if($link.hasClass('disabled')) return;
var $form = $link.closest('form');
var notification = mdn.Notifier.growl($link.data('subscribe-status'), { duration: 0 });
$link.addClass('disabled');
$.ajax($form.attr('action'), {
cache: false,
method: 'post',
data: $form.serialize()
}).done(function(data) {
var message;
data = JSON.parse(data);
if(Number(data.status) === 1) {
$link.text($link.data('unsubscribe-text'));
message = $link.data('subscribe-message');
}
else {
$link.text($link.data('subscribe-text'));
message = $link.data('unsubscribe-message');
}
notification.success(message, 2000);
$link.removeClass('disabled');
});
});
// Utility method for the togglers
function setupTogglers($elements) {
$elements.each(function() {
var $li = $(this);
var $sublist = $li.find('> ul, > ol');
if($sublist.length) {
$li.addClass('toggleable closed');
$li.find('> a').addClass('toggler').prepend('<i aria-hidden="true" class="icon-caret-up"></i>');
$sublist.addClass('toggle-container');
}
});
}
/*
Add icons to external links if they don't have images
*/
$('.external').each(function() {
var $link = $(this);
if(!$link.find('img').length) $link.addClass('external-icon');
});
/*
Syntax highlighting scripts
*/
if($('article pre').length && ('querySelectorAll' in doc)) (function() {
var syntaxScript = doc.createElement('script');
syntaxScript.setAttribute('data-manual', '');
syntaxScript.async = 'true';
syntaxScript.src = mdn.mediaPath + 'js/syntax-prism-min.js?build=' + mdn.build;
doc.body.appendChild(syntaxScript);
})();
/*
Add link to syntax explanations
*/
(function(){
// possible syntax languages and links to resources for reading them
var syntaxSections = {
css: {
link: 'docs/Web/CSS/Value_definition_syntax',
title: gettext('How to read CSS syntax.'),
urlTest: '/docs/Web/CSS/',
classTest: 'brush:css'
},
/* these languages do not have syntax articles yet but it's important
to have the classTest and section tests available when deciding
if there is a matching language for the purposes of creating the
link, adding a link and title later will cause them to be linked */
html: {
urlTest: '/docs/Web/HTML/',
classTest: 'brush:html'
},
js: {
urlTest: '/docs/Web/JavaScript/',
classTest: 'brush:js'
},
api: {
urlTest: '/docs/Web/API/',
classTest: 'brush:js'
}
};
// check if there is any syntax on the page to add links to
var $boxes = $('.syntaxbox, .twopartsyntaxbox');
if($boxes.length) {
/* run the section and page matching logic
- isLinkMatch becomes true if we're already on one of the syntax articles
- sectionMatch becomes the link to a wiki article if we're in a section of
the site that has a matching wiki syntax article
*/
var isLinkMatch = false;
var sectionMatch;
for (var section in syntaxSections) {
var sectionLink = syntaxSections[section].link;
var sectionTest = syntaxSections[section].urlTest;
if(window.location.href.indexOf(sectionLink) > -1) {
isLinkMatch = true;
}
if(window.location.href.indexOf(sectionTest) > -1) {
sectionMatch = syntaxSections[section];
}
}
// if we're not already reading an article on syntax...
if(!isLinkMatch){
// loop through boxes
$boxes.each(function() {
var $thisBox = $(this);
// determine language
var syntaxLanguage;
// pick CSS if it has class twopartsyntaxbox, this should only ever have CSS in it
if($thisBox.hasClass('twopartsyntaxbox')) {
syntaxLanguage = syntaxSections.css;
}
// check if there is a class on the box matching a language (sets to last match)
// overrides .twopartsyntaxbox, that's good
for (var section in syntaxSections) {
var classTest = syntaxSections[section].classTest;
if($thisBox.hasClass(classTest)) {
syntaxLanguage = syntaxSections[section];
}
}
// if we still don't have a match fall back to the language the section is in
if (!syntaxLanguage && sectionMatch) {
syntaxLanguage = sectionMatch;
}
// check we have identified matching help text and links
if(syntaxLanguage) {
// check that we have the objects we need to add the help text for this language
if(syntaxLanguage.link && syntaxLanguage.title) {
var syntaxLink = syntaxLanguage.link;
var syntaxTitle = syntaxLanguage.title;
// add the help text and link to the page
var $helpLink = $('<a href="' + syntaxLink + '" class="syntaxbox-help icon-only" lang="en"><i aria-hidden="true" class="icon-question-sign"></i><span>' + syntaxTitle + '</span></a>');
$thisBox.before($helpLink);
// show help text on mouseover (CSS handles focus)
$thisBox.on('mouseenter', function(){$helpLink.addClass('isOpaque');});
$thisBox.on('mouseleave', function(){$helpLink.removeClass('isOpaque');});
}
}
});
}
}
})();
/*
Set up the scrolling TOC effect
*/
(function() {
var $toc = $('#toc');
var tocOffset = $toc.offset();
var $toggler = $toc.find('> .toggler');
var fixedClass = 'fixed';
var $wikiRight = $('#wiki-right');
var $pageButtons = $('.page-buttons');
var pageButtonsOffset = $pageButtons.offset();
// Get button alignment according to text direction
var buttonDirection = ($('html').attr('dir') === 'rtl') ? 'left' : 'right';
var scrollFn = debounce(function(e) {
var scroll = $(doc).scrollTop();
var pageButtonsHeight = 0;
var $mainContent = $('.wiki-main-content');
if(!e || e.type === 'resize') {
// Calculate right and offset for page buttons on resize and page load
if(buttonDirection === 'right'){
pageButtonsOffset.right = $(win).width() - $mainContent.offset().left - $mainContent.innerWidth();
}
// Should the TOC be one-column (auto-closed) or sidebar'd
if($toc.length){
if($toggler.css('pointer-events') === 'auto' || $toggler.find('i').css('display') !== 'none') { /* icon check is for old IEs that don't support pointer-events */
// Checking "data-clicked" to ensure we don't override closing/opening if user has done so explicitly
if(!$toc.attr('data-closed') && !$toggler.attr('data-clicked')) {
$toggler.trigger('mdn:click');
}
}
else if($toc.attr('data-closed')) { // Changes width, should be opened (i.e. mobile to desktop width)
$toggler.trigger('mdn:click');
}
}
}
// Check if page buttons need to be sticky
if($pageButtons.attr('data-sticky') === 'true'){
pageButtonsHeight = $pageButtons.innerHeight();
if(scroll > pageButtonsOffset.top) {
$pageButtons.css('min-width', $pageButtons.css('width'));
$pageButtons.css(buttonDirection, pageButtonsOffset[buttonDirection]);
$pageButtons.addClass(fixedClass);
} else {
$pageButtons.removeClass(fixedClass);
}
}
// If there is no ToC on the page
if(!$toc.length) return;
// Styling for sticky ToC
var maxHeight = win.innerHeight - parseInt($toc.css('padding-top'), 10) - parseInt($toc.css('padding-bottom'), 10) - pageButtonsHeight;
if(scroll + pageButtonsHeight > tocOffset.top && $toggler.css('pointer-events') === 'none') {
$toc.css({
width: $toc.css('width'),
top: pageButtonsHeight,
maxHeight: maxHeight
});
$toc.addClass(fixedClass);
}
else {
$toc.css({
width: 'auto',
maxHeight: 'none'
});
$toc.removeClass(fixedClass);
}
}, 10);
// Set it forth!
if($toc.length || $pageButtons.attr('data-sticky') === 'true'){
scrollFn();
$(win).on('scroll resize', scrollFn);
}
})();
/*
Compat table table setup
*/
$('.htab').each(function(index) {
var $htab = $(this);
var $items = $htab.find('>ul>li');
$htab.append($('div[id=compat-desktop]')[index]);
$htab.append($('div[id=compat-mobile]')[index]);
$items.find('a').on('click mdn:click', function(e) {
var $this = $(this);
if(e) {
e.preventDefault();
e.stopPropagation();
}
$items.removeClass('selected');
$this.parent().addClass('selected');
$htab.find('>div').hide().eq($items.index($this.parent())).show();
}).eq(0).trigger('mdn:click');
});
/*
Bottom language checker autosubmit
*/
$('.wiki-l10n').on('change', function() {
if(this.value) {
win.location = this.value;
}
});
/*
Adds a context menu to edit page or view history
*/
$('body[contextmenu=edit-history-menu]').mozContextMenu(function(target, $contextMenu) {
var $menuitems = $contextMenu.find('menuitem');
var $body = $('body');
var isTextSelected = !document.getSelection().isCollapsed;
var isLinkTargeted = ($(target).is('a') || $(target).parents().is('a'));
var isImageTargeted = $(target).is('img');
$body.attr('contextmenu', 'edit-history-menu');
if(isLinkTargeted || isTextSelected || isImageTargeted) {
$body.attr('contextmenu', '');
}
$contextMenu.on('click', function(e) {
location.href = (target.href || location.href) + $(e.target).data('action') + '?src=context';
});
});
/*
Toggle kumascript error detail pane
*/
$('.kumascript-detail-toggle').toggleMessage({
toggleCallback: function() {
$('.kumascript-details').toggleClass('hidden');
}
});
/*
Stack overflow search form, used for dev program
ex: http://stackoverflow.com/search?q=[firefox]+or+[firefox-os]+or+[html5-apps]+foobar
*/
$('.stack-form').html('<form action="http://stackoverflow.com/search"><i class="stack-icon" aria-hidden="true"></i><label for="stack-search" class="offscreen">' + gettext('Search Stack Overflow') + '</label><input id="stack-search" placeholder="' + gettext('Search Stack Overflow') + '" /><button type="submit" class="offscreen">Submit Search</button></form>').find('form').on('submit', function(e) {
e.preventDefault();
var value = $(this).find('#stack-search').val();
if(value !== '') {
win.location = 'http://stackoverflow.com/search?q=[firefox]+or+[firefox-os]+or+[html5-apps]+' + value;
}
});
/*
if many contributors, dont show all at once.
*/
(function (){
var hiddenClass = 'hidden';
var $contributors = $('.contributor-avatars');
var $hiddenContributors;
var $showAllContributors;
function loadImages(selector) {
return $contributors.find(selector).mozLazyloadImage();
}
// Start displaying first contributors in list
loadImages('li.shown noscript');
// Setup "Show all Contributors block"
if ($contributors.data('has-hidden')) {
$showAllContributors = $('<button type="button" class="transparent">' + $contributors.data('all-text') + '</button>');
$showAllContributors.on('click', function(e) {
e.preventDefault();
mdn.analytics.trackEvent({
category: 'Top Contributors',
action: 'Show all'
});
// Show all LI elements
$hiddenContributors = $contributors.find('li.' + hiddenClass);
$hiddenContributors.removeClass(hiddenClass);
// Start loading images which were hidden
loadImages('noscript');
// Focus on the first hidden element
$($hiddenContributors.get(0)).find('a').get(0).focus();
// Remove the "Show all" button
$(this).remove();
});
// Inject the show all button
$showAllContributors.appendTo($contributors);
}
// Track clicks on avatars for the sake of Google Analytics tracking
$contributors.on('click', 'a', function(e) {
var newTab = (e.metaKey || e.ctrlKey);
var href = this.href;
var data = {
category: 'Top Contributors',
action: 'Click position',
label: href
};
if (newTab) {
mdn.analytics.trackEvent(data);
} else {
e.preventDefault();
mdn.analytics.trackEvent(data, function() { win.location = href; });
}
});
// Allow focus into and out of the list itself
$contributors.find('ul').on('focusin focusout', function(e) {
$(this)[(e.type === 'focusin' ? 'add' : 'remove') + 'Class']('focused');
});
})();
/*
Bug 981409 - Add some CSS fallback for browsers without MathML support.
This is based on
https://developer.mozilla.org/en-US/docs/Web/MathML/Authoring#Fallback_for_Browsers_without)MathML_support
and https://github.com/fred-wang/mathml.css.
*/
if($('math').length) (function() {
// Test for MathML support
var $div = $('<div class="offscreen"><math xmlns="http://www.w3.org/1998/Math/MathML"><mspace height="23px" width="77px"/></math></div>').appendTo(document.body);
var box = $div.get(0).firstChild.firstChild.getBoundingClientRect();
$div.remove();
var supportsMathML = Math.abs(box.height - 23) <= 1 && Math.abs(box.width - 77) <= 1;
if (!supportsMathML) {
// Add CSS fallback
$('<link href="/media/css/libs/mathml.css" rel="stylesheet" type="text/css" />').appendTo(doc.head);
// Add notification
$('#wikiArticle').prepend('<div class="notice"><p>' + gettext('Your browser does not support MathML. A CSS fallback has been used instead.') + '</p></div>');
}
})();
/*
jQuery extensions used within the wiki.
*/
$.extend({
// Currently used within CKEDitor YouTube plugin
parseQuerystring: function(str){
var nvpair = {};
var qs = (str || location.search).replace('?', '');
var pairs = qs.split('&');
$.each(pairs, function(i, v){
var pair = v.split('=');
nvpair[pair[0]] = pair[1];
});
return nvpair;
},
// Used within the wiki new/move pages
slugifyString: function(str, allowSlash, allowMultipleUnderscores) {
var regex = new RegExp('[?&\"\'#*$' + (allowSlash ? '' : '\/') + ' +?]', 'g');
// Remove anything from the slug that could cause big problems
// "$" is used for verb delimiter in URLs
var result = str.replace(regex, '_').replace(/\$/g, '');
// Don't allow "_____" mess
if(!allowMultipleUnderscores) {
result = result.replace(/_+/g, '_');
}
return result;
}
});
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
/*
Track YouTube videos
*/
(function(){
var $youtubeIframes = $('iframe[src*="youtube.com/embed"]');
var players = [];
var timeoutFlag = 1;
var timer;
function timeout() {
var fraction;
timeoutFlag = 1;
$.each(players, function(index, player) {
if(player.getPlayerState() !== 1) return;
timeoutFlag = 0;
fraction = player.getCurrentTime() / player.getDuration();
if(!player.checkpoint) {
player.checkpoint = 0.1 + Math.round(fraction * 10) / 10;
}
if(fraction > player.checkpoint) {
mdn.analytics.trackEvent({
category: 'YouTube',
action: 'Percent Completed',
label: player.getVideoUrl(),
value: Math.round(player.checkpoint * 100)
});
// 10% checkpoints for analytics
player.checkpoint += 0.1;
}
});
if(timeoutFlag) {
if(timer) clearTimeout(timer);
}else{
timer = setTimeout(timeout, 6000);
}
}
// If the page does not have any YouTube videos
if(!$youtubeIframes.length) return;
var origin = win.location.protocol + '//' + win.location.hostname +
(win.location.port ? ':' + win.location.port: '');
//Enable JS API on all YouTube iframes, might cause flicker!
$youtubeIframes.each(function() {
$(this).attr('src', function(i, src){
return src + (src.split('?')[1] ? '&':'?') + '&enablejsapi=1&origin=' + origin;
});
});
// Load YouTube Iframe API
var youtubeScript = doc.createElement('script');
youtubeScript.async = 'true';
youtubeScript.src = '//www.youtube.com/iframe_api';
doc.body.appendChild(youtubeScript);
// Method executed by YouTube API, needs to be global
win.onYouTubeIframeAPIReady = function(event) {
$youtubeIframes.each(function(i){
players[i] = new YT.Player($(this).get(0));
players[i].addEventListener('onReady', function(){
mdn.analytics.trackEvent({
category: 'YouTube',
action: 'Load',
label: players[i].getVideoUrl()
});
});
players[i].addEventListener('onStateChange', function(event) {
var action;
switch(event.data) {
case 0: // YT.PlayerState.ENDED
action = 'Finished';
break;
case 1: // YT.PlayerState.PLAYING
action = 'Play';
if(timeoutFlag){
timeout();
}
break;
case 2: // YT.PlayerState.PAUSED
action = 'Pause';
break;
case 3: // YT.PlayerState.BUFFERING
action = 'Buffering';
break;
default:
return;
}
mdn.analytics.trackEvent({
category: 'YouTube',
action: action,
label: players[i].getVideoUrl()
});
});
players[i].addEventListener('onPlaybackQualityChange', function(event) {
var value;
//quality is highres, hd1080, hd720, large, medium and small
switch(event.data) {
case 'small':
value = 240;
break;
case 'medium':
value = 360;
break;
case 'large':
value = 480;
break;
case 'hd720':
value = 720;
break;
case 'hd1080':
value = 1080;
break;
case 'highres': //higher than 1080p
value = 1440;
break;
default: //undefined
value = 0;
}
mdn.analytics.trackEvent({
category: 'YouTube',
action: 'Playback Quality',
label: players[i].getVideoUrl(),
value: value
});
});
players[i].addEventListener('onError', function(event) {
mdn.trackError('YouTube Error: ' + event.data + 'on ' + win.location.href);
});
});
};
})();
/*
Manually activate the sticky page button experiment if the page has a
table of contents (the current sticky button implementation has a bug
where it only works on pages that have tables of content).
This will be removed when we finish running the experiment.
*/
if($('#toc').length) {
mdn.optimizely.push(['activate', 2127730778]);
}
})(window, document, jQuery);