book.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. "use strict";
  2. // Fix back button cache problem
  3. window.onunload = function () { };
  4. // Global variable, shared between modules
  5. function playpen_text(playpen) {
  6. let code_block = playpen.querySelector("code");
  7. if (window.ace && code_block.classList.contains("editable")) {
  8. let editor = window.ace.edit(code_block);
  9. return editor.getValue();
  10. } else {
  11. return code_block.textContent;
  12. }
  13. }
  14. (function codeSnippets() {
  15. // Hide Rust code lines prepended with a specific character
  16. var hiding_character = "#";
  17. var playpens = Array.from(document.querySelectorAll(".playpen"));
  18. if (playpens.length > 0) {
  19. fetch("https://play.rust-lang.org/meta/crates", {
  20. headers: {
  21. 'Content-Type': "application/json",
  22. },
  23. method: 'POST',
  24. mode: 'cors',
  25. })
  26. .then(response => response.json())
  27. .then(response => {
  28. // get list of crates available in the rust playground
  29. let playground_crates = response.crates.map(item => item["id"]);
  30. playpens.forEach(block => handle_crate_list_update(block, playground_crates));
  31. });
  32. }
  33. function handle_crate_list_update(playpen_block, playground_crates) {
  34. // update the play buttons after receiving the response
  35. update_play_button(playpen_block, playground_crates);
  36. // and install on change listener to dynamically update ACE editors
  37. if (window.ace) {
  38. let code_block = playpen_block.querySelector("code");
  39. if (code_block.classList.contains("editable")) {
  40. let editor = window.ace.edit(code_block);
  41. editor.addEventListener("change", function (e) {
  42. update_play_button(playpen_block, playground_crates);
  43. });
  44. }
  45. }
  46. }
  47. // updates the visibility of play button based on `no_run` class and
  48. // used crates vs ones available on http://play.rust-lang.org
  49. function update_play_button(pre_block, playground_crates) {
  50. var play_button = pre_block.querySelector(".play-button");
  51. // skip if code is `no_run`
  52. if (pre_block.querySelector('code').classList.contains("no_run")) {
  53. play_button.classList.add("hidden");
  54. return;
  55. }
  56. // get list of `extern crate`'s from snippet
  57. var txt = playpen_text(pre_block);
  58. var re = /extern\s+crate\s+([a-zA-Z_0-9]+)\s*;/g;
  59. var snippet_crates = [];
  60. var item;
  61. while (item = re.exec(txt)) {
  62. snippet_crates.push(item[1]);
  63. }
  64. // check if all used crates are available on play.rust-lang.org
  65. var all_available = snippet_crates.every(function (elem) {
  66. return playground_crates.indexOf(elem) > -1;
  67. });
  68. if (all_available) {
  69. play_button.classList.remove("hidden");
  70. } else {
  71. play_button.classList.add("hidden");
  72. }
  73. }
  74. function run_rust_code(code_block) {
  75. var result_block = code_block.querySelector(".result");
  76. if (!result_block) {
  77. result_block = document.createElement('code');
  78. result_block.className = 'result hljs language-bash';
  79. code_block.append(result_block);
  80. }
  81. let text = playpen_text(code_block);
  82. var params = {
  83. channel: "stable",
  84. mode: "debug",
  85. crateType: "bin",
  86. tests: false,
  87. code: text,
  88. }
  89. if (text.indexOf("#![feature") !== -1) {
  90. params.channel = "nightly";
  91. }
  92. result_block.innerText = "Running...";
  93. var request = fetch("https://play.rust-lang.org/execute", {
  94. headers: {
  95. 'Content-Type': "application/json",
  96. },
  97. method: 'POST',
  98. mode: 'cors',
  99. body: JSON.stringify(params)
  100. });
  101. request
  102. .then(function (response) { return response.json(); })
  103. .then(function (response) { result_block.innerText = response.success ? response.stdout : response.stderr; })
  104. .catch(function (error) { result_block.innerText = "Playground communication" + error.message; });
  105. }
  106. // Syntax highlighting Configuration
  107. hljs.configure({
  108. tabReplace: ' ', // 4 spaces
  109. languages: [], // Languages used for auto-detection
  110. });
  111. if (window.ace) {
  112. // language-rust class needs to be removed for editable
  113. // blocks or highlightjs will capture events
  114. Array
  115. .from(document.querySelectorAll('code.editable'))
  116. .forEach(function (block) { block.classList.remove('language-rust'); });
  117. Array
  118. .from(document.querySelectorAll('code:not(.editable)'))
  119. .forEach(function (block) { hljs.highlightBlock(block); });
  120. } else {
  121. Array
  122. .from(document.querySelectorAll('code'))
  123. .forEach(function (block) { hljs.highlightBlock(block); });
  124. }
  125. // Adding the hljs class gives code blocks the color css
  126. // even if highlighting doesn't apply
  127. Array
  128. .from(document.querySelectorAll('code'))
  129. .forEach(function (block) { block.classList.add('hljs'); });
  130. Array.from(document.querySelectorAll("code.language-rust")).forEach(function (block) {
  131. var code_block = block;
  132. var pre_block = block.parentNode;
  133. // hide lines
  134. var lines = code_block.innerHTML.split("\n");
  135. var first_non_hidden_line = false;
  136. var lines_hidden = false;
  137. var trimmed_line = "";
  138. for (var n = 0; n < lines.length; n++) {
  139. trimmed_line = lines[n].trim();
  140. if (trimmed_line[0] == hiding_character && trimmed_line[1] != hiding_character) {
  141. if (first_non_hidden_line) {
  142. lines[n] = "<span class=\"hidden\">" + "\n" + lines[n].replace(/(\s*)# ?/, "$1") + "</span>";
  143. }
  144. else {
  145. lines[n] = "<span class=\"hidden\">" + lines[n].replace(/(\s*)# ?/, "$1") + "\n" + "</span>";
  146. }
  147. lines_hidden = true;
  148. }
  149. else if (first_non_hidden_line) {
  150. lines[n] = "\n" + lines[n];
  151. }
  152. else {
  153. first_non_hidden_line = true;
  154. }
  155. if (trimmed_line[0] == hiding_character && trimmed_line[1] == hiding_character) {
  156. lines[n] = lines[n].replace("##", "#")
  157. }
  158. }
  159. code_block.innerHTML = lines.join("");
  160. // If no lines were hidden, return
  161. if (!lines_hidden) { return; }
  162. var buttons = document.createElement('div');
  163. buttons.className = 'buttons';
  164. buttons.innerHTML = "<button class=\"fa fa-expand\" title=\"Show hidden lines\" aria-label=\"Show hidden lines\"></button>";
  165. // add expand button
  166. pre_block.insertBefore(buttons, pre_block.firstChild);
  167. pre_block.querySelector('.buttons').addEventListener('click', function (e) {
  168. if (e.target.classList.contains('fa-expand')) {
  169. var lines = pre_block.querySelectorAll('span.hidden');
  170. e.target.classList.remove('fa-expand');
  171. e.target.classList.add('fa-compress');
  172. e.target.title = 'Hide lines';
  173. e.target.setAttribute('aria-label', e.target.title);
  174. Array.from(lines).forEach(function (line) {
  175. line.classList.remove('hidden');
  176. line.classList.add('unhidden');
  177. });
  178. } else if (e.target.classList.contains('fa-compress')) {
  179. var lines = pre_block.querySelectorAll('span.unhidden');
  180. e.target.classList.remove('fa-compress');
  181. e.target.classList.add('fa-expand');
  182. e.target.title = 'Show hidden lines';
  183. e.target.setAttribute('aria-label', e.target.title);
  184. Array.from(lines).forEach(function (line) {
  185. line.classList.remove('unhidden');
  186. line.classList.add('hidden');
  187. });
  188. }
  189. });
  190. });
  191. Array.from(document.querySelectorAll('pre code')).forEach(function (block) {
  192. var pre_block = block.parentNode;
  193. if (!pre_block.classList.contains('playpen')) {
  194. var buttons = pre_block.querySelector(".buttons");
  195. if (!buttons) {
  196. buttons = document.createElement('div');
  197. buttons.className = 'buttons';
  198. pre_block.insertBefore(buttons, pre_block.firstChild);
  199. }
  200. var clipButton = document.createElement('button');
  201. clipButton.className = 'fa fa-copy clip-button';
  202. clipButton.title = 'Copy to clipboard';
  203. clipButton.setAttribute('aria-label', clipButton.title);
  204. clipButton.innerHTML = '<i class=\"tooltiptext\"></i>';
  205. buttons.insertBefore(clipButton, buttons.firstChild);
  206. }
  207. });
  208. // Process playpen code blocks
  209. Array.from(document.querySelectorAll(".playpen")).forEach(function (pre_block) {
  210. // Add play button
  211. var buttons = pre_block.querySelector(".buttons");
  212. if (!buttons) {
  213. buttons = document.createElement('div');
  214. buttons.className = 'buttons';
  215. pre_block.insertBefore(buttons, pre_block.firstChild);
  216. }
  217. var runCodeButton = document.createElement('button');
  218. runCodeButton.className = 'fa fa-play play-button';
  219. runCodeButton.hidden = true;
  220. runCodeButton.title = 'Run this code';
  221. runCodeButton.setAttribute('aria-label', runCodeButton.title);
  222. var copyCodeClipboardButton = document.createElement('button');
  223. copyCodeClipboardButton.className = 'fa fa-copy clip-button';
  224. copyCodeClipboardButton.innerHTML = '<i class="tooltiptext"></i>';
  225. copyCodeClipboardButton.title = 'Copy to clipboard';
  226. copyCodeClipboardButton.setAttribute('aria-label', copyCodeClipboardButton.title);
  227. buttons.insertBefore(runCodeButton, buttons.firstChild);
  228. buttons.insertBefore(copyCodeClipboardButton, buttons.firstChild);
  229. runCodeButton.addEventListener('click', function (e) {
  230. run_rust_code(pre_block);
  231. });
  232. let code_block = pre_block.querySelector("code");
  233. if (window.ace && code_block.classList.contains("editable")) {
  234. var undoChangesButton = document.createElement('button');
  235. undoChangesButton.className = 'fa fa-history reset-button';
  236. undoChangesButton.title = 'Undo changes';
  237. undoChangesButton.setAttribute('aria-label', undoChangesButton.title);
  238. buttons.insertBefore(undoChangesButton, buttons.firstChild);
  239. undoChangesButton.addEventListener('click', function () {
  240. let editor = window.ace.edit(code_block);
  241. editor.setValue(editor.originalCode);
  242. editor.clearSelection();
  243. });
  244. }
  245. });
  246. })();
  247. (function themes() {
  248. var html = document.querySelector('html');
  249. var themeToggleButton = document.getElementById('theme-toggle');
  250. var themePopup = document.getElementById('theme-list');
  251. var themeColorMetaTag = document.querySelector('meta[name="theme-color"]');
  252. var stylesheets = {
  253. ayuHighlight: document.querySelector("[href$='ayu-highlight.css']"),
  254. tomorrowNight: document.querySelector("[href$='tomorrow-night.css']"),
  255. highlight: document.querySelector("[href$='highlight.css']"),
  256. };
  257. function showThemes() {
  258. themePopup.style.display = 'block';
  259. themeToggleButton.setAttribute('aria-expanded', true);
  260. themePopup.querySelector("button#" + document.body.className).focus();
  261. }
  262. function hideThemes() {
  263. themePopup.style.display = 'none';
  264. themeToggleButton.setAttribute('aria-expanded', false);
  265. themeToggleButton.focus();
  266. }
  267. function set_theme(theme) {
  268. let ace_theme;
  269. if (theme == 'coal' || theme == 'navy') {
  270. stylesheets.ayuHighlight.disabled = true;
  271. stylesheets.tomorrowNight.disabled = false;
  272. stylesheets.highlight.disabled = true;
  273. ace_theme = "ace/theme/tomorrow_night";
  274. } else if (theme == 'ayu') {
  275. stylesheets.ayuHighlight.disabled = false;
  276. stylesheets.tomorrowNight.disabled = true;
  277. stylesheets.highlight.disabled = true;
  278. ace_theme = "ace/theme/tomorrow_night";
  279. } else {
  280. stylesheets.ayuHighlight.disabled = true;
  281. stylesheets.tomorrowNight.disabled = true;
  282. stylesheets.highlight.disabled = false;
  283. ace_theme = "ace/theme/dawn";
  284. }
  285. setTimeout(function () {
  286. themeColorMetaTag.content = getComputedStyle(document.body).backgroundColor;
  287. }, 1);
  288. if (window.ace && window.editors) {
  289. window.editors.forEach(function (editor) {
  290. editor.setTheme(ace_theme);
  291. });
  292. }
  293. var previousTheme;
  294. try { previousTheme = localStorage.getItem('mdbook-theme'); } catch (e) { }
  295. if (previousTheme === null || previousTheme === undefined) { previousTheme = 'light'; }
  296. try { localStorage.setItem('mdbook-theme', theme); } catch (e) { }
  297. document.body.className = theme;
  298. html.classList.remove(previousTheme);
  299. html.classList.add(theme);
  300. }
  301. // Set theme
  302. var theme;
  303. try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
  304. if (theme === null || theme === undefined) { theme = 'light'; }
  305. set_theme(theme);
  306. themeToggleButton.addEventListener('click', function () {
  307. if (themePopup.style.display === 'block') {
  308. hideThemes();
  309. } else {
  310. showThemes();
  311. }
  312. });
  313. themePopup.addEventListener('click', function (e) {
  314. var theme = e.target.id || e.target.parentElement.id;
  315. set_theme(theme);
  316. });
  317. themePopup.addEventListener('focusout', function(e) {
  318. // e.relatedTarget is null in Safari and Firefox on macOS (see workaround below)
  319. if (!!e.relatedTarget && !themePopup.contains(e.relatedTarget)) {
  320. hideThemes();
  321. }
  322. });
  323. // Should not be needed, but it works around an issue on macOS & iOS: https://github.com/rust-lang-nursery/mdBook/issues/628
  324. document.addEventListener('click', function(e) {
  325. if (themePopup.style.display === 'block' && !themeToggleButton.contains(e.target) && !themePopup.contains(e.target)) {
  326. hideThemes();
  327. }
  328. });
  329. document.addEventListener('keydown', function (e) {
  330. if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
  331. if (!themePopup.contains(e.target)) { return; }
  332. switch (e.key) {
  333. case 'Escape':
  334. e.preventDefault();
  335. hideThemes();
  336. break;
  337. case 'ArrowUp':
  338. e.preventDefault();
  339. var li = document.activeElement.parentElement;
  340. if (li && li.previousElementSibling) {
  341. li.previousElementSibling.querySelector('button').focus();
  342. }
  343. break;
  344. case 'ArrowDown':
  345. e.preventDefault();
  346. var li = document.activeElement.parentElement;
  347. if (li && li.nextElementSibling) {
  348. li.nextElementSibling.querySelector('button').focus();
  349. }
  350. break;
  351. case 'Home':
  352. e.preventDefault();
  353. themePopup.querySelector('li:first-child button').focus();
  354. break;
  355. case 'End':
  356. e.preventDefault();
  357. themePopup.querySelector('li:last-child button').focus();
  358. break;
  359. }
  360. });
  361. })();
  362. (function sidebar() {
  363. var html = document.querySelector("html");
  364. var sidebar = document.getElementById("sidebar");
  365. var sidebarLinks = document.querySelectorAll('#sidebar a');
  366. var sidebarToggleButton = document.getElementById("sidebar-toggle");
  367. var firstContact = null;
  368. function showSidebar() {
  369. html.classList.remove('sidebar-hidden')
  370. html.classList.add('sidebar-visible');
  371. Array.from(sidebarLinks).forEach(function (link) {
  372. link.setAttribute('tabIndex', 0);
  373. });
  374. sidebarToggleButton.setAttribute('aria-expanded', true);
  375. sidebar.setAttribute('aria-hidden', false);
  376. try { localStorage.setItem('mdbook-sidebar', 'visible'); } catch (e) { }
  377. }
  378. function hideSidebar() {
  379. html.classList.remove('sidebar-visible')
  380. html.classList.add('sidebar-hidden');
  381. Array.from(sidebarLinks).forEach(function (link) {
  382. link.setAttribute('tabIndex', -1);
  383. });
  384. sidebarToggleButton.setAttribute('aria-expanded', false);
  385. sidebar.setAttribute('aria-hidden', true);
  386. try { localStorage.setItem('mdbook-sidebar', 'hidden'); } catch (e) { }
  387. }
  388. // Toggle sidebar
  389. sidebarToggleButton.addEventListener('click', function sidebarToggle() {
  390. if (html.classList.contains("sidebar-hidden")) {
  391. showSidebar();
  392. } else if (html.classList.contains("sidebar-visible")) {
  393. hideSidebar();
  394. } else {
  395. if (getComputedStyle(sidebar)['transform'] === 'none') {
  396. hideSidebar();
  397. } else {
  398. showSidebar();
  399. }
  400. }
  401. });
  402. document.addEventListener('touchstart', function (e) {
  403. firstContact = {
  404. x: e.touches[0].clientX,
  405. time: Date.now()
  406. };
  407. }, { passive: true });
  408. document.addEventListener('touchmove', function (e) {
  409. if (!firstContact)
  410. return;
  411. var curX = e.touches[0].clientX;
  412. var xDiff = curX - firstContact.x,
  413. tDiff = Date.now() - firstContact.time;
  414. if (tDiff < 250 && Math.abs(xDiff) >= 150) {
  415. if (xDiff >= 0 && firstContact.x < Math.min(document.body.clientWidth * 0.25, 300))
  416. showSidebar();
  417. else if (xDiff < 0 && curX < 300)
  418. hideSidebar();
  419. firstContact = null;
  420. }
  421. }, { passive: true });
  422. // Scroll sidebar to current active section
  423. var activeSection = sidebar.querySelector(".active");
  424. if (activeSection) {
  425. sidebar.scrollTop = activeSection.offsetTop;
  426. }
  427. })();
  428. (function chapterNavigation() {
  429. document.addEventListener('keydown', function (e) {
  430. if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
  431. if (window.search && window.search.hasFocus()) { return; }
  432. switch (e.key) {
  433. case 'ArrowRight':
  434. e.preventDefault();
  435. var nextButton = document.querySelector('.nav-chapters.next');
  436. if (nextButton) {
  437. window.location.href = nextButton.href;
  438. }
  439. break;
  440. case 'ArrowLeft':
  441. e.preventDefault();
  442. var previousButton = document.querySelector('.nav-chapters.previous');
  443. if (previousButton) {
  444. window.location.href = previousButton.href;
  445. }
  446. break;
  447. }
  448. });
  449. })();
  450. (function clipboard() {
  451. var clipButtons = document.querySelectorAll('.clip-button');
  452. function hideTooltip(elem) {
  453. elem.firstChild.innerText = "";
  454. elem.className = 'fa fa-copy clip-button';
  455. }
  456. function showTooltip(elem, msg) {
  457. elem.firstChild.innerText = msg;
  458. elem.className = 'fa fa-copy tooltipped';
  459. }
  460. var clipboardSnippets = new Clipboard('.clip-button', {
  461. text: function (trigger) {
  462. hideTooltip(trigger);
  463. let playpen = trigger.closest("pre");
  464. return playpen_text(playpen);
  465. }
  466. });
  467. Array.from(clipButtons).forEach(function (clipButton) {
  468. clipButton.addEventListener('mouseout', function (e) {
  469. hideTooltip(e.currentTarget);
  470. });
  471. });
  472. clipboardSnippets.on('success', function (e) {
  473. e.clearSelection();
  474. showTooltip(e.trigger, "Copied!");
  475. });
  476. clipboardSnippets.on('error', function (e) {
  477. showTooltip(e.trigger, "Clipboard error!");
  478. });
  479. })();
  480. (function scrollToTop () {
  481. var menuTitle = document.querySelector('.menu-title');
  482. menuTitle.addEventListener('click', function () {
  483. document.scrollingElement.scrollTo({ top: 0, behavior: 'smooth' });
  484. });
  485. })();
  486. (function autoHideMenu() {
  487. var menu = document.getElementById('menu-bar');
  488. var previousScrollTop = document.scrollingElement.scrollTop;
  489. document.addEventListener('scroll', function () {
  490. if (menu.classList.contains('folded') && document.scrollingElement.scrollTop < previousScrollTop) {
  491. menu.classList.remove('folded');
  492. } else if (!menu.classList.contains('folded') && document.scrollingElement.scrollTop > previousScrollTop) {
  493. menu.classList.add('folded');
  494. }
  495. if (!menu.classList.contains('bordered') && document.scrollingElement.scrollTop > 0) {
  496. menu.classList.add('bordered');
  497. }
  498. if (menu.classList.contains('bordered') && document.scrollingElement.scrollTop === 0) {
  499. menu.classList.remove('bordered');
  500. }
  501. previousScrollTop = document.scrollingElement.scrollTop;
  502. }, { passive: true });
  503. })();