fix(theme): Fix side menu being stuck open and obscuring most of the page (#376)

pull/378/head
simonsan 8 months ago committed by GitHub
parent 675591b4ef
commit 79467dc448
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -23,7 +23,7 @@ site-url = "/patterns/"
git-repository-url = "https://github.com/rust-unofficial/patterns"
git-repository-icon = "fa-github"
edit-url-template = "https://github.com/rust-unofficial/patterns/edit/main/{path}"
additional-css = ["./language-picker.css"]
additional-css = ["theme/css/language-picker.css"]
[output.html.fold]
enable = true
@ -33,3 +33,8 @@ level = 1
editable = false
# [output.linkcheck] # enable the "mdbook-linkcheck" renderer, disabled due to gh-actions
[output.html.redirect]
# Redirects in the form of "old-path" = "new-path", where the new path
# is relative to the old path.
"functional/lenses.html" = "optics.html"

@ -3,6 +3,11 @@
right: 10px;
}
[dir="rtl"] #language-list {
left: 10px;
right: auto;
}
#language-list a {
color: inherit;
}

@ -0,0 +1,26 @@
{{! Move to template code after fixing this issue:
https://github.com/google/mdbook-i18n-helpers/issues/70 }}
<script>
(function () {
// See these pages for details:
// https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls
// https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics
let base = "https://rust-unofficial.github.io/patterns";
{{#if(eq language "en")}}
let canonical_href = `${base}/{{ path }}`;
{{else}}
let canonical_href = `${base}/{{ language }}/{{ path }}`;
{{/if}}
// mdbook gives us a string ending in ".md", we replace it with ".html":
canonical_href = canonical_href.slice(0, -"md".length) + "html";
if (canonical_href.endsWith("/index.html")) {
canonical_href = canonical_href.slice(0, -"index.html".length);
}
let link = document.createElement("link");
link.rel = "canonical";
link.href = canonical_href;
document.head.appendChild(link);
}) ()
</script>

@ -1,5 +1,6 @@
<!DOCTYPE HTML>
<html lang="{{ language }}" class="sidebar-visible no-js {{ default_theme }}">
<html lang="{{ language }}" class="{{ default_theme }}" dir="{{ text_direction }}">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
@ -11,6 +12,7 @@
<base href="{{ base_url }}">
{{/if}}
<!-- Custom HTML head -->
{{> head}}
@ -49,10 +51,13 @@
{{#if mathjax_support}}
<!-- MathJax -->
<script async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
{{/if}}
</head>
<body>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "{{ path_to_root }}";
@ -81,22 +86,29 @@
try { theme = localStorage.getItem('mdbook-theme'); } catch (e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('{{ default_theme }}')
html.classList.add(theme);
html.classList.add('js');
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var html = document.querySelector('html');
var sidebar = 'hidden';
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch (e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
@ -106,17 +118,43 @@
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function (e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
{{> header}}
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky bordered">
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor"
title="Toggle Table of Contents" aria-label="Toggle Table of Contents"
aria-controls="sidebar">
<i class="fa fa-bars"></i>
</button>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme"
aria-label="Change theme" aria-haspopup="true" aria-expanded="false"
aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
@ -127,7 +165,9 @@
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
{{#if search_enabled}}
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)"
aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S"
aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
{{/if}}
@ -136,9 +176,8 @@
<h1 class="menu-title">{{ book_title }}</h1>
<div class="right-buttons">
<button id="language-toggle" class="icon-button" type="button"
title="Change language" aria-label="Change language"
aria-haspopup="true" aria-expanded="false"
<button id="language-toggle" class="icon-button" type="button" title="Change language"
aria-label="Change language" aria-haspopup="true" aria-expanded="false"
aria-controls="language-list">
<i class="fa fa-globe"></i>
</button>
@ -161,7 +200,9 @@
langList.style.display = langList.style.display == "block" ? "none" : "block";
});
let selectedLang = document.getElementById("{{ language }}");
if (selectedLang) {
selectedLang.parentNode.classList.add("theme-selected");
}
// The path to the root, taking the current
// language into account.
@ -194,12 +235,13 @@
{{/if}}
{{#if git_repository_edit_url}}
{{#if (eq language "en")}}
<a href="{{git_repository_edit_url}}" title="Suggest an edit" aria-label="Suggest an edit">
<a href="{{git_repository_edit_url}}" title="Suggest an edit" aria-label="Suggest an edit"
target="_blank">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
{{else}}
<a href="https://github.com/rust-unofficial/patterns/edit/main/po/{{language}}.po"
title="Suggest an edit to the translation" aria-label="Suggest an edit to the translation">
title="Suggest an edit to the translation" aria-label="Suggest an edit to the translation" target="_blank">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
{{/if}}
@ -211,7 +253,8 @@
{{#if search_enabled}}
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..."
aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
@ -238,13 +281,15 @@
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
{{#previous}}
<a rel="prev" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<a rel="prev" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters previous"
title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
{{/previous}}
{{#next}}
<a rel="next" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<a rel="next" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters next"
title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
{{/next}}
@ -256,13 +301,15 @@
<nav class="nav-wide-wrapper" aria-label="Page navigation">
{{#previous}}
<a rel="prev" href="{{ path_to_root }}{{link}}" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<a rel="prev" href="{{ path_to_root }}{{link}}" class="nav-chapters previous" title="Previous chapter"
aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
{{/previous}}
{{#next}}
<a rel="next" href="{{ path_to_root }}{{link}}" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<a rel="next" href="{{ path_to_root }}{{link}}" class="nav-chapters next" title="Next chapter"
aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
{{/next}}
@ -297,8 +344,10 @@
// make sure we don't activate google analytics if the developer is
// inspecting the book locally...
if (localAddrs.indexOf(document.location.hostname) === -1) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
@ -361,5 +410,7 @@
{{/if}}
{{/if}}
</div>
</body>
</html>

@ -31,7 +31,9 @@ function playground_text(playground, hidden = true) {
function fetch_with_timeout(url, options, timeout = 15000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout))
new Promise((_, reject) =>
setTimeout(() => reject(new Error("timeout")), timeout)
),
]);
}
@ -39,16 +41,18 @@ function playground_text(playground, hidden = true) {
if (playgrounds.length > 0) {
fetch_with_timeout("https://play.rust-lang.org/meta/crates", {
headers: {
'Content-Type': "application/json",
"Content-Type": "application/json",
},
method: 'POST',
mode: 'cors',
method: "POST",
mode: "cors",
})
.then(response => response.json())
.then(response => {
.then((response) => response.json())
.then((response) => {
// get list of crates available in the rust playground
let playground_crates = response.crates.map(item => item["id"]);
playgrounds.forEach(block => handle_crate_list_update(block, playground_crates));
let playground_crates = response.crates.map((item) => item["id"]);
playgrounds.forEach((block) =>
handle_crate_list_update(block, playground_crates)
);
});
}
@ -69,21 +73,21 @@ function playground_text(playground, hidden = true) {
name: "run",
bindKey: {
win: "Ctrl-Enter",
mac: "Ctrl-Enter"
mac: "Ctrl-Enter",
},
exec: _editor => run_rust_code(playground_block)
exec: (_editor) => run_rust_code(playground_block),
});
}
}
}
// updates the visibility of play button based on `no_run` class and
// used crates vs ones available on http://play.rust-lang.org
// used crates vs ones available on https://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")) {
if (pre_block.querySelector("code").classList.contains("no_run")) {
play_button.classList.add("hidden");
return;
}
@ -93,7 +97,7 @@ function playground_text(playground, hidden = true) {
var re = /extern\s+crate\s+([a-zA-Z_0-9]+)\s*;/g;
var snippet_crates = [];
var item;
while (item = re.exec(txt)) {
while ((item = re.exec(txt))) {
snippet_crates.push(item[1]);
}
@ -112,14 +116,14 @@ function playground_text(playground, hidden = true) {
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';
result_block = document.createElement("code");
result_block.className = "result hljs language-bash";
code_block.append(result_block);
}
let text = playground_text(code_block);
let classes = code_block.querySelector('code').classList;
let classes = code_block.querySelector("code").classList;
let edition = "2015";
if (classes.contains("edition2018")) {
edition = "2018";
@ -130,7 +134,7 @@ function playground_text(playground, hidden = true) {
version: "stable",
optimize: "0",
code: text,
edition: edition
edition: edition,
};
if (text.indexOf("#![feature") !== -1) {
@ -143,22 +147,22 @@ function playground_text(playground, hidden = true) {
const startTime = window.performance.now();
fetch_with_timeout("https://play.rust-lang.org/evaluate.json", {
headers: {
'Content-Type': "application/json",
"Content-Type": "application/json",
},
method: 'POST',
mode: 'cors',
body: JSON.stringify(params)
method: "POST",
mode: "cors",
body: JSON.stringify(params),
})
.then(response => response.json())
.then(response => {
.then((response) => response.json())
.then((response) => {
const endTime = window.performance.now();
gtag("event", "playground", {
"modified": playgroundModified,
"error": (response.error == null) ? null : 'compilation_error',
"latency": (endTime - startTime) / 1000,
modified: playgroundModified,
error: response.error == null ? null : "compilation_error",
latency: (endTime - startTime) / 1000,
});
if (response.result.trim() === '') {
if (response.result.trim() === "") {
result_block.innerText = "No output";
result_block.classList.add("result-no-output");
} else {
@ -166,96 +170,111 @@ function playground_text(playground, hidden = true) {
result_block.classList.remove("result-no-output");
}
})
.catch(error => {
.catch((error) => {
const endTime = window.performance.now();
gtag("event", "playground", {
"modified": playgroundModified,
"error": error.message,
"latency": (endTime - startTime) / 1000,
modified: playgroundModified,
error: error.message,
latency: (endTime - startTime) / 1000,
});
result_block.innerText = "Playground Communication: " + error.message
result_block.innerText = "Playground Communication: " + error.message;
});
}
// Syntax highlighting Configuration
hljs.configure({
tabReplace: ' ', // 4 spaces
tabReplace: " ", // 4 spaces
languages: [], // Languages used for auto-detection
});
let code_nodes = Array
.from(document.querySelectorAll('code'))
let code_nodes = Array.from(document.querySelectorAll("code"))
// Don't highlight `inline code` blocks in headers.
.filter(function (node) {return !node.parentElement.classList.contains("header"); });
.filter(function (node) {
return !node.parentElement.classList.contains("header");
});
if (window.ace) {
// language-rust class needs to be removed for editable
// blocks or highlightjs will capture events
code_nodes
.filter(function (node) {return node.classList.contains("editable"); })
.forEach(function (block) { block.classList.remove('language-rust'); });
.filter(function (node) {
return node.classList.contains("editable");
})
.forEach(function (block) {
block.classList.remove("language-rust");
});
code_nodes
.filter(function (node) {return !node.classList.contains("editable"); })
.forEach(function (block) { hljs.highlightBlock(block); });
.filter(function (node) {
return !node.classList.contains("editable");
})
.forEach(function (block) {
hljs.highlightBlock(block);
});
} else {
code_nodes.forEach(function (block) { hljs.highlightBlock(block); });
code_nodes.forEach(function (block) {
hljs.highlightBlock(block);
});
}
// Adding the hljs class gives code blocks the color css
// even if highlighting doesn't apply
code_nodes.forEach(function (block) { block.classList.add('hljs'); });
Array.from(document.querySelectorAll("code.language-rust")).forEach(function (block) {
code_nodes.forEach(function (block) {
block.classList.add("hljs");
});
var lines = Array.from(block.querySelectorAll('.boring'));
Array.from(document.querySelectorAll("code.hljs")).forEach(function (block) {
var lines = Array.from(block.querySelectorAll(".boring"));
// If no lines were hidden, return
if (!lines.length) { return; }
if (!lines.length) {
return;
}
block.classList.add("hide-boring");
var buttons = document.createElement('div');
buttons.className = 'buttons';
buttons.innerHTML = "<button class=\"fa fa-eye\" title=\"Show hidden lines\" aria-label=\"Show hidden lines\"></button>";
var buttons = document.createElement("div");
buttons.className = "buttons";
buttons.innerHTML =
'<button class="fa fa-eye" title="Show hidden lines" aria-label="Show hidden lines"></button>';
// add expand button
var pre_block = block.parentNode;
pre_block.insertBefore(buttons, pre_block.firstChild);
pre_block.querySelector('.buttons').addEventListener('click', function (e) {
if (e.target.classList.contains('fa-eye')) {
e.target.classList.remove('fa-eye');
e.target.classList.add('fa-eye-slash');
e.target.title = 'Hide lines';
e.target.setAttribute('aria-label', e.target.title);
pre_block.querySelector(".buttons").addEventListener("click", function (e) {
if (e.target.classList.contains("fa-eye")) {
e.target.classList.remove("fa-eye");
e.target.classList.add("fa-eye-slash");
e.target.title = "Hide lines";
e.target.setAttribute("aria-label", e.target.title);
block.classList.remove('hide-boring');
} else if (e.target.classList.contains('fa-eye-slash')) {
e.target.classList.remove('fa-eye-slash');
e.target.classList.add('fa-eye');
e.target.title = 'Show hidden lines';
e.target.setAttribute('aria-label', e.target.title);
block.classList.remove("hide-boring");
} else if (e.target.classList.contains("fa-eye-slash")) {
e.target.classList.remove("fa-eye-slash");
e.target.classList.add("fa-eye");
e.target.title = "Show hidden lines";
e.target.setAttribute("aria-label", e.target.title);
block.classList.add('hide-boring');
block.classList.add("hide-boring");
}
});
});
if (window.playground_copyable) {
Array.from(document.querySelectorAll('pre code')).forEach(function (block) {
Array.from(document.querySelectorAll("pre code")).forEach(function (block) {
var pre_block = block.parentNode;
if (!pre_block.classList.contains('playground')) {
if (!pre_block.classList.contains("playground")) {
var buttons = pre_block.querySelector(".buttons");
if (!buttons) {
buttons = document.createElement('div');
buttons.className = 'buttons';
buttons = document.createElement("div");
buttons.className = "buttons";
pre_block.insertBefore(buttons, pre_block.firstChild);
}
var clipButton = document.createElement('button');
clipButton.className = 'fa fa-copy clip-button';
clipButton.title = 'Copy to clipboard';
clipButton.setAttribute('aria-label', clipButton.title);
clipButton.innerHTML = '<i class=\"tooltiptext\"></i>';
var clipButton = document.createElement("button");
clipButton.className = "fa fa-copy clip-button";
clipButton.title = "Copy to clipboard";
clipButton.setAttribute("aria-label", clipButton.title);
clipButton.innerHTML = '<i class="tooltiptext"></i>';
buttons.insertBefore(clipButton, buttons.firstChild);
}
@ -263,46 +282,51 @@ function playground_text(playground, hidden = true) {
}
// Process playground code blocks
Array.from(document.querySelectorAll(".playground")).forEach(function (pre_block) {
Array.from(document.querySelectorAll(".playground")).forEach(function (
pre_block
) {
// Add play button
var buttons = pre_block.querySelector(".buttons");
if (!buttons) {
buttons = document.createElement('div');
buttons.className = 'buttons';
buttons = document.createElement("div");
buttons.className = "buttons";
pre_block.insertBefore(buttons, pre_block.firstChild);
}
var runCodeButton = document.createElement('button');
runCodeButton.className = 'fa fa-play play-button';
var runCodeButton = document.createElement("button");
runCodeButton.className = "fa fa-play play-button";
runCodeButton.hidden = true;
runCodeButton.title = 'Run this code';
runCodeButton.setAttribute('aria-label', runCodeButton.title);
runCodeButton.title = "Run this code";
runCodeButton.setAttribute("aria-label", runCodeButton.title);
buttons.insertBefore(runCodeButton, buttons.firstChild);
runCodeButton.addEventListener('click', function (e) {
runCodeButton.addEventListener("click", function (e) {
run_rust_code(pre_block);
});
if (window.playground_copyable) {
var copyCodeClipboardButton = document.createElement('button');
copyCodeClipboardButton.className = 'fa fa-copy clip-button';
var copyCodeClipboardButton = document.createElement("button");
copyCodeClipboardButton.className = "fa fa-copy clip-button";
copyCodeClipboardButton.innerHTML = '<i class="tooltiptext"></i>';
copyCodeClipboardButton.title = 'Copy to clipboard';
copyCodeClipboardButton.setAttribute('aria-label', copyCodeClipboardButton.title);
copyCodeClipboardButton.title = "Copy to clipboard";
copyCodeClipboardButton.setAttribute(
"aria-label",
copyCodeClipboardButton.title
);
buttons.insertBefore(copyCodeClipboardButton, buttons.firstChild);
}
let code_block = pre_block.querySelector("code");
if (window.ace && code_block.classList.contains("editable")) {
var undoChangesButton = document.createElement('button');
undoChangesButton.className = 'fa fa-history reset-button';
undoChangesButton.title = 'Undo changes';
undoChangesButton.setAttribute('aria-label', undoChangesButton.title);
var undoChangesButton = document.createElement("button");
undoChangesButton.className = "fa fa-history reset-button";
undoChangesButton.title = "Undo changes";
undoChangesButton.setAttribute("aria-label", undoChangesButton.title);
buttons.insertBefore(undoChangesButton, buttons.firstChild);
undoChangesButton.addEventListener('click', function () {
undoChangesButton.addEventListener("click", function () {
let editor = window.ace.edit(code_block);
editor.setValue(editor.originalCode);
editor.clearSelection();
@ -312,9 +336,9 @@ function playground_text(playground, hidden = true) {
})();
(function themes() {
var html = document.querySelector('html');
var themeToggleButton = document.getElementById('theme-toggle');
var themePopup = document.getElementById('theme-list');
var html = document.querySelector("html");
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']"),
@ -323,27 +347,31 @@ function playground_text(playground, hidden = true) {
};
function showThemes() {
themePopup.style.display = 'block';
themeToggleButton.setAttribute('aria-expanded', true);
themePopup.style.display = "block";
themeToggleButton.setAttribute("aria-expanded", true);
themePopup.querySelector("button#" + get_theme()).focus();
}
function updateThemeSelected() {
themePopup.querySelectorAll('.theme-selected').forEach(function (el) {
el.classList.remove('theme-selected');
themePopup.querySelectorAll(".theme-selected").forEach(function (el) {
el.classList.remove("theme-selected");
});
themePopup.querySelector("button#" + get_theme()).classList.add('theme-selected');
themePopup
.querySelector("button#" + get_theme())
.classList.add("theme-selected");
}
function hideThemes() {
themePopup.style.display = 'none';
themeToggleButton.setAttribute('aria-expanded', false);
themePopup.style.display = "none";
themeToggleButton.setAttribute("aria-expanded", false);
themeToggleButton.focus();
}
function get_theme() {
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch (e) { }
try {
theme = localStorage.getItem("mdbook-theme");
} catch (e) {}
if (theme === null || theme === undefined) {
return default_theme;
} else {
@ -354,13 +382,13 @@ function playground_text(playground, hidden = true) {
function set_theme(theme, store = true) {
let ace_theme;
if (theme == 'coal' || theme == 'navy') {
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') {
} else if (theme == "ayu") {
stylesheets.ayuHighlight.disabled = false;
stylesheets.tomorrowNight.disabled = true;
stylesheets.highlight.disabled = true;
@ -373,7 +401,9 @@ function playground_text(playground, hidden = true) {
}
setTimeout(function () {
themeColorMetaTag.content = getComputedStyle(document.body).backgroundColor;
themeColorMetaTag.content = getComputedStyle(
document.documentElement
).backgroundColor;
}, 1);
if (window.ace && window.editors) {
@ -385,7 +415,9 @@ function playground_text(playground, hidden = true) {
var previousTheme = get_theme();
if (store) {
try { localStorage.setItem('mdbook-theme', theme); } catch (e) { }
try {
localStorage.setItem("mdbook-theme", theme);
} catch (e) {}
}
html.classList.remove(previousTheme);
@ -398,15 +430,15 @@ function playground_text(playground, hidden = true) {
set_theme(theme, false);
themeToggleButton.addEventListener('click', function () {
if (themePopup.style.display === 'block') {
themeToggleButton.addEventListener("click", function () {
if (themePopup.style.display === "block") {
hideThemes();
} else {
showThemes();
}
});
themePopup.addEventListener('click', function (e) {
themePopup.addEventListener("click", function (e) {
var theme;
if (e.target.className === "theme") {
theme = e.target.id;
@ -418,50 +450,62 @@ function playground_text(playground, hidden = true) {
set_theme(theme);
});
themePopup.addEventListener('focusout', function(e) {
themePopup.addEventListener("focusout", function (e) {
// e.relatedTarget is null in Safari and Firefox on macOS (see workaround below)
if (!!e.relatedTarget && !themeToggleButton.contains(e.relatedTarget) && !themePopup.contains(e.relatedTarget)) {
if (
!!e.relatedTarget &&
!themeToggleButton.contains(e.relatedTarget) &&
!themePopup.contains(e.relatedTarget)
) {
hideThemes();
}
});
// Should not be needed, but it works around an issue on macOS & iOS: https://github.com/rust-lang/mdBook/issues/628
document.addEventListener('click', function(e) {
if (themePopup.style.display === 'block' && !themeToggleButton.contains(e.target) && !themePopup.contains(e.target)) {
document.addEventListener("click", function (e) {
if (
themePopup.style.display === "block" &&
!themeToggleButton.contains(e.target) &&
!themePopup.contains(e.target)
) {
hideThemes();
}
});
document.addEventListener('keydown', function (e) {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
if (!themePopup.contains(e.target)) { return; }
document.addEventListener("keydown", function (e) {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
return;
}
if (!themePopup.contains(e.target)) {
return;
}
switch (e.key) {
case 'Escape':
case "Escape":
e.preventDefault();
hideThemes();
break;
case 'ArrowUp':
case "ArrowUp":
e.preventDefault();
var li = document.activeElement.parentElement;
if (li && li.previousElementSibling) {
li.previousElementSibling.querySelector('button').focus();
li.previousElementSibling.querySelector("button").focus();
}
break;
case 'ArrowDown':
case "ArrowDown":
e.preventDefault();
var li = document.activeElement.parentElement;
if (li && li.nextElementSibling) {
li.nextElementSibling.querySelector('button').focus();
li.nextElementSibling.querySelector("button").focus();
}
break;
case 'Home':
case "Home":
e.preventDefault();
themePopup.querySelector('li:first-child button').focus();
themePopup.querySelector("li:first-child button").focus();
break;
case 'End':
case "End":
e.preventDefault();
themePopup.querySelector('li:last-child button').focus();
themePopup.querySelector("li:last-child button").focus();
break;
}
});
@ -470,57 +514,62 @@ function playground_text(playground, hidden = true) {
(function sidebar() {
var html = document.querySelector("html");
var sidebar = document.getElementById("sidebar");
var sidebarLinks = document.querySelectorAll('#sidebar a');
var sidebarLinks = document.querySelectorAll("#sidebar a");
var sidebarToggleButton = document.getElementById("sidebar-toggle");
var sidebarResizeHandle = document.getElementById("sidebar-resize-handle");
var firstContact = null;
function showSidebar() {
html.classList.remove('sidebar-hidden')
html.classList.add('sidebar-visible');
html.classList.remove("sidebar-hidden");
html.classList.add("sidebar-visible");
Array.from(sidebarLinks).forEach(function (link) {
link.setAttribute('tabIndex', 0);
link.setAttribute("tabIndex", 0);
});
sidebarToggleButton.setAttribute('aria-expanded', true);
sidebar.setAttribute('aria-hidden', false);
try { localStorage.setItem('mdbook-sidebar', 'visible'); } catch (e) { }
sidebarToggleButton.setAttribute("aria-expanded", true);
sidebar.setAttribute("aria-hidden", false);
try {
localStorage.setItem("mdbook-sidebar", "visible");
} catch (e) {}
}
var sidebarAnchorToggles = document.querySelectorAll('#sidebar a.toggle');
var sidebarAnchorToggles = document.querySelectorAll("#sidebar a.toggle");
function toggleSection(ev) {
ev.currentTarget.parentElement.classList.toggle('expanded');
ev.currentTarget.parentElement.classList.toggle("expanded");
}
Array.from(sidebarAnchorToggles).forEach(function (el) {
el.addEventListener('click', toggleSection);
el.addEventListener("click", toggleSection);
});
function hideSidebar() {
html.classList.remove('sidebar-visible')
html.classList.add('sidebar-hidden');
html.classList.remove("sidebar-visible");
html.classList.add("sidebar-hidden");
Array.from(sidebarLinks).forEach(function (link) {
link.setAttribute('tabIndex', -1);
link.setAttribute("tabIndex", -1);
});
sidebarToggleButton.setAttribute('aria-expanded', false);
sidebar.setAttribute('aria-hidden', true);
try { localStorage.setItem('mdbook-sidebar', 'hidden'); } catch (e) { }
sidebarToggleButton.setAttribute("aria-expanded", false);
sidebar.setAttribute("aria-hidden", true);
try {
localStorage.setItem("mdbook-sidebar", "hidden");
} catch (e) {}
}
// Toggle sidebar
sidebarToggleButton.addEventListener('click', function sidebarToggle() {
sidebarToggleButton.addEventListener("click", function sidebarToggle() {
if (html.classList.contains("sidebar-hidden")) {
var current_width = parseInt(
document.documentElement.style.getPropertyValue('--sidebar-width'), 10);
document.documentElement.style.getPropertyValue("--sidebar-width"),
10
);
if (current_width < 150) {
document.documentElement.style.setProperty('--sidebar-width', '150px');
document.documentElement.style.setProperty("--sidebar-width", "150px");
}
showSidebar();
} else if (html.classList.contains("sidebar-visible")) {
hideSidebar();
} else {
if (getComputedStyle(sidebar)['transform'] === 'none') {
if (getComputedStyle(sidebar)["transform"] === "none") {
hideSidebar();
} else {
showSidebar();
@ -528,15 +577,15 @@ function playground_text(playground, hidden = true) {
}
});
sidebarResizeHandle.addEventListener('mousedown', initResize, false);
sidebarResizeHandle.addEventListener("mousedown", initResize, false);
function initResize(e) {
window.addEventListener('mousemove', resize, false);
window.addEventListener('mouseup', stopResize, false);
html.classList.add('sidebar-resizing');
window.addEventListener("mousemove", resize, false);
window.addEventListener("mouseup", stopResize, false);
html.classList.add("sidebar-resizing");
}
function resize(e) {
var pos = (e.clientX - sidebar.offsetLeft);
var pos = e.clientX - sidebar.offsetLeft;
if (pos < 20) {
hideSidebar();
} else {
@ -544,65 +593,71 @@ function playground_text(playground, hidden = true) {
showSidebar();
}
pos = Math.min(pos, window.innerWidth - 100);
document.documentElement.style.setProperty('--sidebar-width', pos + 'px');
document.documentElement.style.setProperty("--sidebar-width", pos + "px");
}
}
//on mouseup remove windows functions mousemove & mouseup
function stopResize(e) {
html.classList.remove('sidebar-resizing');
window.removeEventListener('mousemove', resize, false);
window.removeEventListener('mouseup', stopResize, false);
html.classList.remove("sidebar-resizing");
window.removeEventListener("mousemove", resize, false);
window.removeEventListener("mouseup", stopResize, false);
}
document.addEventListener('touchstart', function (e) {
document.addEventListener(
"touchstart",
function (e) {
firstContact = {
x: e.touches[0].clientX,
time: Date.now()
time: Date.now(),
};
}, { passive: true });
},
{ passive: true }
);
document.addEventListener('touchmove', function (e) {
if (!firstContact)
return;
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))
if (
xDiff >= 0 &&
firstContact.x < Math.min(document.body.clientWidth * 0.25, 300)
)
showSidebar();
else if (xDiff < 0 && curX < 300)
hideSidebar();
else if (xDiff < 0 && curX < 300) hideSidebar();
firstContact = null;
}
}, { passive: true });
// Scroll sidebar to current active section
var activeSection = document.getElementById("sidebar").querySelector(".active");
if (activeSection) {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
activeSection.scrollIntoView({ block: 'center' });
}
},
{ passive: true }
);
})();
(function chapterNavigation() {
document.addEventListener('keydown', function (e) {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
if (window.search && window.search.hasFocus()) { return; }
document.addEventListener("keydown", function (e) {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
return;
}
if (window.search && window.search.hasFocus()) {
return;
}
switch (e.key) {
case 'ArrowRight':
case "ArrowRight":
e.preventDefault();
var nextButton = document.querySelector('.nav-chapters.next');
var nextButton = document.querySelector(".nav-chapters.next");
if (nextButton) {
window.location.href = nextButton.href;
}
break;
case 'ArrowLeft':
case "ArrowLeft":
e.preventDefault();
var previousButton = document.querySelector('.nav-chapters.previous');
var previousButton = document.querySelector(".nav-chapters.previous");
if (previousButton) {
window.location.href = previousButton.href;
}
@ -612,64 +667,66 @@ function playground_text(playground, hidden = true) {
})();
(function clipboard() {
var clipButtons = document.querySelectorAll('.clip-button');
var clipButtons = document.querySelectorAll(".clip-button");
function hideTooltip(elem) {
elem.firstChild.innerText = "";
elem.className = 'fa fa-copy clip-button';
elem.className = "fa fa-copy clip-button";
}
function showTooltip(elem, msg) {
elem.firstChild.innerText = msg;
elem.className = 'fa fa-copy tooltipped';
elem.className = "fa fa-copy tooltipped";
}
var clipboardSnippets = new ClipboardJS('.clip-button', {
var clipboardSnippets = new ClipboardJS(".clip-button", {
text: function (trigger) {
hideTooltip(trigger);
let playground = trigger.closest("pre");
return playground_text(playground, false);
}
},
});
Array.from(clipButtons).forEach(function (clipButton) {
clipButton.addEventListener('mouseout', function (e) {
clipButton.addEventListener("mouseout", function (e) {
hideTooltip(e.currentTarget);
});
});
clipboardSnippets.on('success', function (e) {
clipboardSnippets.on("success", function (e) {
e.clearSelection();
showTooltip(e.trigger, "Copied!");
});
clipboardSnippets.on('error', function (e) {
clipboardSnippets.on("error", function (e) {
showTooltip(e.trigger, "Clipboard error!");
});
})();
(function scrollToTop() {
var menuTitle = document.querySelector('.menu-title');
var menuTitle = document.querySelector(".menu-title");
menuTitle.addEventListener('click', function () {
document.scrollingElement.scrollTo({ top: 0, behavior: 'smooth' });
menuTitle.addEventListener("click", function () {
document.scrollingElement.scrollTo({ top: 0, behavior: "smooth" });
});
})();
(function controllMenu() {
var menu = document.getElementById('menu-bar');
var menu = document.getElementById("menu-bar");
(function controllPosition() {
var scrollTop = document.scrollingElement.scrollTop;
var prevScrollTop = scrollTop;
var minMenuY = -menu.clientHeight - 50;
// When the script loads, the page can be at any scroll (e.g. if you reforesh it).
menu.style.top = scrollTop + 'px';
menu.style.top = scrollTop + "px";
// Same as parseInt(menu.style.top.slice(0, -2), but faster
var topCache = menu.style.top.slice(0, -2);
menu.classList.remove('sticky');
menu.classList.remove("sticky");
var stickyCache = false; // Same as menu.classList.contains('sticky'), but faster
document.addEventListener('scroll', function () {
document.addEventListener(
"scroll",
function () {
scrollTop = Math.max(document.scrollingElement.scrollTop, 0);
// `null` means that it doesn't need to be updated
var nextSticky = null;
@ -689,27 +746,30 @@ function playground_text(playground, hidden = true) {
}
}
if (nextSticky === true && stickyCache === false) {
menu.classList.add('sticky');
menu.classList.add("sticky");
stickyCache = true;
} else if (nextSticky === false && stickyCache === true) {
menu.classList.remove('sticky');
menu.classList.remove("sticky");
stickyCache = false;
}
if (nextTop !== null) {
menu.style.top = nextTop + 'px';
menu.style.top = nextTop + "px";
topCache = nextTop;
}
prevScrollTop = scrollTop;
}, { passive: true });
},
{ passive: true }
);
})();
(function controllBorder() {
menu.classList.remove('bordered');
document.addEventListener('scroll', function () {
function updateBorder() {
if (menu.offsetTop === 0) {
menu.classList.remove('bordered');
menu.classList.remove("bordered");
} else {
menu.classList.add('bordered');
menu.classList.add("bordered");
}
}
}, { passive: true });
updateBorder();
document.addEventListener("scroll", updateBorder, { passive: true });
})();
})();

Loading…
Cancel
Save