book.js 21 KB

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