1
Fork 0

Move callback to the () => {} syntax.

Fix lint

Fix main.js

Restore anonymous functions

Fix

Fix more
This commit is contained in:
Folyd 2022-05-03 12:03:17 +08:00
parent 468492c2af
commit 67ebeea7a0
6 changed files with 109 additions and 112 deletions

View file

@ -1,6 +1,7 @@
/* eslint-env es6 */ /* eslint-env es6 */
/* eslint no-var: "error" */ /* eslint no-var: "error" */
/* eslint prefer-const: "error" */ /* eslint prefer-const: "error" */
/* eslint prefer-arrow-callback: "error" */
// Local js definitions: // Local js definitions:
/* global addClass, getSettingValue, hasClass, searchState */ /* global addClass, getSettingValue, hasClass, searchState */
/* global onEach, onEachLazy, removeClass */ /* global onEach, onEachLazy, removeClass */
@ -152,7 +153,7 @@ function hideThemeButtonState() {
themePicker.style.borderBottomLeftRadius = "3px"; themePicker.style.borderBottomLeftRadius = "3px";
} }
window.hideSettings = function() { window.hideSettings = () => {
// Does nothing by default. // Does nothing by default.
}; };
@ -190,10 +191,10 @@ window.hideSettings = function() {
themePicker.onclick = switchThemeButtonState; themePicker.onclick = switchThemeButtonState;
themePicker.onblur = handleThemeButtonsBlur; themePicker.onblur = handleThemeButtonsBlur;
availableThemes.forEach(function(item) { availableThemes.forEach(item => {
const but = document.createElement("button"); const but = document.createElement("button");
but.textContent = item; but.textContent = item;
but.onclick = function() { but.onclick = () => {
switchTheme(window.currentTheme, window.mainTheme, item, true); switchTheme(window.currentTheme, window.mainTheme, item, true);
useSystemTheme(false); useSystemTheme(false);
}; };
@ -300,7 +301,7 @@ function loadCss(cssFileName) {
} }
getSettingsButton().onclick = function(event) { getSettingsButton().onclick = event => {
event.preventDefault(); event.preventDefault();
loadScript(window.settingsJS); loadScript(window.settingsJS);
}; };
@ -308,7 +309,7 @@ function loadCss(cssFileName) {
window.searchState = { window.searchState = {
loadingText: "Loading search results...", loadingText: "Loading search results...",
input: document.getElementsByClassName("search-input")[0], input: document.getElementsByClassName("search-input")[0],
outputElement: function() { outputElement: () => {
let el = document.getElementById("search"); let el = document.getElementById("search");
if (!el) { if (!el) {
el = document.createElement("section"); el = document.createElement("section");
@ -328,24 +329,22 @@ function loadCss(cssFileName) {
currentTab: 0, currentTab: 0,
// tab and back preserves the element that was focused. // tab and back preserves the element that was focused.
focusedByTab: [null, null, null], focusedByTab: [null, null, null],
clearInputTimeout: function() { clearInputTimeout: () => {
if (searchState.timeout !== null) { if (searchState.timeout !== null) {
clearTimeout(searchState.timeout); clearTimeout(searchState.timeout);
searchState.timeout = null; searchState.timeout = null;
} }
}, },
isDisplayed: function() { isDisplayed: () => searchState.outputElement().parentElement.id === ALTERNATIVE_DISPLAY_ID,
return searchState.outputElement().parentElement.id === ALTERNATIVE_DISPLAY_ID;
},
// Sets the focus on the search bar at the top of the page // Sets the focus on the search bar at the top of the page
focus: function() { focus: () => {
searchState.input.focus(); searchState.input.focus();
}, },
// Removes the focus from the search bar. // Removes the focus from the search bar.
defocus: function() { defocus: () => {
searchState.input.blur(); searchState.input.blur();
}, },
showResults: function(search) { showResults: search => {
if (search === null || typeof search === 'undefined') { if (search === null || typeof search === 'undefined') {
search = searchState.outputElement(); search = searchState.outputElement();
} }
@ -353,7 +352,7 @@ function loadCss(cssFileName) {
searchState.mouseMovedAfterSearch = false; searchState.mouseMovedAfterSearch = false;
document.title = searchState.title; document.title = searchState.title;
}, },
hideResults: function() { hideResults: () => {
switchDisplayedElement(null); switchDisplayedElement(null);
document.title = searchState.titleBeforeSearch; document.title = searchState.titleBeforeSearch;
// We also remove the query parameter from the URL. // We also remove the query parameter from the URL.
@ -362,17 +361,17 @@ function loadCss(cssFileName) {
getNakedUrl() + window.location.hash); getNakedUrl() + window.location.hash);
} }
}, },
getQueryStringParams: function() { getQueryStringParams: () => {
const params = {}; const params = {};
window.location.search.substring(1).split("&"). window.location.search.substring(1).split("&").
map(function(s) { map(s => {
const pair = s.split("="); const pair = s.split("=");
params[decodeURIComponent(pair[0])] = params[decodeURIComponent(pair[0])] =
typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]); typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
}); });
return params; return params;
}, },
setup: function() { setup: () => {
const search_input = searchState.input; const search_input = searchState.input;
if (!searchState.input) { if (!searchState.input) {
return; return;
@ -386,13 +385,13 @@ function loadCss(cssFileName) {
} }
} }
search_input.addEventListener("focus", function() { search_input.addEventListener("focus", () => {
search_input.origPlaceholder = search_input.placeholder; search_input.origPlaceholder = search_input.placeholder;
search_input.placeholder = "Type your search here."; search_input.placeholder = "Type your search here.";
loadSearch(); loadSearch();
}); });
if (search_input.value != '') { if (search_input.value !== '') {
loadSearch(); loadSearch();
} }
@ -620,7 +619,7 @@ function loadCss(cssFileName) {
document.addEventListener("keydown", handleShortcut); document.addEventListener("keydown", handleShortcut);
// delayed sidebar rendering. // delayed sidebar rendering.
window.initSidebarItems = function(items) { window.initSidebarItems = items => {
const sidebar = document.getElementsByClassName("sidebar-elems")[0]; const sidebar = document.getElementsByClassName("sidebar-elems")[0];
let others; let others;
const current = window.sidebarCurrent; const current = window.sidebarCurrent;
@ -731,7 +730,7 @@ function loadCss(cssFileName) {
} }
}; };
window.register_implementors = function(imp) { window.register_implementors = imp => {
const implementors = document.getElementById("implementors-list"); const implementors = document.getElementById("implementors-list");
const synthetic_implementors = document.getElementById("synthetic-implementors-list"); const synthetic_implementors = document.getElementById("synthetic-implementors-list");
const inlined_types = new Set(); const inlined_types = new Set();
@ -742,12 +741,12 @@ function loadCss(cssFileName) {
// //
// By the way, this is only used by and useful for traits implemented automatically // By the way, this is only used by and useful for traits implemented automatically
// (like "Send" and "Sync"). // (like "Send" and "Sync").
onEachLazy(synthetic_implementors.getElementsByClassName("impl"), function(el) { onEachLazy(synthetic_implementors.getElementsByClassName("impl"), el => {
const aliases = el.getAttribute("data-aliases"); const aliases = el.getAttribute("data-aliases");
if (!aliases) { if (!aliases) {
return; return;
} }
aliases.split(",").forEach(function(alias) { aliases.split(",").forEach(alias => {
inlined_types.add(alias); inlined_types.add(alias);
}); });
}); });
@ -781,7 +780,7 @@ function loadCss(cssFileName) {
addClass(code, "code-header"); addClass(code, "code-header");
addClass(code, "in-band"); addClass(code, "in-band");
onEachLazy(code.getElementsByTagName("a"), function(elem) { onEachLazy(code.getElementsByTagName("a"), elem => {
const href = elem.getAttribute("href"); const href = elem.getAttribute("href");
if (href && href.indexOf("http") !== 0) { if (href && href.indexOf("http") !== 0) {
@ -826,7 +825,7 @@ function loadCss(cssFileName) {
let sectionIsCollapsed = false; let sectionIsCollapsed = false;
if (hasClass(innerToggle, "will-expand")) { if (hasClass(innerToggle, "will-expand")) {
removeClass(innerToggle, "will-expand"); removeClass(innerToggle, "will-expand");
onEachLazy(document.getElementsByClassName("rustdoc-toggle"), function(e) { onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
if (!hasClass(e, "type-contents-toggle")) { if (!hasClass(e, "type-contents-toggle")) {
e.open = true; e.open = true;
} }
@ -834,7 +833,7 @@ function loadCss(cssFileName) {
innerToggle.title = "collapse all docs"; innerToggle.title = "collapse all docs";
} else { } else {
addClass(innerToggle, "will-expand"); addClass(innerToggle, "will-expand");
onEachLazy(document.getElementsByClassName("rustdoc-toggle"), function(e) { onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
if (e.parentNode.id !== "implementations-list" || if (e.parentNode.id !== "implementations-list" ||
(!hasClass(e, "implementors-toggle") && (!hasClass(e, "implementors-toggle") &&
!hasClass(e, "type-contents-toggle"))) !hasClass(e, "type-contents-toggle")))
@ -861,7 +860,7 @@ function loadCss(cssFileName) {
function setImplementorsTogglesOpen(id, open) { function setImplementorsTogglesOpen(id, open) {
const list = document.getElementById(id); const list = document.getElementById(id);
if (list !== null) { if (list !== null) {
onEachLazy(list.getElementsByClassName("implementors-toggle"), function(e) { onEachLazy(list.getElementsByClassName("implementors-toggle"), e => {
e.open = open; e.open = open;
}); });
} }
@ -872,7 +871,7 @@ function loadCss(cssFileName) {
setImplementorsTogglesOpen("blanket-implementations-list", false); setImplementorsTogglesOpen("blanket-implementations-list", false);
} }
onEachLazy(document.getElementsByClassName("rustdoc-toggle"), function (e) { onEachLazy(document.getElementsByClassName("rustdoc-toggle"), e => {
if (!hideLargeItemContents && hasClass(e, "type-contents-toggle")) { if (!hideLargeItemContents && hasClass(e, "type-contents-toggle")) {
e.open = true; e.open = true;
} }
@ -890,9 +889,9 @@ function loadCss(cssFileName) {
(function() { (function() {
// To avoid checking on "rustdoc-line-numbers" value on every loop... // To avoid checking on "rustdoc-line-numbers" value on every loop...
let lineNumbersFunc = function() {}; let lineNumbersFunc = () => {};
if (getSettingValue("line-numbers") === "true") { if (getSettingValue("line-numbers") === "true") {
lineNumbersFunc = function(x) { lineNumbersFunc = x => {
const count = x.textContent.split("\n").length; const count = x.textContent.split("\n").length;
const elems = []; const elems = [];
for (let i = 0; i < count; ++i) { for (let i = 0; i < count; ++i) {
@ -904,7 +903,7 @@ function loadCss(cssFileName) {
x.parentNode.insertBefore(node, x); x.parentNode.insertBefore(node, x);
}; };
} }
onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) { onEachLazy(document.getElementsByClassName("rust-example-rendered"), e => {
if (hasClass(e, "compile_fail")) { if (hasClass(e, "compile_fail")) {
e.addEventListener("mouseover", function() { e.addEventListener("mouseover", function() {
this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00"; this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
@ -935,34 +934,34 @@ function loadCss(cssFileName) {
elem.addEventListener("click", f); elem.addEventListener("click", f);
} }
} }
handleClick("help-button", function(ev) { handleClick("help-button", ev => {
displayHelp(true, ev); displayHelp(true, ev);
}); });
handleClick(MAIN_ID, function() { handleClick(MAIN_ID, () => {
hideSidebar(); hideSidebar();
}); });
onEachLazy(document.getElementsByTagName("a"), function(el) { onEachLazy(document.getElementsByTagName("a"), el => {
// For clicks on internal links (<A> tags with a hash property), we expand the section we're // For clicks on internal links (<A> tags with a hash property), we expand the section we're
// jumping to *before* jumping there. We can't do this in onHashChange, because it changes // jumping to *before* jumping there. We can't do this in onHashChange, because it changes
// the height of the document so we wind up scrolled to the wrong place. // the height of the document so we wind up scrolled to the wrong place.
if (el.hash) { if (el.hash) {
el.addEventListener("click", function() { el.addEventListener("click", () => {
expandSection(el.hash.slice(1)); expandSection(el.hash.slice(1));
hideSidebar(); hideSidebar();
}); });
} }
}); });
onEachLazy(document.querySelectorAll(".rustdoc-toggle > summary:not(.hideme)"), function(el) { onEachLazy(document.querySelectorAll(".rustdoc-toggle > summary:not(.hideme)"), el => {
el.addEventListener("click", function(e) { el.addEventListener("click", e => {
if (e.target.tagName != "SUMMARY" && e.target.tagName != "A") { if (e.target.tagName !== "SUMMARY" && e.target.tagName !== "A") {
e.preventDefault(); e.preventDefault();
} }
}); });
}); });
onEachLazy(document.getElementsByClassName("notable-traits"), function(e) { onEachLazy(document.getElementsByClassName("notable-traits"), e => {
e.onclick = function() { e.onclick = function() {
this.getElementsByClassName('notable-traits-tooltiptext')[0] this.getElementsByClassName('notable-traits-tooltiptext')[0]
.classList.toggle("force-tooltip"); .classList.toggle("force-tooltip");
@ -971,7 +970,7 @@ function loadCss(cssFileName) {
const sidebar_menu_toggle = document.getElementsByClassName("sidebar-menu-toggle")[0]; const sidebar_menu_toggle = document.getElementsByClassName("sidebar-menu-toggle")[0];
if (sidebar_menu_toggle) { if (sidebar_menu_toggle) {
sidebar_menu_toggle.addEventListener("click", function() { sidebar_menu_toggle.addEventListener("click", () => {
const sidebar = document.getElementsByClassName("sidebar")[0]; const sidebar = document.getElementsByClassName("sidebar")[0];
if (!hasClass(sidebar, "shown")) { if (!hasClass(sidebar, "shown")) {
addClass(sidebar, "shown"); addClass(sidebar, "shown");
@ -981,12 +980,12 @@ function loadCss(cssFileName) {
}); });
} }
let buildHelperPopup = function() { let buildHelperPopup = () => {
const popup = document.createElement("aside"); const popup = document.createElement("aside");
addClass(popup, "hidden"); addClass(popup, "hidden");
popup.id = "help"; popup.id = "help";
popup.addEventListener("click", function(ev) { popup.addEventListener("click", ev => {
if (ev.target === popup) { if (ev.target === popup) {
// Clicked the blurred zone outside the help popup; dismiss help. // Clicked the blurred zone outside the help popup; dismiss help.
displayHelp(false, ev); displayHelp(false, ev);
@ -1009,14 +1008,10 @@ function loadCss(cssFileName) {
["&#9166;", "Go to active search result"], ["&#9166;", "Go to active search result"],
["+", "Expand all sections"], ["+", "Expand all sections"],
["-", "Collapse all sections"], ["-", "Collapse all sections"],
].map(function(x) { ].map(x => "<dt>" +
return "<dt>" +
x[0].split(" ") x[0].split(" ")
.map(function(y, index) { .map((y, index) => (index & 1) === 0 ? "<kbd>" + y + "</kbd>" : " " + y + " ")
return (index & 1) === 0 ? "<kbd>" + y + "</kbd>" : " " + y + " "; .join("") + "</dt><dd>" + x[1] + "</dd>").join("");
})
.join("") + "</dt><dd>" + x[1] + "</dd>";
}).join("");
const div_shortcuts = document.createElement("div"); const div_shortcuts = document.createElement("div");
addClass(div_shortcuts, "shortcuts"); addClass(div_shortcuts, "shortcuts");
div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>"; div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
@ -1034,9 +1029,7 @@ function loadCss(cssFileName) {
"You can look for items with an exact name by putting double quotes around \ "You can look for items with an exact name by putting double quotes around \
your request: <code>\"string\"</code>", your request: <code>\"string\"</code>",
"Look for items inside another one by searching for a path: <code>vec::Vec</code>", "Look for items inside another one by searching for a path: <code>vec::Vec</code>",
].map(function(x) { ].map(x => "<p>" + x + "</p>").join("");
return "<p>" + x + "</p>";
}).join("");
const div_infos = document.createElement("div"); const div_infos = document.createElement("div");
addClass(div_infos, "infos"); addClass(div_infos, "infos");
div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos; div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
@ -1056,7 +1049,7 @@ function loadCss(cssFileName) {
popup.appendChild(container); popup.appendChild(container);
insertAfter(popup, document.querySelector("main")); insertAfter(popup, document.querySelector("main"));
// So that it's only built once and then it'll do nothing when called! // So that it's only built once and then it'll do nothing when called!
buildHelperPopup = function() {}; buildHelperPopup = () => {};
}; };
onHashChange(null); onHashChange(null);
@ -1067,11 +1060,11 @@ function loadCss(cssFileName) {
(function () { (function () {
let reset_button_timeout = null; let reset_button_timeout = null;
window.copy_path = function(but) { window.copy_path = but => {
const parent = but.parentElement; const parent = but.parentElement;
const path = []; const path = [];
onEach(parent.childNodes, function(child) { onEach(parent.childNodes, child => {
if (child.tagName === 'A') { if (child.tagName === 'A') {
path.push(child.textContent); path.push(child.textContent);
} }
@ -1097,7 +1090,7 @@ function loadCss(cssFileName) {
tmp = document.createTextNode('✓'); tmp = document.createTextNode('✓');
but.appendChild(tmp); but.appendChild(tmp);
} else { } else {
onEachLazy(but.childNodes, function(e) { onEachLazy(but.childNodes, e => {
if (e.nodeType === Node.TEXT_NODE) { if (e.nodeType === Node.TEXT_NODE) {
tmp = e; tmp = e;
return true; return true;

View file

@ -1,6 +1,7 @@
/* eslint-env es6 */ /* eslint-env es6 */
/* eslint no-var: "error" */ /* eslint no-var: "error" */
/* eslint prefer-const: "error" */ /* eslint prefer-const: "error" */
/* eslint prefer-arrow-callback: "error" */
/* global addClass, hasClass, removeClass, onEachLazy */ /* global addClass, hasClass, removeClass, onEachLazy */
(function () { (function () {
@ -38,7 +39,7 @@
if (locs.length > 1) { if (locs.length > 1) {
// Toggle through list of examples in a given file // Toggle through list of examples in a given file
const onChangeLoc = function(changeIndex) { const onChangeLoc = changeIndex => {
removeClass(highlights[locIndex], 'focus'); removeClass(highlights[locIndex], 'focus');
changeIndex(); changeIndex();
scrollToLoc(example, locs[locIndex][0]); scrollToLoc(example, locs[locIndex][0]);
@ -52,15 +53,15 @@
}; };
example.querySelector('.prev') example.querySelector('.prev')
.addEventListener('click', function() { .addEventListener('click', () => {
onChangeLoc(function() { onChangeLoc(() => {
locIndex = (locIndex - 1 + locs.length) % locs.length; locIndex = (locIndex - 1 + locs.length) % locs.length;
}); });
}); });
example.querySelector('.next') example.querySelector('.next')
.addEventListener('click', function() { .addEventListener('click', () => {
onChangeLoc(function() { onChangeLoc(() => {
locIndex = (locIndex + 1) % locs.length; locIndex = (locIndex + 1) % locs.length;
}); });
}); });
@ -68,7 +69,7 @@
const expandButton = example.querySelector('.expand'); const expandButton = example.querySelector('.expand');
if (expandButton) { if (expandButton) {
expandButton.addEventListener('click', function () { expandButton.addEventListener('click', () => {
if (hasClass(example, "expanded")) { if (hasClass(example, "expanded")) {
removeClass(example, "expanded"); removeClass(example, "expanded");
scrollToLoc(example, locs[0][0]); scrollToLoc(example, locs[0][0]);
@ -84,22 +85,22 @@
const firstExamples = document.querySelectorAll('.scraped-example-list > .scraped-example'); const firstExamples = document.querySelectorAll('.scraped-example-list > .scraped-example');
onEachLazy(firstExamples, updateScrapedExample); onEachLazy(firstExamples, updateScrapedExample);
onEachLazy(document.querySelectorAll('.more-examples-toggle'), function(toggle) { onEachLazy(document.querySelectorAll('.more-examples-toggle'), toggle => {
// Allow users to click the left border of the <details> section to close it, // Allow users to click the left border of the <details> section to close it,
// since the section can be large and finding the [+] button is annoying. // since the section can be large and finding the [+] button is annoying.
onEachLazy(toggle.querySelectorAll('.toggle-line, .hide-more'), button => { onEachLazy(toggle.querySelectorAll('.toggle-line, .hide-more'), button => {
button.addEventListener('click', function() { button.addEventListener('click', () => {
toggle.open = false; toggle.open = false;
}); });
}); });
const moreExamples = toggle.querySelectorAll('.scraped-example'); const moreExamples = toggle.querySelectorAll('.scraped-example');
toggle.querySelector('summary').addEventListener('click', function() { toggle.querySelector('summary').addEventListener('click', () => {
// Wrapping in setTimeout ensures the update happens after the elements are actually // Wrapping in setTimeout ensures the update happens after the elements are actually
// visible. This is necessary since updateScrapedExample calls scrollToLoc which // visible. This is necessary since updateScrapedExample calls scrollToLoc which
// depends on offsetHeight, a property that requires an element to be visible to // depends on offsetHeight, a property that requires an element to be visible to
// compute correctly. // compute correctly.
setTimeout(function() { onEachLazy(moreExamples, updateScrapedExample); }); setTimeout(() => { onEachLazy(moreExamples, updateScrapedExample); });
}, {once: true}); }, {once: true});
}); });
})(); })();

View file

@ -1,10 +1,11 @@
/* eslint-env es6 */ /* eslint-env es6 */
/* eslint no-var: "error" */ /* eslint no-var: "error" */
/* eslint prefer-const: "error" */ /* eslint prefer-const: "error" */
/* eslint prefer-arrow-callback: "error" */
/* global addClass, getNakedUrl, getSettingValue, hasOwnPropertyRustdoc, initSearch, onEach */ /* global addClass, getNakedUrl, getSettingValue, hasOwnPropertyRustdoc, initSearch, onEach */
/* global onEachLazy, removeClass, searchState, browserSupportsHistoryApi */ /* global onEachLazy, removeClass, searchState, browserSupportsHistoryApi */
(function() { (function () {
// This mapping table should match the discriminants of // This mapping table should match the discriminants of
// `rustdoc::formats::item_type::ItemType` type in Rust. // `rustdoc::formats::item_type::ItemType` type in Rust.
const itemTypes = [ const itemTypes = [
@ -46,7 +47,7 @@ function printTab(nb) {
searchState.currentTab = nb; searchState.currentTab = nb;
} }
let nb_copy = nb; let nb_copy = nb;
onEachLazy(document.getElementById("titles").childNodes, function(elem) { onEachLazy(document.getElementById("titles").childNodes, elem => {
if (nb_copy === 0) { if (nb_copy === 0) {
addClass(elem, "selected"); addClass(elem, "selected");
} else { } else {
@ -54,7 +55,7 @@ function printTab(nb) {
} }
nb_copy -= 1; nb_copy -= 1;
}); });
onEachLazy(document.getElementById("results").childNodes, function(elem) { onEachLazy(document.getElementById("results").childNodes, elem => {
if (nb === 0) { if (nb === 0) {
addClass(elem, "active"); addClass(elem, "active");
} else { } else {
@ -100,7 +101,7 @@ function levenshtein(s1, s2) {
return s1_len + s2_len; return s1_len + s2_len;
} }
window.initSearch = function(rawSearchIndex) { window.initSearch = rawSearchIndex => {
const MAX_LEV_DISTANCE = 3; const MAX_LEV_DISTANCE = 3;
const MAX_RESULTS = 200; const MAX_RESULTS = 200;
const GENERICS_DATA = 2; const GENERICS_DATA = 2;
@ -774,7 +775,7 @@ window.initSearch = function(rawSearchIndex) {
return []; return [];
} }
results.sort(function(aaa, bbb) { results.sort((aaa, bbb) => {
let a, b; let a, b;
// sort by exact match with regard to the last word (mismatch goes later) // sort by exact match with regard to the last word (mismatch goes later)
@ -978,9 +979,8 @@ window.initSearch = function(rawSearchIndex) {
if (elem.generics.length === 0) { if (elem.generics.length === 0) {
const checkGeneric = (row.length > GENERICS_DATA && const checkGeneric = (row.length > GENERICS_DATA &&
row[GENERICS_DATA].length > 0); row[GENERICS_DATA].length > 0);
if (checkGeneric && row[GENERICS_DATA].findIndex(function(tmp_elem) { if (checkGeneric && row[GENERICS_DATA]
return tmp_elem[NAME] === elem.name; .findIndex(tmp_elem => tmp_elem[NAME] === elem.name) !== -1) {
}) !== -1) {
return 0; return 0;
} }
} }
@ -1169,7 +1169,7 @@ window.initSearch = function(rawSearchIndex) {
} }
} }
} else { } else {
Object.keys(ALIASES).forEach(function(crate) { Object.keys(ALIASES).forEach(crate => {
if (ALIASES[crate][lowerQuery]) { if (ALIASES[crate][lowerQuery]) {
const pushTo = crate === window.currentCrate ? crateAliases : aliases; const pushTo = crate === window.currentCrate ? crateAliases : aliases;
const query_aliases = ALIASES[crate][lowerQuery]; const query_aliases = ALIASES[crate][lowerQuery];
@ -1180,7 +1180,7 @@ window.initSearch = function(rawSearchIndex) {
}); });
} }
const sortFunc = function(aaa, bbb) { const sortFunc = (aaa, bbb) => {
if (aaa.path < bbb.path) { if (aaa.path < bbb.path) {
return 1; return 1;
} else if (aaa.path === bbb.path) { } else if (aaa.path === bbb.path) {
@ -1191,7 +1191,7 @@ window.initSearch = function(rawSearchIndex) {
crateAliases.sort(sortFunc); crateAliases.sort(sortFunc);
aliases.sort(sortFunc); aliases.sort(sortFunc);
const pushFunc = function(alias) { const pushFunc = alias => {
alias.alias = query; alias.alias = query;
const res = buildHrefAndPath(alias); const res = buildHrefAndPath(alias);
alias.displayPath = pathSplitter(res[0]); alias.displayPath = pathSplitter(res[0]);
@ -1579,7 +1579,7 @@ window.initSearch = function(rawSearchIndex) {
if (array.length > 0) { if (array.length > 0) {
output.className = "search-results " + extraClass; output.className = "search-results " + extraClass;
array.forEach(function(item) { array.forEach(item => {
const name = item.name; const name = item.name;
const type = itemTypes[item.ty]; const type = itemTypes[item.ty];
@ -1746,9 +1746,9 @@ window.initSearch = function(rawSearchIndex) {
searchState.focusedByTab = [null, null, null]; searchState.focusedByTab = [null, null, null];
searchState.showResults(search); searchState.showResults(search);
const elems = document.getElementById("titles").childNodes; const elems = document.getElementById("titles").childNodes;
elems[0].onclick = function() { printTab(0); }; elems[0].onclick = () => { printTab(0); };
elems[1].onclick = function() { printTab(1); }; elems[1].onclick = () => { printTab(1); };
elems[2].onclick = function() { printTab(2); }; elems[2].onclick = () => { printTab(2); };
printTab(currentTab); printTab(currentTab);
} }
@ -1977,7 +1977,7 @@ window.initSearch = function(rawSearchIndex) {
} }
function registerSearchEvents() { function registerSearchEvents() {
const searchAfter500ms = function() { const searchAfter500ms = () => {
searchState.clearInputTimeout(); searchState.clearInputTimeout();
if (searchState.input.value.length === 0) { if (searchState.input.value.length === 0) {
if (browserSupportsHistoryApi()) { if (browserSupportsHistoryApi()) {
@ -1992,7 +1992,7 @@ window.initSearch = function(rawSearchIndex) {
searchState.input.onkeyup = searchAfter500ms; searchState.input.onkeyup = searchAfter500ms;
searchState.input.oninput = searchAfter500ms; searchState.input.oninput = searchAfter500ms;
document.getElementsByClassName("search-form")[0].onsubmit = onSearchSubmit; document.getElementsByClassName("search-form")[0].onsubmit = onSearchSubmit;
searchState.input.onchange = function(e) { searchState.input.onchange = e => {
if (e.target !== document.activeElement) { if (e.target !== document.activeElement) {
// To prevent doing anything when it's from a blur event. // To prevent doing anything when it's from a blur event.
return; return;
@ -2006,7 +2006,7 @@ window.initSearch = function(rawSearchIndex) {
}; };
searchState.input.onpaste = searchState.input.onchange; searchState.input.onpaste = searchState.input.onchange;
searchState.outputElement().addEventListener("keydown", function(e) { searchState.outputElement().addEventListener("keydown", e => {
// We only handle unmodified keystrokes here. We don't want to interfere with, // We only handle unmodified keystrokes here. We don't want to interfere with,
// for instance, alt-left and alt-right for history navigation. // for instance, alt-left and alt-right for history navigation.
if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) { if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
@ -2041,18 +2041,18 @@ window.initSearch = function(rawSearchIndex) {
} }
}); });
searchState.input.addEventListener("keydown", function(e) { searchState.input.addEventListener("keydown", e => {
if (e.which === 40) { // down if (e.which === 40) { // down
focusSearchResult(); focusSearchResult();
e.preventDefault(); e.preventDefault();
} }
}); });
searchState.input.addEventListener("focus", function() { searchState.input.addEventListener("focus", () => {
putBackSearch(); putBackSearch();
}); });
searchState.input.addEventListener("blur", function() { searchState.input.addEventListener("blur", () => {
searchState.input.placeholder = searchState.input.origPlaceholder; searchState.input.placeholder = searchState.input.origPlaceholder;
}); });
@ -2062,7 +2062,7 @@ window.initSearch = function(rawSearchIndex) {
// Store the previous <title> so we can revert back to it later. // Store the previous <title> so we can revert back to it later.
const previousTitle = document.title; const previousTitle = document.title;
window.addEventListener("popstate", function(e) { window.addEventListener("popstate", e => {
const params = searchState.getQueryStringParams(); const params = searchState.getQueryStringParams();
// Revert to the previous title manually since the History // Revert to the previous title manually since the History
// API ignores the title parameter. // API ignores the title parameter.
@ -2098,7 +2098,7 @@ window.initSearch = function(rawSearchIndex) {
// This was an interaction between the back-forward cache and our handlers // This was an interaction between the back-forward cache and our handlers
// that try to sync state between the URL and the search input. To work around it, // that try to sync state between the URL and the search input. To work around it,
// do a small amount of re-init on page show. // do a small amount of re-init on page show.
window.onpageshow = function(){ window.onpageshow = () => {
const qSearch = searchState.getQueryStringParams().search; const qSearch = searchState.getQueryStringParams().search;
if (searchState.input.value === "" && qSearch) { if (searchState.input.value === "" && qSearch) {
searchState.input.value = qSearch; searchState.input.value = qSearch;

View file

@ -1,6 +1,7 @@
/* eslint-env es6 */ /* eslint-env es6 */
/* eslint no-var: "error" */ /* eslint no-var: "error" */
/* eslint prefer-const: "error" */ /* eslint prefer-const: "error" */
/* eslint prefer-arrow-callback: "error" */
// Local js definitions: // Local js definitions:
/* global getSettingValue, getVirtualKey, updateLocalStorage, updateSystemTheme, loadCss */ /* global getSettingValue, getVirtualKey, updateLocalStorage, updateSystemTheme, loadCss */
/* global addClass, removeClass, onEach, onEachLazy, NOT_DISPLAYED_ID */ /* global addClass, removeClass, onEach, onEachLazy, NOT_DISPLAYED_ID */
@ -60,7 +61,7 @@
function setEvents(settingsElement) { function setEvents(settingsElement) {
updateLightAndDark(); updateLightAndDark();
onEachLazy(settingsElement.getElementsByClassName("slider"), function(elem) { onEachLazy(settingsElement.getElementsByClassName("slider"), elem => {
const toggle = elem.previousElementSibling; const toggle = elem.previousElementSibling;
const settingId = toggle.id; const settingId = toggle.id;
const settingValue = getSettingValue(settingId); const settingValue = getSettingValue(settingId);
@ -73,7 +74,7 @@
toggle.onkeyup = handleKey; toggle.onkeyup = handleKey;
toggle.onkeyrelease = handleKey; toggle.onkeyrelease = handleKey;
}); });
onEachLazy(settingsElement.getElementsByClassName("select-wrapper"), function(elem) { onEachLazy(settingsElement.getElementsByClassName("select-wrapper"), elem => {
const select = elem.getElementsByTagName("select")[0]; const select = elem.getElementsByTagName("select")[0];
const settingId = select.id; const settingId = select.id;
const settingValue = getSettingValue(settingId); const settingValue = getSettingValue(settingId);
@ -84,13 +85,13 @@
changeSetting(this.id, this.value); changeSetting(this.id, this.value);
}; };
}); });
onEachLazy(settingsElement.querySelectorAll("input[type=\"radio\"]"), function(elem) { onEachLazy(settingsElement.querySelectorAll("input[type=\"radio\"]"), elem => {
const settingId = elem.name; const settingId = elem.name;
const settingValue = getSettingValue(settingId); const settingValue = getSettingValue(settingId);
if (settingValue !== null && settingValue !== "null") { if (settingValue !== null && settingValue !== "null") {
elem.checked = settingValue === elem.value; elem.checked = settingValue === elem.value;
} }
elem.addEventListener("change", function(ev) { elem.addEventListener("change", ev => {
changeSetting(ev.target.name, ev.target.value); changeSetting(ev.target.name, ev.target.value);
}); });
}); });
@ -118,7 +119,7 @@
output += `<div class="radio-line" id="${js_data_name}">\ output += `<div class="radio-line" id="${js_data_name}">\
<span class="setting-name">${setting_name}</span>\ <span class="setting-name">${setting_name}</span>\
<div class="choices">`; <div class="choices">`;
onEach(setting["options"], function(option) { onEach(setting["options"], option => {
const checked = option === setting["default"] ? " checked" : ""; const checked = option === setting["default"] ? " checked" : "";
output += `<label for="${js_data_name}-${option}" class="choice">\ output += `<label for="${js_data_name}-${option}" class="choice">\
@ -265,7 +266,7 @@
} }
// We now wait a bit for the web browser to end re-computing the DOM... // We now wait a bit for the web browser to end re-computing the DOM...
setTimeout(function() { setTimeout(() => {
setEvents(settingsMenu); setEvents(settingsMenu);
// The setting menu is already displayed if we're on the settings page. // The setting menu is already displayed if we're on the settings page.
if (!isSettingsPage) { if (!isSettingsPage) {

View file

@ -1,6 +1,7 @@
/* eslint-env es6 */ /* eslint-env es6 */
/* eslint no-var: "error" */ /* eslint no-var: "error" */
/* eslint prefer-const: "error" */ /* eslint prefer-const: "error" */
/* eslint prefer-arrow-callback: "error" */
// From rust: // From rust:
/* global search, sourcesIndex */ /* global search, sourcesIndex */
@ -8,7 +9,7 @@
// Local js definitions: // Local js definitions:
/* global addClass, getCurrentValue, hasClass, onEachLazy, removeClass, browserSupportsHistoryApi */ /* global addClass, getCurrentValue, hasClass, onEachLazy, removeClass, browserSupportsHistoryApi */
/* global updateLocalStorage */ /* global updateLocalStorage */
(function() { (function () {
function getCurrentFilePath() { function getCurrentFilePath() {
const parts = window.location.pathname.split("/"); const parts = window.location.pathname.split("/");
@ -32,7 +33,7 @@ function createDirEntry(elem, parent, fullPath, currentFile, hasFoundFile) {
fullPath += elem["name"] + "/"; fullPath += elem["name"] + "/";
name.onclick = function() { name.onclick = () => {
if (hasClass(this, "expand")) { if (hasClass(this, "expand")) {
removeClass(this, "expand"); removeClass(this, "expand");
} else { } else {
@ -134,7 +135,7 @@ function createSourceSidebar() {
title.className = "title"; title.className = "title";
title.innerText = "Files"; title.innerText = "Files";
sidebar.appendChild(title); sidebar.appendChild(title);
Object.keys(sourcesIndex).forEach(function(key) { Object.keys(sourcesIndex).forEach(key => {
sourcesIndex[key].name = key; sourcesIndex[key].name = key;
hasFoundFile = createDirEntry(sourcesIndex[key], sidebar, "", hasFoundFile = createDirEntry(sourcesIndex[key], sidebar, "",
currentFile, hasFoundFile); currentFile, hasFoundFile);
@ -175,8 +176,8 @@ function highlightSourceLines(match) {
if (x) { if (x) {
x.scrollIntoView(); x.scrollIntoView();
} }
onEachLazy(document.getElementsByClassName("line-numbers"), function(e) { onEachLazy(document.getElementsByClassName("line-numbers"), e => {
onEachLazy(e.getElementsByTagName("span"), function(i_e) { onEachLazy(e.getElementsByTagName("span"), i_e => {
removeClass(i_e, "line-highlighted"); removeClass(i_e, "line-highlighted");
}); });
}); });
@ -189,10 +190,10 @@ function highlightSourceLines(match) {
} }
} }
const handleSourceHighlight = (function() { const handleSourceHighlight = (function () {
let prev_line_id = 0; let prev_line_id = 0;
const set_fragment = function(name) { const set_fragment = name => {
const x = window.scrollX, const x = window.scrollX,
y = window.scrollY; y = window.scrollY;
if (browserSupportsHistoryApi()) { if (browserSupportsHistoryApi()) {
@ -205,7 +206,7 @@ const handleSourceHighlight = (function() {
window.scrollTo(x, y); window.scrollTo(x, y);
}; };
return function(ev) { return ev => {
let cur_line_id = parseInt(ev.target.id, 10); let cur_line_id = parseInt(ev.target.id, 10);
ev.preventDefault(); ev.preventDefault();
@ -226,14 +227,14 @@ const handleSourceHighlight = (function() {
}; };
}()); }());
window.addEventListener("hashchange", function() { window.addEventListener("hashchange", () => {
const match = window.location.hash.match(lineNumbersRegex); const match = window.location.hash.match(lineNumbersRegex);
if (match) { if (match) {
return highlightSourceLines(match); return highlightSourceLines(match);
} }
}); });
onEachLazy(document.getElementsByClassName("line-numbers"), function(el) { onEachLazy(document.getElementsByClassName("line-numbers"), el => {
el.addEventListener("click", handleSourceHighlight); el.addEventListener("click", handleSourceHighlight);
}); });

View file

@ -1,6 +1,7 @@
/* eslint-env es6 */ /* eslint-env es6 */
/* eslint no-var: "error" */ /* eslint no-var: "error" */
/* eslint prefer-const: "error" */ /* eslint prefer-const: "error" */
/* eslint prefer-arrow-callback: "error" */
const darkThemes = ["dark", "ayu"]; const darkThemes = ["dark", "ayu"];
window.currentTheme = document.getElementById("themeStyle"); window.currentTheme = document.getElementById("themeStyle");
@ -139,11 +140,11 @@ function switchTheme(styleElem, mainStyleElem, newTheme, saveTheme) {
let found = false; let found = false;
if (savedHref.length === 0) { if (savedHref.length === 0) {
onEachLazy(document.getElementsByTagName("link"), function(el) { onEachLazy(document.getElementsByTagName("link"), el => {
savedHref.push(el.href); savedHref.push(el.href);
}); });
} }
onEach(savedHref, function(el) { onEach(savedHref, el => {
if (el === newHref) { if (el === newHref) {
found = true; found = true;
return true; return true;
@ -170,10 +171,10 @@ function useSystemTheme(value) {
} }
} }
const updateSystemTheme = (function() { const updateSystemTheme = (function () {
if (!window.matchMedia) { if (!window.matchMedia) {
// fallback to the CSS computed value // fallback to the CSS computed value
return function() { return () => {
const cssTheme = getComputedStyle(document.documentElement) const cssTheme = getComputedStyle(document.documentElement)
.getPropertyValue('content'); .getPropertyValue('content');
@ -190,7 +191,7 @@ const updateSystemTheme = (function() {
const mql = window.matchMedia("(prefers-color-scheme: dark)"); const mql = window.matchMedia("(prefers-color-scheme: dark)");
function handlePreferenceChange(mql) { function handlePreferenceChange(mql) {
const use = function(theme) { const use = theme => {
switchTheme(window.currentTheme, window.mainTheme, theme, true); switchTheme(window.currentTheme, window.mainTheme, theme, true);
}; };
// maybe the user has disabled the setting in the meantime! // maybe the user has disabled the setting in the meantime!
@ -214,7 +215,7 @@ const updateSystemTheme = (function() {
mql.addListener(handlePreferenceChange); mql.addListener(handlePreferenceChange);
return function() { return () => {
handlePreferenceChange(mql); handlePreferenceChange(mql);
}; };
})(); })();
@ -252,7 +253,7 @@ if (getSettingValue("use-system-theme") !== "false" && window.matchMedia) {
// For some reason, if we try to change the theme while the `pageshow` event is // For some reason, if we try to change the theme while the `pageshow` event is
// running, it sometimes fails to take effect. The problem manifests on Chrome, // running, it sometimes fails to take effect. The problem manifests on Chrome,
// specifically when talking to a remote website with no caching. // specifically when talking to a remote website with no caching.
window.addEventListener("pageshow", function(ev) { window.addEventListener("pageshow", ev => {
if (ev.persisted) { if (ev.persisted) {
setTimeout(switchToSavedTheme, 0); setTimeout(switchToSavedTheme, 0);
} }