book.js 21 KB

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