Skip to content

Commit 40f3fd6

Browse files
committed
add JS to remember language preference
1 parent 736822e commit 40f3fd6

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

resources/js/functions.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,78 @@ $(document).ready(function() {
382382
}
383383
});
384384

385+
// Browser Storage Support (https://stackoverflow.com/a/41462752/2538602)
386+
function storageAvailable(type) {
387+
try {
388+
var storage = window[type],
389+
x = '__storage_test__';
390+
storage.setItem(x, x);
391+
storage.removeItem(x);
392+
return true;
393+
}
394+
catch (e) {
395+
return false;
396+
}
397+
}
398+
399+
// Store preference for Scala 2 vs 3
400+
$(document).ready(function() {
401+
402+
const Storage = (namespace) => {
403+
return ({
404+
getPreference(key, defaultValue) {
405+
const res = localStorage.getItem(`${namespace}.${key}`);
406+
return !res ? defaultValue : res;
407+
},
408+
setPreference(key, value, onChange) {
409+
const old = this.getPreference(key, null);
410+
if (old !== value) { // activate effect only if value changed.
411+
localStorage.setItem(`${namespace}.${key}`, value);
412+
onChange(old);
413+
}
414+
}
415+
});
416+
};
417+
418+
function setupScalaVersionTabs(scalaVersionTabs) {
419+
const BookStorage = Storage('org.scala-lang.docs.scala3.book');
420+
const Scala3 = 'scala-3';
421+
const scalaVersion = BookStorage.getPreference('scalaVersion', Scala3);
422+
423+
function activateTab(tabs, scalaVersion) {
424+
// click the code tab corresponding to the preferred Scala version.
425+
tabs.find('input[data-target=' + scalaVersion + ']').prop("checked", true);
426+
}
427+
428+
activateTab(scalaVersionTabs, scalaVersion);
429+
430+
// setup listeners to record new preferred Scala version.
431+
scalaVersionTabs.find('input').on('change', function() {
432+
// if checked then set the preferred version, and activate the other tabs on page.
433+
if ($(this).is(':checked')) {
434+
const parent = $(this).parent();
435+
const scalaVersion = $(this).data('target');
436+
437+
BookStorage.setPreference('scalaVersion', scalaVersion, oldValue => {
438+
// when we set a new scalaVersion, find scalaVersionTabs except current one
439+
// and activate those tabs.
440+
activateTab(scalaVersionTabs.not(parent), scalaVersion);
441+
});
442+
443+
}
444+
445+
});
446+
}
447+
448+
if (storageAvailable('localStorage')) {
449+
var scalaVersionTabs = $(".tabsection.tabs-scala-version");
450+
if (scalaVersionTabs.length) {
451+
setupScalaVersionTabs(scalaVersionTabs);
452+
}
453+
}
454+
455+
});
456+
385457
// OS detection
386458
function getOS() {
387459
var osname = "linux";

0 commit comments

Comments
 (0)