refactor(theme/book): Split into modules (#556)

Advantages:
 - Easier to reason about
 - Can easily disable some modules when debugging
 - Shared dependencies are explicit (playpen_text)
 - Enables some fancier things later one (e.g. run `codeSnippets` slightly later, to avoid blocking the page)

I'm aware that `codeSnippets` should be split into the highlighter and the editor, but I'm not sure I understand exactly how they interact so I've left it as it is for now.
This commit is contained in:
Sorin Davidoi 2018-01-21 16:01:57 +01:00 committed by Michael Bryan
parent 9fe19d8f31
commit 05e4157c2e
1 changed files with 359 additions and 354 deletions

View File

@ -1,18 +1,115 @@
var html, sidebar, sidebarLinks, sidebarToggleButton, themeToggleButton, themePopup; // Fix back button cache problem
window.onunload = function () { };
document.addEventListener('DOMContentLoaded', function() { // Global variable, shared between modules
function playpen_text(playpen) {
let code_block = playpen.querySelector("code");
// url if (window.ace && code_block.classList.contains("editable")) {
var url = window.location.pathname; let editor = window.ace.edit(code_block);
return editor.getValue();
} else {
return code_block.textContent;
}
}
// Fix back button cache problem (function codeSnippets() {
window.onunload = function(){}; // Hide Rust code lines prepended with a specific character
var hiding_character = "#";
var request = fetch("https://play.rust-lang.org/meta/crates", {
headers: {
'Content-Type': "application/json",
},
method: 'POST',
mode: 'cors',
});
// Set theme function handle_crate_list_update(playpen_block, playground_crates) {
var theme = store.get('mdbook-theme'); // update the play buttons after receiving the response
if (theme === null || theme === undefined) { theme = 'light'; } update_play_button(playpen_block, playground_crates);
set_theme(theme); // and install on change listener to dynamically update ACE editors
if (window.ace) {
let code_block = playpen_block.querySelector("code");
if (code_block.classList.contains("editable")) {
let editor = window.ace.edit(code_block);
editor.addEventListener("change", function (e) {
update_play_button(playpen_block, playground_crates);
});
}
}
}
// updates the visibility of play button based on `no_run` class and
// used crates vs ones available on http://play.rust-lang.org
function update_play_button(pre_block, playground_crates) {
var play_button = pre_block.querySelector(".play-button");
// skip if code is `no_run`
if (pre_block.querySelector('code').classList.contains("no_run")) {
play_button.classList.add("hidden");
return;
}
// get list of `extern crate`'s from snippet
var txt = playpen_text(pre_block);
var re = /extern\s+crate\s+([a-zA-Z_0-9]+)\s*;/g;
var snippet_crates = [];
while (item = re.exec(txt)) {
snippet_crates.push(item[1]);
}
// check if all used crates are available on play.rust-lang.org
var all_available = snippet_crates.every(function (elem) {
return playground_crates.indexOf(elem) > -1;
});
if (all_available) {
play_button.classList.remove("hidden");
} else {
play_button.classList.add("hidden");
}
}
function run_rust_code(code_block) {
var result_block = code_block.querySelector(".result");
if (!result_block) {
result_block = document.createElement('code');
result_block.className = 'result hljs language-bash';
code_block.append(result_block);
}
let text = playpen_text(code_block);
var params = {
channel: "stable",
mode: "debug",
crateType: "bin",
tests: false,
code: text,
}
if (text.indexOf("#![feature") !== -1) {
params.channel = "nightly";
}
result_block.innerText = "Running...";
var request = fetch("https://play.rust-lang.org/execute", {
headers: {
'Content-Type': "application/json",
},
method: 'POST',
mode: 'cors',
body: JSON.stringify(params)
});
request
.then(function (response) { return response.json(); })
.then(function (response) { result_block.innerText = response.success ? response.stdout : response.stderr; })
.catch(function (error) { result_block.innerText = "Playground communication" + error.message; });
}
// Syntax highlighting Configuration // Syntax highlighting Configuration
hljs.configure({ hljs.configure({
@ -25,161 +122,24 @@ document.addEventListener('DOMContentLoaded', function() {
// blocks or highlightjs will capture events // blocks or highlightjs will capture events
Array Array
.from(document.querySelectorAll('code.editable')) .from(document.querySelectorAll('code.editable'))
.forEach(function(block) { block.classList.remove('language-rust'); }); .forEach(function (block) { block.classList.remove('language-rust'); });
Array Array
.from(document.querySelectorAll('code:not(.editable)')) .from(document.querySelectorAll('code:not(.editable)'))
.forEach(function(block) { hljs.highlightBlock(block); }); .forEach(function (block) { hljs.highlightBlock(block); });
} else { } else {
Array Array
.from(document.querySelectorAll('code')) .from(document.querySelectorAll('code'))
.forEach(function(block) { hljs.highlightBlock(block); }); .forEach(function (block) { hljs.highlightBlock(block); });
} }
// Adding the hljs class gives code blocks the color css // Adding the hljs class gives code blocks the color css
// even if highlighting doesn't apply // even if highlighting doesn't apply
Array Array
.from(document.querySelectorAll('code')) .from(document.querySelectorAll('code'))
.forEach(function(block) { block.classList.add('hljs'); }); .forEach(function (block) { block.classList.add('hljs'); });
var KEY_CODES = { Array.from(document.querySelectorAll("code.language-rust")).forEach(function (block) {
PREVIOUS_KEY: 37,
NEXT_KEY: 39,
ESCAPE_KEY: 27,
};
document.addEventListener('keydown', function (e) {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
switch (e.keyCode) {
case KEY_CODES.NEXT_KEY:
e.preventDefault();
var nextButton = document.querySelector('.nav-chapters.next');
if(nextButton) {
window.location.href = nextButton.href;
}
break;
case KEY_CODES.PREVIOUS_KEY:
e.preventDefault();
var previousButton = document.querySelector('.nav-chapters.previous');
if(previousButton) {
window.location.href = previousButton.href;
}
break;
case KEY_CODES.ESCAPE_KEY:
e.preventDefault();
hideThemes();
break;
}
});
// Interesting DOM Elements
html = document.querySelector('html');
sidebar = document.getElementById("sidebar");
sidebarLinks = document.querySelectorAll('#sidebar a');
sidebarToggleButton = document.getElementById("sidebar-toggle");
themeToggleButton = document.getElementById('theme-toggle');
themePopup = document.getElementById('theme-list');
// Toggle sidebar
sidebarToggleButton.addEventListener('click', sidebarToggle);
// Scroll sidebar to current active section
var activeSection = sidebar.querySelector(".active");
if(activeSection) {
sidebar.scrollTop = activeSection.offsetTop;
}
var firstContact = null;
document.addEventListener('touchstart', function(e) {
firstContact = {
x: e.touches[0].clientX,
time: Date.now()
};
});
document.addEventListener('touchmove', function(e) {
if (!firstContact)
return;
var curX = e.touches[0].clientX;
var xDiff = curX - firstContact.x,
tDiff = Date.now() - firstContact.time;
if (tDiff < 250 && Math.abs(xDiff) >= 150) {
if (xDiff >= 0 && firstContact.x < Math.min(document.body.clientWidth * 0.25, 300))
showSidebar();
else if (xDiff < 0 && curX < 300)
hideSidebar();
firstContact = null;
}
});
// Theme button
themeToggleButton.addEventListener('click', function(){
if (themePopup.style.display === 'block') {
hideThemes();
} else {
showThemes();
}
});
themePopup.addEventListener('click', function(e){
var theme = e.target.id || e.target.parentElement.id;
set_theme(theme);
});
// Hide theme selector popup when clicking outside of it
document.addEventListener('click', function(event){
if(themePopup.style.display === 'block' && !themeToggleButton.contains(event.target) && !themePopup.contains(event.target)) {
hideThemes();
}
});
function set_theme(theme) {
let ace_theme;
if (theme == 'coal' || theme == 'navy') {
document.querySelector("[href='ayu-highlight.css']").disabled = true;
document.querySelector("[href='tomorrow-night.css']").disabled = false;
document.querySelector("[href='highlight.css']").disabled = true;
ace_theme = "ace/theme/tomorrow_night";
} else if (theme == 'ayu') {
document.querySelector("[href='ayu-highlight.css']").disabled = false;
document.querySelector("[href='tomorrow-night.css']").disabled = true;
document.querySelector("[href='highlight.css']").disabled = true;
ace_theme = "ace/theme/tomorrow_night";
} else {
document.querySelector("[href='ayu-highlight.css']").disabled = true;
document.querySelector("[href='tomorrow-night.css']").disabled = true;
document.querySelector("[href='highlight.css']").disabled = false;
ace_theme = "ace/theme/dawn";
}
setTimeout(function() {
document.querySelector('meta[name="theme-color"]').content = getComputedStyle(document.body).backgroundColor;
}, 1);
if (window.ace && window.editors) {
window.editors.forEach(function(editor) {
editor.setTheme(ace_theme);
});
}
store.set('mdbook-theme', theme);
document.body.className = theme;
}
// Hide Rust code lines prepended with a specific character
var hiding_character = "#";
Array.from(document.querySelectorAll("code.language-rust")).forEach(function(block){
var code_block = block; var code_block = block;
var pre_block = block.parentNode; var pre_block = block.parentNode;
@ -188,9 +148,9 @@ document.addEventListener('DOMContentLoaded', function() {
var first_non_hidden_line = false; var first_non_hidden_line = false;
var lines_hidden = false; var lines_hidden = false;
for(var n = 0; n < lines.length; n++){ for (var n = 0; n < lines.length; n++) {
if(lines[n].trim()[0] == hiding_character){ if (lines[n].trim()[0] == hiding_character) {
if(first_non_hidden_line){ if (first_non_hidden_line) {
lines[n] = "<span class=\"hidden\">" + "\n" + lines[n].replace(/(\s*)# ?/, "$1") + "</span>"; lines[n] = "<span class=\"hidden\">" + "\n" + lines[n].replace(/(\s*)# ?/, "$1") + "</span>";
} }
else { else {
@ -198,7 +158,7 @@ document.addEventListener('DOMContentLoaded', function() {
} }
lines_hidden = true; lines_hidden = true;
} }
else if(first_non_hidden_line) { else if (first_non_hidden_line) {
lines[n] = "\n" + lines[n]; lines[n] = "\n" + lines[n];
} }
else { else {
@ -208,7 +168,7 @@ document.addEventListener('DOMContentLoaded', function() {
code_block.innerHTML = lines.join(""); code_block.innerHTML = lines.join("");
// If no lines were hidden, return // If no lines were hidden, return
if(!lines_hidden) { return; } if (!lines_hidden) { return; }
var buttons = document.createElement('div'); var buttons = document.createElement('div');
buttons.className = 'buttons'; buttons.className = 'buttons';
@ -217,7 +177,7 @@ document.addEventListener('DOMContentLoaded', function() {
// add expand button // add expand button
pre_block.prepend(buttons); pre_block.prepend(buttons);
pre_block.querySelector('.buttons').addEventListener('click', function(e) { pre_block.querySelector('.buttons').addEventListener('click', function (e) {
if (e.target.classList.contains('fa-expand')) { if (e.target.classList.contains('fa-expand')) {
var lines = pre_block.querySelectorAll('span.hidden'); var lines = pre_block.querySelectorAll('span.hidden');
@ -225,7 +185,7 @@ document.addEventListener('DOMContentLoaded', function() {
e.target.classList.add('fa-compress'); e.target.classList.add('fa-compress');
e.target.title = 'Hide lines'; e.target.title = 'Hide lines';
Array.from(lines).forEach(function(line) { Array.from(lines).forEach(function (line) {
line.classList.remove('hidden'); line.classList.remove('hidden');
line.classList.add('unhidden'); line.classList.add('unhidden');
}); });
@ -236,7 +196,7 @@ document.addEventListener('DOMContentLoaded', function() {
e.target.classList.add('fa-expand'); e.target.classList.add('fa-expand');
e.target.title = 'Show hidden lines'; e.target.title = 'Show hidden lines';
Array.from(lines).forEach(function(line) { Array.from(lines).forEach(function (line) {
line.classList.remove('unhidden'); line.classList.remove('unhidden');
line.classList.add('hidden'); line.classList.add('hidden');
}); });
@ -244,11 +204,11 @@ document.addEventListener('DOMContentLoaded', function() {
}); });
}); });
Array.from(document.querySelectorAll('pre code')).forEach(function(block) { Array.from(document.querySelectorAll('pre code')).forEach(function (block) {
var pre_block = block.parentNode; var pre_block = block.parentNode;
if( !pre_block.classList.contains('playpen') ) { if (!pre_block.classList.contains('playpen')) {
var buttons = pre_block.querySelector(".buttons"); var buttons = pre_block.querySelector(".buttons");
if(!buttons) { if (!buttons) {
buttons = document.createElement('div'); buttons = document.createElement('div');
buttons.className = 'buttons'; buttons.className = 'buttons';
pre_block.prepend(buttons); pre_block.prepend(buttons);
@ -260,17 +220,14 @@ document.addEventListener('DOMContentLoaded', function() {
clipButton.innerHTML = '<i class=\"tooltiptext\"></i>'; clipButton.innerHTML = '<i class=\"tooltiptext\"></i>';
buttons.prepend(clipButton); buttons.prepend(clipButton);
clipButton.addEventListener('mouseout', function(e){
hideTooltip(e.currentTarget);
});
} }
}); });
// Process playpen code blocks // Process playpen code blocks
Array.from(document.querySelectorAll(".playpen")).forEach(function(pre_block){ Array.from(document.querySelectorAll(".playpen")).forEach(function (pre_block) {
// Add play button // Add play button
var buttons = pre_block.querySelector(".buttons"); var buttons = pre_block.querySelector(".buttons");
if(!buttons) { if (!buttons) {
buttons = document.createElement('div'); buttons = document.createElement('div');
buttons.className = 'buttons'; buttons.className = 'buttons';
pre_block.prepend(buttons); pre_block.prepend(buttons);
@ -289,12 +246,9 @@ document.addEventListener('DOMContentLoaded', function() {
buttons.prepend(runCodeButton); buttons.prepend(runCodeButton);
buttons.prepend(copyCodeClipboardButton); buttons.prepend(copyCodeClipboardButton);
runCodeButton.addEventListener('click', function(e){ runCodeButton.addEventListener('click', function (e) {
run_rust_code(pre_block); run_rust_code(pre_block);
}); });
copyCodeClipboardButton.addEventListener('mouseout', function(e){
hideTooltip(e.currentTarget);
});
let code_block = pre_block.querySelector("code"); let code_block = pre_block.querySelector("code");
if (window.ace && code_block.classList.contains("editable")) { if (window.ace && code_block.classList.contains("editable")) {
@ -304,7 +258,7 @@ document.addEventListener('DOMContentLoaded', function() {
buttons.prepend(undoChangesButton); buttons.prepend(undoChangesButton);
undoChangesButton.addEventListener('click', function() { undoChangesButton.addEventListener('click', function () {
let editor = window.ace.edit(code_block); let editor = window.ace.edit(code_block);
editor.setValue(editor.originalCode); editor.setValue(editor.originalCode);
editor.clearSelection(); editor.clearSelection();
@ -312,195 +266,247 @@ document.addEventListener('DOMContentLoaded', function() {
} }
}); });
var clipboardSnippets = new Clipboard('.clip-button', {
text: function(trigger) {
hideTooltip(trigger);
let playpen = trigger.closest("pre");
return playpen_text(playpen);
}
});
clipboardSnippets.on('success', function(e) {
e.clearSelection();
showTooltip(e.trigger, "Copied!");
});
clipboardSnippets.on('error', function(e) {
showTooltip(e.trigger, "Clipboard error!");
});
var request = fetch("https://play.rust-lang.org/meta/crates", {
headers: {
'Content-Type': "application/json",
},
method: 'POST',
mode: 'cors',
});
request request
.then(function(response) { return response.json(); }) .then(function (response) { return response.json(); })
.then(function(response) { .then(function (response) {
// get list of crates available in the rust playground // get list of crates available in the rust playground
let playground_crates = response.crates.map(function(item) {return item["id"];} ); let playground_crates = response.crates.map(function (item) { return item["id"]; });
Array.from(document.querySelectorAll(".playpen")).forEach(function(block) { Array.from(document.querySelectorAll(".playpen")).forEach(function (block) {
handle_crate_list_update(block, playground_crates); handle_crate_list_update(block, playground_crates);
}); });
}); });
}); })();
function playpen_text(playpen) { (function themes() {
let code_block = playpen.querySelector("code"); var themeToggleButton = document.getElementById('theme-toggle');
var themePopup = document.getElementById('theme-list');
var themeColorMetaTag = document.querySelector('meta[name="theme-color"]');
var stylesheets = {
ayuHighlight: document.querySelector("[href='ayu-highlight.css']"),
tomorrowNight: document.querySelector("[href='tomorrow-night.css']"),
highlight: document.querySelector("[href='highlight.css']"),
};
if (window.ace && code_block.classList.contains("editable")) { function showThemes() {
let editor = window.ace.edit(code_block);
return editor.getValue();
} else {
return code_block.textContent;
}
}
function handle_crate_list_update(playpen_block, playground_crates) {
// update the play buttons after receiving the response
update_play_button(playpen_block, playground_crates);
// and install on change listener to dynamically update ACE editors
if (window.ace) {
let code_block = playpen_block.querySelector("code");
if (code_block.classList.contains("editable")) {
let editor = window.ace.edit(code_block);
editor.addEventListener("change", function(e){
update_play_button(playpen_block, playground_crates);
});
}
}
}
// updates the visibility of play button based on `no_run` class and
// used crates vs ones available on http://play.rust-lang.org
function update_play_button(pre_block, playground_crates) {
var play_button = pre_block.querySelector(".play-button");
// skip if code is `no_run`
if (pre_block.querySelector('code').classList.contains("no_run")) {
play_button.classList.add("hidden");
return;
}
// get list of `extern crate`'s from snippet
var txt = playpen_text(pre_block);
var re = /extern\s+crate\s+([a-zA-Z_0-9]+)\s*;/g;
var snippet_crates = [];
while (item = re.exec(txt)) {
snippet_crates.push(item[1]);
}
// check if all used crates are available on play.rust-lang.org
var all_available = snippet_crates.every(function(elem) {
return playground_crates.indexOf(elem) > -1;
});
if (all_available) {
play_button.classList.remove("hidden");
} else {
play_button.classList.add("hidden");
}
}
function hideTooltip(elem) {
elem.firstChild.innerText="";
elem.className = 'fa fa-copy clip-button';
}
function showTooltip(elem, msg) {
elem.firstChild.innerText=msg;
elem.className = 'fa fa-copy tooltipped';
}
function sidebarToggle() {
var html = document.querySelector("html");
if (html.classList.contains("sidebar-hidden")) {
showSidebar();
} else if (html.classList.contains("sidebar-visible")) {
hideSidebar();
} else {
if (getComputedStyle(sidebar)['transform'] === 'none'){
hideSidebar();
} else {
showSidebar();
}
}
}
function showThemes() {
themePopup.style.display = 'block'; themePopup.style.display = 'block';
themeToggleButton.setAttribute('aria-expanded', true); themeToggleButton.setAttribute('aria-expanded', true);
} }
function hideThemes() { function hideThemes() {
themePopup.style.display = 'none'; themePopup.style.display = 'none';
themeToggleButton.setAttribute('aria-expanded', false); themeToggleButton.setAttribute('aria-expanded', false);
} }
function showSidebar() { function set_theme(theme) {
let ace_theme;
if (theme == 'coal' || theme == 'navy') {
stylesheets.ayuHighlight.disabled = true;
stylesheets.tomorrowNight.disabled = false;
stylesheets.highlight.disabled = true;
ace_theme = "ace/theme/tomorrow_night";
} else if (theme == 'ayu') {
stylesheets.ayuHighlight.disabled = false;
stylesheets.tomorrowNight.disabled = true;
stylesheets.highlight.disabled = true;
ace_theme = "ace/theme/tomorrow_night";
} else {
stylesheets.ayuHighlight.disabled = true;
stylesheets.tomorrowNight.disabled = true;
stylesheets.highlight.disabled = false;
ace_theme = "ace/theme/dawn";
}
setTimeout(function () {
themeColorMetaTag.content = getComputedStyle(document.body).backgroundColor;
}, 1);
if (window.ace && window.editors) {
window.editors.forEach(function (editor) {
editor.setTheme(ace_theme);
});
}
store.set('mdbook-theme', theme);
document.body.className = theme;
}
// Set theme
var theme = store.get('mdbook-theme');
if (theme === null || theme === undefined) { theme = 'light'; }
set_theme(theme);
themeToggleButton.addEventListener('click', function () {
if (themePopup.style.display === 'block') {
hideThemes();
} else {
showThemes();
}
});
themePopup.addEventListener('click', function (e) {
var theme = e.target.id || e.target.parentElement.id;
set_theme(theme);
});
// Hide theme selector popup when clicking outside of it
document.addEventListener('click', function (event) {
if (themePopup.style.display === 'block' && !themeToggleButton.contains(event.target) && !themePopup.contains(event.target)) {
hideThemes();
}
});
document.addEventListener('keydown', function (e) {
switch (e.key) {
case 'Escape':
e.preventDefault();
hideThemes();
break;
}
});
})();
(function sidebar() {
var html = document.querySelector("html");
var sidebar = document.getElementById("sidebar");
var sidebarLinks = document.querySelectorAll('#sidebar a');
var sidebarToggleButton = document.getElementById("sidebar-toggle");
var firstContact = null;
function showSidebar() {
html.classList.remove('sidebar-hidden') html.classList.remove('sidebar-hidden')
html.classList.add('sidebar-visible'); html.classList.add('sidebar-visible');
Array.from(sidebarLinks).forEach(function(link) { Array.from(sidebarLinks).forEach(function (link) {
link.setAttribute('tabIndex', 0); link.setAttribute('tabIndex', 0);
}); });
sidebarToggleButton.setAttribute('aria-expanded', true); sidebarToggleButton.setAttribute('aria-expanded', true);
sidebar.setAttribute('aria-hidden', false); sidebar.setAttribute('aria-hidden', false);
store.set('mdbook-sidebar', 'visible'); store.set('mdbook-sidebar', 'visible');
} }
function hideSidebar() { function hideSidebar() {
html.classList.remove('sidebar-visible') html.classList.remove('sidebar-visible')
html.classList.add('sidebar-hidden'); html.classList.add('sidebar-hidden');
Array.from(sidebarLinks).forEach(function(link) { Array.from(sidebarLinks).forEach(function (link) {
link.setAttribute('tabIndex', -1); link.setAttribute('tabIndex', -1);
}); });
sidebarToggleButton.setAttribute('aria-expanded', false); sidebarToggleButton.setAttribute('aria-expanded', false);
sidebar.setAttribute('aria-hidden', true); sidebar.setAttribute('aria-hidden', true);
store.set('mdbook-sidebar', 'hidden'); store.set('mdbook-sidebar', 'hidden');
}
function run_rust_code(code_block) {
var result_block = code_block.querySelector(".result");
if(!result_block) {
result_block = document.createElement('code');
result_block.className = 'result hljs language-bash';
code_block.append(result_block);
} }
let text = playpen_text(code_block); // Toggle sidebar
sidebarToggleButton.addEventListener('click', function sidebarToggle() {
var params = { if (html.classList.contains("sidebar-hidden")) {
channel: "stable", showSidebar();
mode: "debug", } else if (html.classList.contains("sidebar-visible")) {
crateType: "bin", hideSidebar();
tests: false, } else {
code: text, if (getComputedStyle(sidebar)['transform'] === 'none') {
hideSidebar();
} else {
showSidebar();
} }
if(text.indexOf("#![feature") !== -1) {
params.channel = "nightly";
} }
result_block.innerText = "Running...";
var request = fetch("https://play.rust-lang.org/execute", {
headers: {
'Content-Type': "application/json",
},
method: 'POST',
mode: 'cors',
body: JSON.stringify(params)
}); });
request document.addEventListener('touchstart', function (e) {
.then(function(response) { return response.json(); }) firstContact = {
.then(function(response) { result_block.innerText = response.success ? response.stdout : response.stderr; }) x: e.touches[0].clientX,
.catch(function(error) { result_block.innerText = "Playground communication" + error.message; }); time: Date.now()
} };
});
document.addEventListener('touchmove', function (e) {
if (!firstContact)
return;
var curX = e.touches[0].clientX;
var xDiff = curX - firstContact.x,
tDiff = Date.now() - firstContact.time;
if (tDiff < 250 && Math.abs(xDiff) >= 150) {
if (xDiff >= 0 && firstContact.x < Math.min(document.body.clientWidth * 0.25, 300))
showSidebar();
else if (xDiff < 0 && curX < 300)
hideSidebar();
firstContact = null;
}
});
// Scroll sidebar to current active section
var activeSection = sidebar.querySelector(".active");
if (activeSection) {
sidebar.scrollTop = activeSection.offsetTop;
}
})();
(function chapterNavigation() {
document.addEventListener('keydown', function (e) {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
switch (e.key) {
case 'ArrowRight':
e.preventDefault();
var nextButton = document.querySelector('.nav-chapters.next');
if (nextButton) {
window.location.href = nextButton.href;
}
break;
case 'ArrowLeft':
e.preventDefault();
var previousButton = document.querySelector('.nav-chapters.previous');
if (previousButton) {
window.location.href = previousButton.href;
}
break;
}
});
})();
(function clipboard() {
var clipButtons = document.querySelectorAll('.clip-button');
function hideTooltip(elem) {
elem.firstChild.innerText = "";
elem.className = 'fa fa-copy clip-button';
}
function showTooltip(elem, msg) {
elem.firstChild.innerText = msg;
elem.className = 'fa fa-copy tooltipped';
}
var clipboardSnippets = new Clipboard('.clip-button', {
text: function (trigger) {
hideTooltip(trigger);
let playpen = trigger.closest("pre");
return playpen_text(playpen);
}
});
Array.from(clipButtons).forEach(function (clipButton) {
clipButton.addEventListener('mouseout', function (e) {
hideTooltip(e.currentTarget);
});
});
clipboardSnippets.on('success', function (e) {
e.clearSelection();
showTooltip(e.trigger, "Copied!");
});
clipboardSnippets.on('error', function (e) {
showTooltip(e.trigger, "Clipboard error!");
});
})();
(function autoHideMenu() { (function autoHideMenu() {
var scrollingContainer = document.querySelector('html'); var scrollingContainer = document.querySelector('html');
@ -508,7 +514,7 @@ function run_rust_code(code_block) {
var previousScrollTop = scrollingContainer.scrollTop; var previousScrollTop = scrollingContainer.scrollTop;
document.addEventListener('scroll', function() { document.addEventListener('scroll', function () {
if (menu.classList.contains('folded') && scrollingContainer.scrollTop < previousScrollTop) { if (menu.classList.contains('folded') && scrollingContainer.scrollTop < previousScrollTop) {
menu.classList.remove('folded'); menu.classList.remove('folded');
} else if (!menu.classList.contains('folded') && scrollingContainer.scrollTop > previousScrollTop) { } else if (!menu.classList.contains('folded') && scrollingContainer.scrollTop > previousScrollTop) {
@ -524,6 +530,5 @@ function run_rust_code(code_block) {
} }
previousScrollTop = scrollingContainer.scrollTop; previousScrollTop = scrollingContainer.scrollTop;
hideThemes();
}, { passive: true }); }, { passive: true });
})(); })();