-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathfunctions.js
682 lines (591 loc) · 19.6 KB
/
functions.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
// Sliding Panel and scala in a nutshell
$(document).ready(function() {
$('.navigation-panel-button,.navigation-fade-screen,.navigation-panel-close').on('click touchstart', function(e) {
$('.navigation-menu,.navigation-fade-screen').toggleClass('is-visible');
e.preventDefault();
});
var menus = $('.items-menu');
var allContents = $('.items-code');
var allButtons = $('.scala-item');
menus.each(function(index1, row) {
var row = $(row);
var items = row.find('.scala-item');
var content = row.children('.items-content');
var contents = content.children('.items-code');
items.each(function(index2, button) {
var jButton = $(button);
jButton.click(function(event) {
var activeCode = contents.eq(index2);
var others = allContents.not(activeCode);
allButtons.removeClass('active');
others.hide();
if (activeCode.is(":visible")) {
activeCode.hide();
} else {
jButton.addClass('active')
activeCode.show();
}
});
});
});
});
// Tooltip
$(document).ready(function() {
// Tooltip only Text
$('.masterTooltip').hover(function() {
// Hover over code
var title = $(this).attr('title');
$(this).data('tipText', title).removeAttr('title');
$('<p class="tooltip"></p>')
.text(title)
.appendTo('body')
.fadeIn('slow');
}, function() {
// Hover out code
$(this).attr('title', $(this).data('tipText'));
$('.tooltip').remove();
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
$('.tooltip')
.css({
top: mousey,
left: mousex
})
});
});
// Highlight
$(document).ready(function() {
hljs.configure({
languages: ["scala", "bash"],
noHighlightRe: /^hljs-skip$/i
})
hljs.registerLanguage("scala", highlightDotty);
hljs.highlightAll();
});
// Show Blog
$(".hide").click(function() {
$(".new-on-the-blog").hide();
});
// Documentation menu dropdown toggle
$(document).ready(function() { // DOM ready
// If a link has a dropdown, add sub menu toggle.
$('nav ul li a:not(:only-child)').click(function(e) {
// if mobile...
if ($(".navigation-ellipsis").css("display") == "block") {
// toggle the submenu associated with the clicked id
var submenuId = $(this).attr('id');
$(".doc-navigation-submenus #" + submenuId).toggle();
// Close one dropdown when selecting another
$('.navigation-submenu:not(#' + submenuId + ')').hide();
} else { // not mobile
// toggle the dropdown associted with the clicked li element
$(this).siblings('.navigation-dropdown').toggle();
// Close one dropdown when selecting another
$('.navigation-dropdown').not($(this).siblings()).hide();
}
e.stopPropagation();
});
// Clicking away from dropdown will remove the dropdown class
$('html').click(function() {
$('.navigation-dropdown').hide();
$('.navigation-submenu:not(.ellipsis-menu)').hide();
// $('.ellipsis-menu').hide();
});
// expands doc menu on mobile
$('.navigation-ellipsis').click(function(e) {
$(".navigation-submenu.ellipsis-menu").toggle();
});
}); // end DOM ready
// Expand button on cards (guides & overviews page)
$(document).ready(function() {
$.fn.hasOverflow = function() {
var $this = $(this);
var $children = $this.find('*');
var len = $children.length;
if (len) {
var maxWidth = 0;
var maxHeight = 0
$children.map(function() {
maxWidth = Math.max(maxWidth, $(this).outerWidth(true));
maxHeight = Math.max(maxHeight, $(this).outerHeight(true));
});
return maxWidth > $this.width() || (maxHeight + 66) > $this.height();
}
return false;
};
});
// populate language dropdown
$(document).ready(function() {
var old = $("#available-languages");
var items = $("#available-languages li");
var newList = $("#dd .dropdown");
items.each(function(index, value){
newList.append(value);
});
old.empty();
// if there are no translations, hide language dropdown box
if (items.length === 0) {
$("#dd").hide();
}
});
//Tweet feed in frontpage
$('#tweet-feed').tweetMachine('', {
backendScript: '/webscripts/ajax/getFromTwitter.php',
endpoint: 'statuses/user_timeline',
user_name: 'scala_lang',
include_retweets: true,
exclude_replies: false,
limit: 6,
pageLimit: 3,
autoRefresh: false,
animateIn: false,
tweetFormat: `
<div class="item-tweet">
<img src="" class="avatar" alt="">
<div class="tweet-text">
<div class="header-tweet">
<ul>
<li class="user"><a href="" class="userLink"></a></li>
<li class="username"><a href="" class="usernameLink"></a></li>
</ul>
<span class="date"></span>
</div>
<div class="main-tweet"></div>
</div>
</div>
`
}, function(tweets, tweetsDisplayed) {
$('.slider-twitter').unslider({});
});
// Scaladex autocomplete search
var prevResult = "";
var lastElementClicked;
$(document).mousedown(function(e) {
lastElementClicked = $(e.target);
});
$(document).mouseup(function(e) {
lastElementClicked = null;
});
function hideSuggestions() {
$('.autocomplete-suggestions').hide();
$('.autocomplete-suggestion').hide();
}
function showSuggestions() {
$('.autocomplete-suggestions').show();
$('.autocomplete-suggestion').show();
}
hideSuggestions();
$('#scaladex-search').on('input', function(e) {
if ($("#scaladex-search").val() == "") hideSuggestions();
});
$('#scaladex-search').on('focus', function(e) {
if ($("#scaladex-search").val() != "") showSuggestions();
});
$('#scaladex-search').on('blur', function(e) {
if (!$(e.target).is('.autocomplete-suggestion')) {
if (lastElementClicked != null && !lastElementClicked.is('.autocomplete-suggestion')) {
hideSuggestions();
}
} else {
hideSuggestions();
}
});
$('#scaladex-search').autocomplete({
paramName: 'q',
serviceUrl: 'https://index.scala-lang.org/api/autocomplete',
dataType: 'json',
beforeRender: function() {
showSuggestions();
},
onSearchStart: function(query) {
if (query == "") {
hideSuggestions()
} else {
showSuggestions();
}
},
transformResult: function(response) {
return {
suggestions: $.map(response, function(dataItem) {
return {
value: dataItem.repository,
data: 'https://scaladex.scala-lang.org/' + dataItem.organization + "/" + dataItem.repository
};
})
};
},
onSearchComplete: function(query, suggestions) {
suggestions.length > 0 ? showSuggestions() : hideSuggestions();
},
onSelect: function(suggestion) {
if (suggestion.data != prevResult) {
prevResult = suggestion.data;
hideSuggestions();
$("#scaladex-search").blur();
window.open(suggestion.data, '_blank');
}
}
});
$(document).ready(function() {
$(window).on("blur", function() {
if ($("#scaladex-search").length) {
$("#scaladex-search").blur();
$("#scaladex-search").autocomplete().clear();
}
});
});
// TOC:
$(document).ready(function() {
if ($("#sidebar-toc").length) {
$('#toc').toc({
exclude: 'h1, h4, h5, h6',
context: '.toc-context',
autoId: true,
numerate: false
});
const target = $('#sidebar-toc .active');
if (target.length) {
const marginTop = $('#sidebar-toc .type-chapter').length ? 15 : 10;
$('#sidebar-toc').animate({scrollTop: target.position().top - marginTop}, 200);
};
}
});
// Language dropdown
function DropDown(el) {
this.dd = el;
this.placeholder = this.dd.children('span');
this.opts = this.dd.find('ul.dropdown > li');
this.val = '';
this.index = -1;
this.href = '';
this.initEvents();
}
DropDown.prototype = {
initEvents: function() {
var obj = this;
obj.dd.on('click', function(event) {
$(this).toggleClass('active');
return false;
});
obj.opts.on('click', function() {
var opt = $(this);
obj.val = opt.text();
obj.index = opt.index();
obj.placeholder.text(obj.val);
obj.href = opt.find('a').attr("href");
window.location.href = obj.href;
});
},
getValue: function() {
return this.val;
},
getIndex: function() {
return this.index;
}
}
$(function() {
var dd = new DropDown($('#dd'));
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown').removeClass('active');
});
});
// Blog search
$(document).ready(function() {
if ($("#blog-search-bar").length) {
SimpleJekyllSearch({
searchInput: document.getElementById('blog-search-bar'),
resultsContainer: document.getElementById('result-container'),
json: '/resources/json/search.json',
searchResultTemplate: '<li><a href="{url}">{title}</a></li>',
limit: 5,
});
$("#blog-search-bar").on("change paste keyup", function() {
if ($(this).val()) {
$("#result-container").show();
} else {
$("#result-container").hide();
}
});
}
});
// Scala in the browser
$(document).ready(function() {
if ($("#scastie-textarea").length) {
var editor = CodeMirror.fromTextArea(document.getElementById("scastie-textarea"), {
lineNumbers: true,
matchBrackets: true,
theme: "monokai",
mode: "text/x-scala",
autoRefresh: true,
fixedGutter: false
});
editor.setSize("100%", ($("#scastie-code-container").height()));
var codeSnippet = "List(\"Hello\", \"World\").mkString(\"\", \", \", \"!\")";
editor.getDoc().setValue(codeSnippet);
editor.refresh();
$('.btn-run').click(function() {
// TODO: Code to connect to the scastie server would be here, what follows is just a simulation for the UI elements:
$('.btn-run').addClass("inactive");
$('.btn-run i').removeClass("fa fa-play").addClass("fa fa-spinner fa-spin");
setTimeout(function() {
var currentCodeSnippet = editor.getDoc().getValue();
console.log("Current code snippet: " + currentCodeSnippet);
$('.btn-run').removeClass("inactive");
$('.btn-run i').removeClass("fa-spinner fa-spin").addClass("fa fa-play");
}, 2000);
})
}
});
// Browser Storage Support (https://stackoverflow.com/a/41462752/2538602)
function storageAvailable(type) {
try {
var storage = window[type],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch (e) {
return false;
}
}
// Store preference for Scala 2 vs 3
$(document).ready(function() {
const Storage = (namespace) => {
return ({
getPreference(key, defaultValue) {
const res = localStorage.getItem(`${namespace}.${key}`);
return res === null ? defaultValue : res;
},
setPreference(key, value, onChange) {
const old = this.getPreference(key, null);
if (old !== value) { // activate effect only if value changed.
localStorage.setItem(`${namespace}.${key}`, value);
onChange(old);
}
}
});
};
function activateTab(tabs, value) {
// check the code tab corresponding to the preferred value
tabs.find('input[data-target=' + value + ']').prop("checked", true);
}
/** Links all tabs created in Liquid templates with class ".tabs-$namespace"
* on the page together, such that
* changing a tab to some value will activate all other tab sections to
* also change to that value.
* Also records a preference for the tab in localStorage, so
* that when the page is refreshed, the same tab will be selected.
* On page load, selects the tab corresponding to stored value.
*/
function setupTabs(tabs, namespace, defaultValue) {
const PreferenceStorage = Storage('org.scala-lang.docs.preferences');
const preferredValue = PreferenceStorage.getPreference(namespace, defaultValue);
activateTab(tabs, preferredValue)
// setup listeners to record new preferred Scala version.
tabs.find('input').on('change', function() {
// if checked then set the preferred version, and activate the other tabs on page.
if ($(this).is(':checked')) {
const parent = $(this).parent();
const newValue = $(this).data('target');
PreferenceStorage.setPreference(namespace, newValue, oldValue => {
// when we set a new scalaVersion, find scalaVersionTabs except current one
// and activate those tabs.
activateTab(tabs.not(parent), newValue);
});
}
});
}
if (storageAvailable('localStorage')) {
var scalaVersionTabs = $(".tabsection.tabs-scala-version");
if (scalaVersionTabs.length) {
setupTabs(scalaVersionTabs, "scalaVersion", "scala-3");
}
var buildToolTabs = $(".tabsection.tabs-build-tool");
if (buildToolTabs.length) {
setupTabs(buildToolTabs, "buildTool", "scala-cli");
}
}
});
// OS detection
function getOS() {
var osname = "linux";
if (navigator.appVersion.indexOf("Win") != -1) osname = "windows";
if (navigator.appVersion.indexOf("Mac") != -1) osname = "macos";
if (navigator.appVersion.indexOf("Linux") != -1) osname = "linux";
if (navigator.appVersion.indexOf("X11") != -1) osname = "unix";
return osname;
}
$(document).ready(function () {
// for each code snippet area, find the copy button,
// and add a click listener that will copy text from
// the code area to the clipboard
$(".code-snippet-area").each(function () {
var area = this;
$(area).children(".code-snippet-buttons").children("button.copy-button").click(function () {
var code = $(area).children(".code-snippet-display").children("code").text();
window.navigator.clipboard.writeText(code);
});
});
});
$(document).ready(function () {
// click the get-started tab corresponding to the users OS.
var platformOSOptions = $(".tabsection.platform-os-options");
if (platformOSOptions.length) {
var os = getOS();
if (os === 'unix') {
os = 'linux';
}
platformOSOptions.find('input[data-target=' + os + ']').prop("checked", true);
}
});
var image = {
width: 1680,
height: 1100
};
var target = {
x: 1028,
y: 290
};
var pointer = $('#position-marker');
$(document).ready(updatePointer);
$(window).resize(updatePointer);
function updatePointer() {
var windowWidth = $(window).width();
var windowHeight = $(window).height();
var xScale = windowWidth / image.width;
var yScale = windowHeight / image.height;
pointer.css('top', (target.y));
pointer.css('left', (target.x) * xScale);
}
// Glossary search
$(document).ready(function() {
$('#filter-glossary-terms').focus();
$("#filter-glossary-terms").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
// Loop through the comment list
$(".glossary .toc-context > ul li").each(function(){
// If the name of the glossary term does not contain the text phrase fade it out
if (jQuery(this).find("h3").text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Found "+count+" occurrences.").css('visibility', 'visible');
// check if input is empty, and if so, hide filter count
if (!filter.trim()) {
$("#filter-count").css('visibility', 'hidden');
}
});
});
//Footer scroll to top button
$(document).ready(function(){
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('#scroll-to-top-btn').fadeIn();
} else {
$('#scroll-to-top-btn').fadeOut();
}
});
$('#scroll-to-top-btn').click(function(){
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
});
});
//Contributors widget
// see https://stackoverflow.com/a/19200303/4496364
$(document).ready(function () {
let githubApiUrl = 'https://api.github.com/repos/scala/docs.scala-lang/commits';
let identiconsUrl = 'https://github.com/identicons';
/* - we need to transform "/tour/basics.html" to "_ba/tour/basics.md"
* - some files aren't prefixed with underscore, see rootFiles
* - some files are placed in _overviews but rendered to its folder, see overviewsFolders
*/
let rootFiles = ['getting-started', 'learn', 'glossary'];
let overviewsFolders = ['FAQ', 'cheatsheets', 'collections', 'compiler-options',
'core', 'jdk-compatibility', 'macros', 'parallel-collections',
'plugins', 'quasiquotes', 'reflection',
'repl', 'scaladoc', 'tutorials'
];
let thisPageUrl = window.location.pathname;
// chop off beginning slash and ending .html
thisPageUrl = thisPageUrl.substring(1, thisPageUrl.lastIndexOf('.'));
let isRootFile = rootFiles.some(rf => thisPageUrl.startsWith(rf));
let isInOverviewsFolder = overviewsFolders.some(of => thisPageUrl.startsWith(of));
if(isRootFile) {
thisPageUrl = thisPageUrl + '.md';
} else if(thisPageUrl.indexOf("tutorials/FAQ/") == 0) {
thisPageUrl = '_overviews/' + thisPageUrl.substring("tutorials/".length) + '.md';
} else if(isInOverviewsFolder) {
thisPageUrl = '_overviews/'+ thisPageUrl + '.md';
} else if (thisPageUrl.startsWith('scala3/book')) {
thisPageUrl = '_overviews/scala3-book/' + thisPageUrl.substring("scala3/book/".length) + '.md';
} else {
thisPageUrl = '_' + thisPageUrl + '.md';
}
let url = githubApiUrl + '?path=' + thisPageUrl;
$.get(url, function (data, status) {
if(!data || data.length < 1) {
$('.content-contributors').html(''); // clear content
return false; // break
}
let contributorsUnique = [];
data.forEach(commit => {
// add if not already in array
let addedToList = contributorsUnique.find(c => {
let matches = c.authorName == commit.commit.author.name;
if (!matches && commit.author) {
matches = c.authorName == commit.author.login;
}
return matches;
});
if (!addedToList) {
// first set fallback properties
let authorName = commit.commit.author.name;
let authorLink = '';
let authorImageLink = identiconsUrl + '/' + commit.commit.author.name + '.png';
// if author present, fill these preferably
if (commit.author) {
authorName = commit.author.login;
authorLink = commit.author.html_url;
authorImageLink = commit.author.avatar_url;
}
contributorsUnique.push({
'authorName': authorName,
'authorLink': authorLink,
'authorImageLink': authorImageLink
});
}
});
let contributorsHtml = '';
contributorsUnique.forEach(contributor => {
let contributorHtml = '<div>';
contributorHtml += '<img src="' + contributor.authorImageLink + '">';
if (contributor.authorLink)
contributorHtml += '<a href="' + contributor.authorLink + '">' + contributor.authorName + '</a>';
else
contributorHtml += '<a>' + contributor.authorName + '</a>';
contributorHtml += '</div>';
contributorsHtml += contributorHtml;
});
$('#contributors').html(contributorsHtml);
});
});
$(document).ready(function() {
const icon = '<i class="fa fa-link fa-2xs" aria-hidden="true"></i>'
const anchor = '<a class="heading-anchor" aria-hidden="true"></a>'
$('.content-primary.documentation').find('h1, h2, h3, h4, h5, h6').each(function() {
const id = $(this).attr('id');
if (id) {
$(this).append($(anchor).attr('href', '#' + id).html(icon));
}
});
});