rust/src/librustdoc/html/static/js/main.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1443 lines
55 KiB
JavaScript
Raw Normal View History

// Local js definitions:
2023-09-08 01:45:24 +00:00
/* global addClass, getSettingValue, hasClass, searchState, updateLocalStorage */
/* global onEach, onEachLazy, removeClass, getVar */
2022-05-02 12:32:56 +00:00
"use strict";
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
// The amount of time that the cursor must remain still over a hover target before
// revealing a tooltip.
//
// https://www.nngroup.com/articles/timing-exposing-content/
window.RUSTDOC_TOOLTIP_HOVER_MS = 300;
window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS = 450;
// Given a basename (e.g. "storage") and an extension (e.g. ".js"), return a URL
// for a resource under the root-path, with the resource-suffix.
function resourcePath(basename, extension) {
return getVar("root-path") + basename + getVar("resource-suffix") + extension;
}
2022-01-19 21:36:15 +00:00
function hideMain() {
addClass(document.getElementById(MAIN_ID), "hidden");
}
function showMain() {
removeClass(document.getElementById(MAIN_ID), "hidden");
}
function elemIsInParent(elem, parent) {
while (elem && elem !== document.body) {
if (elem === parent) {
return true;
}
elem = elem.parentElement;
}
return false;
}
function blurHandler(event, parentElem, hideCallback) {
if (!elemIsInParent(document.activeElement, parentElem) &&
!elemIsInParent(event.relatedTarget, parentElem)
) {
hideCallback();
}
}
window.rootPath = getVar("root-path");
window.currentCrate = getVar("current-crate");
function setMobileTopbar() {
// FIXME: It would be nicer to generate this text content directly in HTML,
// but with the current code it's hard to get the right information in the right place.
const mobileTopbar = document.querySelector(".mobile-topbar");
const locationTitle = document.querySelector(".sidebar h2.location");
if (mobileTopbar) {
const mobileTitle = document.createElement("h2");
mobileTitle.className = "location";
rustdoc: show crate name beside small logo This commit changes the layout to something a bit less "look at my logo!!!111" gigantic, and makes it clearer where clicking the logo will actually take you. It also means the crate name is persistently at the top of the sidebar, even when in a sub-item page, and clicking that name takes you back to the root. | | Short crate name | Long crate name | |---------|------------------|-----------------| | Root | ![short-root] | ![long-root] | Subpage | ![short-subpage] | ![long-subpage] [short-root]: https://github.com/rust-lang/rust/assets/1593513/fe2ce102-d4b8-44e6-9f7b-68636a907f56 [short-subpage]: https://github.com/rust-lang/rust/assets/1593513/29501663-56c0-4151-b7de-d2637e167125 [long-root]: https://github.com/rust-lang/rust/assets/1593513/f6a385c0-b4c5-4a9c-954b-21b38de4192f [long-subpage]: https://github.com/rust-lang/rust/assets/1593513/97ec47b4-61bf-4ebe-b461-0d2187b8c6ca https://notriddle.com/rustdoc-html-demo-4/logo-lockup/image/index.html https://notriddle.com/rustdoc-html-demo-4/logo-lockup/crossbeam_channel/index.html https://notriddle.com/rustdoc-html-demo-4/logo-lockup/adler/struct.Adler32.html https://notriddle.com/rustdoc-html-demo-4/logo-lockup/crossbeam_channel/struct.Sender.html This improves visual information density (the construct with the logo and crate name is *shorter* than the logo on its own, because it's not square) and navigation clarity (we can now see what clicking the Rust logo does, specifically). Compare this with the layout at [Phoenix's Hexdocs] (which is what this proposal is closely based on), the old proposal on [Internals Discourse] (which always says "Rust standard library" in the sidebar, but doesn't do the side-by-side layout). [Phoenix's Hexdocs]: https://hexdocs.pm/phoenix/1.7.7/overview.html [Internals Discourse]: https://internals.rust-lang.org/t/poc-of-a-new-design-for-the-generated-rustdoc/11018 In newer versions of rustdoc, the crate name and version are always shown in the sidebar, even in subpages. Clicking the crate name does the same thing clicking the logo always did: return you to the crate root. While this actually takes up less screen real estate than the old layout on desktop, it takes up more HTML. It's also a bit more visually complex. I could do what the Internals POC did and keep the vertically stacked layout all the time, instead of doing a horizontal stack where possible. It would take up more screen real estate, though. This design is lifted almost verbatim from Hexdocs. It seems to work for them. [`opentelemetry_process_propagator`], for example, has a long application name. [`opentelemetry_process_propagator`]: https://hexdocs.pm/opentelemetry_process_propagator/OpentelemetryProcessPropagator.html Has anyone written the rationale on why the Rust logo shows up on projects that aren't the standard library? If we turned it off on non-standard crates by default, it would line wrap crate names a lot less often. Or maybe we should encourage crate authors to include their own logo more often? It certainly helps give people a better sense of "place." I'm not sure of anything that directly follows up this one. Plenty of other changes could be made to improve the layout, like * coming up with a less cluttered way to do disclosure (there's a lot of `[-]` on the page) * doing a better job of separating lateral navigation (vec::Vec links to vec::IntoIter) and the table of contents (vec::Vec links to vec::Vec::new) * giving readers more control of how much rustdoc hows them, and giving doc authors more control of how much it generates * better search that reduces the need to browse But those are mostly orthogonal, not future possibilities unlocked by this change.
2023-09-18 18:59:49 +00:00
if (hasClass(document.body, "crate")) {
mobileTitle.innerText = `Crate ${window.currentCrate}`;
rustdoc: show crate name beside small logo This commit changes the layout to something a bit less "look at my logo!!!111" gigantic, and makes it clearer where clicking the logo will actually take you. It also means the crate name is persistently at the top of the sidebar, even when in a sub-item page, and clicking that name takes you back to the root. | | Short crate name | Long crate name | |---------|------------------|-----------------| | Root | ![short-root] | ![long-root] | Subpage | ![short-subpage] | ![long-subpage] [short-root]: https://github.com/rust-lang/rust/assets/1593513/fe2ce102-d4b8-44e6-9f7b-68636a907f56 [short-subpage]: https://github.com/rust-lang/rust/assets/1593513/29501663-56c0-4151-b7de-d2637e167125 [long-root]: https://github.com/rust-lang/rust/assets/1593513/f6a385c0-b4c5-4a9c-954b-21b38de4192f [long-subpage]: https://github.com/rust-lang/rust/assets/1593513/97ec47b4-61bf-4ebe-b461-0d2187b8c6ca https://notriddle.com/rustdoc-html-demo-4/logo-lockup/image/index.html https://notriddle.com/rustdoc-html-demo-4/logo-lockup/crossbeam_channel/index.html https://notriddle.com/rustdoc-html-demo-4/logo-lockup/adler/struct.Adler32.html https://notriddle.com/rustdoc-html-demo-4/logo-lockup/crossbeam_channel/struct.Sender.html This improves visual information density (the construct with the logo and crate name is *shorter* than the logo on its own, because it's not square) and navigation clarity (we can now see what clicking the Rust logo does, specifically). Compare this with the layout at [Phoenix's Hexdocs] (which is what this proposal is closely based on), the old proposal on [Internals Discourse] (which always says "Rust standard library" in the sidebar, but doesn't do the side-by-side layout). [Phoenix's Hexdocs]: https://hexdocs.pm/phoenix/1.7.7/overview.html [Internals Discourse]: https://internals.rust-lang.org/t/poc-of-a-new-design-for-the-generated-rustdoc/11018 In newer versions of rustdoc, the crate name and version are always shown in the sidebar, even in subpages. Clicking the crate name does the same thing clicking the logo always did: return you to the crate root. While this actually takes up less screen real estate than the old layout on desktop, it takes up more HTML. It's also a bit more visually complex. I could do what the Internals POC did and keep the vertically stacked layout all the time, instead of doing a horizontal stack where possible. It would take up more screen real estate, though. This design is lifted almost verbatim from Hexdocs. It seems to work for them. [`opentelemetry_process_propagator`], for example, has a long application name. [`opentelemetry_process_propagator`]: https://hexdocs.pm/opentelemetry_process_propagator/OpentelemetryProcessPropagator.html Has anyone written the rationale on why the Rust logo shows up on projects that aren't the standard library? If we turned it off on non-standard crates by default, it would line wrap crate names a lot less often. Or maybe we should encourage crate authors to include their own logo more often? It certainly helps give people a better sense of "place." I'm not sure of anything that directly follows up this one. Plenty of other changes could be made to improve the layout, like * coming up with a less cluttered way to do disclosure (there's a lot of `[-]` on the page) * doing a better job of separating lateral navigation (vec::Vec links to vec::IntoIter) and the table of contents (vec::Vec links to vec::Vec::new) * giving readers more control of how much rustdoc hows them, and giving doc authors more control of how much it generates * better search that reduces the need to browse But those are mostly orthogonal, not future possibilities unlocked by this change.
2023-09-18 18:59:49 +00:00
} else if (locationTitle) {
mobileTitle.innerHTML = locationTitle.innerHTML;
rustdoc: show crate name beside small logo This commit changes the layout to something a bit less "look at my logo!!!111" gigantic, and makes it clearer where clicking the logo will actually take you. It also means the crate name is persistently at the top of the sidebar, even when in a sub-item page, and clicking that name takes you back to the root. | | Short crate name | Long crate name | |---------|------------------|-----------------| | Root | ![short-root] | ![long-root] | Subpage | ![short-subpage] | ![long-subpage] [short-root]: https://github.com/rust-lang/rust/assets/1593513/fe2ce102-d4b8-44e6-9f7b-68636a907f56 [short-subpage]: https://github.com/rust-lang/rust/assets/1593513/29501663-56c0-4151-b7de-d2637e167125 [long-root]: https://github.com/rust-lang/rust/assets/1593513/f6a385c0-b4c5-4a9c-954b-21b38de4192f [long-subpage]: https://github.com/rust-lang/rust/assets/1593513/97ec47b4-61bf-4ebe-b461-0d2187b8c6ca https://notriddle.com/rustdoc-html-demo-4/logo-lockup/image/index.html https://notriddle.com/rustdoc-html-demo-4/logo-lockup/crossbeam_channel/index.html https://notriddle.com/rustdoc-html-demo-4/logo-lockup/adler/struct.Adler32.html https://notriddle.com/rustdoc-html-demo-4/logo-lockup/crossbeam_channel/struct.Sender.html This improves visual information density (the construct with the logo and crate name is *shorter* than the logo on its own, because it's not square) and navigation clarity (we can now see what clicking the Rust logo does, specifically). Compare this with the layout at [Phoenix's Hexdocs] (which is what this proposal is closely based on), the old proposal on [Internals Discourse] (which always says "Rust standard library" in the sidebar, but doesn't do the side-by-side layout). [Phoenix's Hexdocs]: https://hexdocs.pm/phoenix/1.7.7/overview.html [Internals Discourse]: https://internals.rust-lang.org/t/poc-of-a-new-design-for-the-generated-rustdoc/11018 In newer versions of rustdoc, the crate name and version are always shown in the sidebar, even in subpages. Clicking the crate name does the same thing clicking the logo always did: return you to the crate root. While this actually takes up less screen real estate than the old layout on desktop, it takes up more HTML. It's also a bit more visually complex. I could do what the Internals POC did and keep the vertically stacked layout all the time, instead of doing a horizontal stack where possible. It would take up more screen real estate, though. This design is lifted almost verbatim from Hexdocs. It seems to work for them. [`opentelemetry_process_propagator`], for example, has a long application name. [`opentelemetry_process_propagator`]: https://hexdocs.pm/opentelemetry_process_propagator/OpentelemetryProcessPropagator.html Has anyone written the rationale on why the Rust logo shows up on projects that aren't the standard library? If we turned it off on non-standard crates by default, it would line wrap crate names a lot less often. Or maybe we should encourage crate authors to include their own logo more often? It certainly helps give people a better sense of "place." I'm not sure of anything that directly follows up this one. Plenty of other changes could be made to improve the layout, like * coming up with a less cluttered way to do disclosure (there's a lot of `[-]` on the page) * doing a better job of separating lateral navigation (vec::Vec links to vec::IntoIter) and the table of contents (vec::Vec links to vec::Vec::new) * giving readers more control of how much rustdoc hows them, and giving doc authors more control of how much it generates * better search that reduces the need to browse But those are mostly orthogonal, not future possibilities unlocked by this change.
2023-09-18 18:59:49 +00:00
}
mobileTopbar.appendChild(mobileTitle);
}
}
// Gets the human-readable string for the virtual-key code of the
// given KeyboardEvent, ev.
//
// This function is meant as a polyfill for KeyboardEvent#key,
// since it is not supported in IE 11 or Chrome for Android. We also test for
// KeyboardEvent#keyCode because the handleShortcut handler is
// also registered for the keydown event, because Blink doesn't fire
// keypress on hitting the Escape key.
//
// So I guess you could say things are getting pretty interoperable.
function getVirtualKey(ev) {
2022-05-27 20:30:19 +00:00
if ("key" in ev && typeof ev.key !== "undefined") {
return ev.key;
}
2022-04-25 12:23:17 +00:00
const c = ev.charCode || ev.keyCode;
2022-05-27 20:30:19 +00:00
if (c === 27) {
return "Escape";
}
return String.fromCharCode(c);
}
2022-04-25 12:23:17 +00:00
const MAIN_ID = "main-content";
2022-01-19 21:36:15 +00:00
const SETTINGS_BUTTON_ID = "settings-menu";
const ALTERNATIVE_DISPLAY_ID = "alternative-display";
const NOT_DISPLAYED_ID = "not-displayed";
const HELP_BUTTON_ID = "help-button";
2021-03-05 15:16:03 +00:00
2022-01-19 21:36:15 +00:00
function getSettingsButton() {
return document.getElementById(SETTINGS_BUTTON_ID);
}
function getHelpButton() {
return document.getElementById(HELP_BUTTON_ID);
}
// Returns the current URL without any query parameter or hash.
function getNakedUrl() {
return window.location.href.split("?")[0].split("#")[0];
}
2022-01-19 21:36:15 +00:00
/**
* This function inserts `newNode` after `referenceNode`. It doesn't work if `referenceNode`
* doesn't have a parent node.
*
* @param {HTMLElement} newNode
* @param {HTMLElement} referenceNode
2022-01-19 21:36:15 +00:00
*/
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/**
* This function creates a new `<section>` with the given `id` and `classes` if it doesn't already
* exist.
*
* More information about this in `switchDisplayedElement` documentation.
*
* @param {string} id
* @param {string} classes
*/
function getOrCreateSection(id, classes) {
let el = document.getElementById(id);
if (!el) {
el = document.createElement("section");
el.id = id;
el.className = classes;
insertAfter(el, document.getElementById(MAIN_ID));
}
return el;
}
/**
* Returns the `<section>` element which contains the displayed element.
*
* @return {HTMLElement}
2022-01-19 21:36:15 +00:00
*/
function getAlternativeDisplayElem() {
return getOrCreateSection(ALTERNATIVE_DISPLAY_ID, "content hidden");
}
/**
* Returns the `<section>` element which contains the not-displayed elements.
*
* @return {HTMLElement}
2022-01-19 21:36:15 +00:00
*/
function getNotDisplayedElem() {
return getOrCreateSection(NOT_DISPLAYED_ID, "hidden");
}
/**
* To nicely switch between displayed "extra" elements (such as search results or settings menu)
* and to alternate between the displayed and not displayed elements, we hold them in two different
* `<section>` elements. They work in pair: one holds the hidden elements while the other
2022-01-19 21:36:15 +00:00
* contains the displayed element (there can be only one at the same time!). So basically, we switch
* elements between the two `<section>` elements.
*
* @param {HTMLElement} elemToDisplay
2022-01-19 21:36:15 +00:00
*/
function switchDisplayedElement(elemToDisplay) {
const el = getAlternativeDisplayElem();
if (el.children.length > 0) {
getNotDisplayedElem().appendChild(el.firstElementChild);
}
if (elemToDisplay === null) {
addClass(el, "hidden");
showMain();
return;
}
el.appendChild(elemToDisplay);
hideMain();
removeClass(el, "hidden");
}
function browserSupportsHistoryApi() {
return window.history && typeof window.history.pushState === "function";
}
function preLoadCss(cssUrl) {
// https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/preload
const link = document.createElement("link");
link.href = cssUrl;
link.rel = "preload";
link.as = "style";
document.getElementsByTagName("head")[0].appendChild(link);
}
(function() {
const isHelpPage = window.location.pathname.endsWith("/help.html");
2022-01-19 21:36:15 +00:00
function loadScript(url) {
2022-05-07 18:18:23 +00:00
const script = document.createElement("script");
2022-01-19 21:36:15 +00:00
script.src = url;
document.head.append(script);
}
getSettingsButton().onclick = event => {
if (event.ctrlKey || event.altKey || event.metaKey) {
return;
}
window.hideAllModals(false);
addClass(getSettingsButton(), "rotate");
2022-01-19 21:36:15 +00:00
event.preventDefault();
// Sending request for the CSS and the JS files at the same time so it will
// hopefully be loaded when the JS will generate the settings content.
loadScript(getVar("static-root-path") + getVar("settings-js"));
// Pre-load all theme CSS files, so that switching feels seamless.
//
// When loading settings.html as a standalone page, the equivalent HTML is
// generated in context.rs.
setTimeout(() => {
const themes = getVar("themes").split(",");
for (const theme of themes) {
// if there are no themes, do nothing
// "".split(",") == [""]
if (theme !== "") {
preLoadCss(getVar("root-path") + theme + ".css");
}
}
}, 0);
2022-01-19 21:36:15 +00:00
};
window.searchState = {
2021-05-11 09:47:39 +00:00
loadingText: "Loading search results...",
input: document.getElementsByClassName("search-input")[0],
outputElement: () => {
2022-01-19 21:36:15 +00:00
let el = document.getElementById("search");
if (!el) {
el = document.createElement("section");
el.id = "search";
getNotDisplayedElem().appendChild(el);
}
return el;
2021-05-11 09:47:39 +00:00
},
title: document.title,
2021-05-11 09:47:39 +00:00
titleBeforeSearch: document.title,
timeout: null,
// On the search screen, so you remain on the last tab you opened.
//
// 0 for "In Names"
// 1 for "In Parameters"
// 2 for "In Return Types"
currentTab: 0,
2021-05-09 19:56:21 +00:00
// tab and back preserves the element that was focused.
focusedByTab: [null, null, null],
clearInputTimeout: () => {
2021-05-11 09:47:39 +00:00
if (searchState.timeout !== null) {
clearTimeout(searchState.timeout);
searchState.timeout = null;
}
},
isDisplayed: () => searchState.outputElement().parentElement.id === ALTERNATIVE_DISPLAY_ID,
2021-05-11 09:47:39 +00:00
// Sets the focus on the search bar at the top of the page
focus: () => {
2021-05-11 09:47:39 +00:00
searchState.input.focus();
},
// Removes the focus from the search bar.
defocus: () => {
2021-05-11 09:47:39 +00:00
searchState.input.blur();
},
showResults: search => {
2022-05-07 18:18:23 +00:00
if (search === null || typeof search === "undefined") {
2021-05-11 09:47:39 +00:00
search = searchState.outputElement();
}
2022-01-19 21:36:15 +00:00
switchDisplayedElement(search);
2021-05-11 09:47:39 +00:00
searchState.mouseMovedAfterSearch = false;
document.title = searchState.title;
2021-05-11 09:47:39 +00:00
},
removeQueryParameters: () => {
// We change the document title.
2021-05-11 09:47:39 +00:00
document.title = searchState.titleBeforeSearch;
2022-01-19 21:36:15 +00:00
if (browserSupportsHistoryApi()) {
history.replaceState(null, "", getNakedUrl() + window.location.hash);
2021-05-11 09:47:39 +00:00
}
},
hideResults: () => {
switchDisplayedElement(null);
// We also remove the query parameter from the URL.
searchState.removeQueryParameters();
},
getQueryStringParams: () => {
2022-04-25 12:23:17 +00:00
const params = {};
2021-05-11 09:47:39 +00:00
window.location.search.substring(1).split("&").
map(s => {
2022-04-25 12:23:17 +00:00
const pair = s.split("=");
2021-05-11 09:47:39 +00:00
params[decodeURIComponent(pair[0])] =
typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
});
return params;
},
setup: () => {
2022-04-25 12:23:17 +00:00
const search_input = searchState.input;
2021-05-11 09:47:39 +00:00
if (!searchState.input) {
return;
}
2022-04-25 12:23:17 +00:00
let searchLoaded = false;
2021-05-11 09:47:39 +00:00
function loadSearch() {
if (!searchLoaded) {
searchLoaded = true;
loadScript(getVar("static-root-path") + getVar("search-js"));
loadScript(resourcePath("search-index", ".js"));
2021-05-11 09:47:39 +00:00
}
}
2017-10-14 14:31:48 +00:00
search_input.addEventListener("focus", () => {
2022-01-10 13:57:43 +00:00
search_input.origPlaceholder = search_input.placeholder;
2021-05-11 09:47:39 +00:00
search_input.placeholder = "Type your search here.";
loadSearch();
});
2022-05-07 18:18:23 +00:00
if (search_input.value !== "") {
loadSearch();
}
2022-04-25 12:23:17 +00:00
const params = searchState.getQueryStringParams();
2021-05-11 09:47:39 +00:00
if (params.search !== undefined) {
searchState.setLoadingSearch();
2021-05-11 09:47:39 +00:00
loadSearch();
}
},
setLoadingSearch: () => {
const search = searchState.outputElement();
search.innerHTML = "<h3 class=\"search-loading\">" + searchState.loadingText + "</h3>";
searchState.showResults(search);
},
};
2022-04-25 12:23:17 +00:00
const toggleAllDocsId = "toggle-all-docs";
let savedHash = "";
2018-11-26 16:17:38 +00:00
function handleHashes(ev) {
2022-01-19 21:36:15 +00:00
if (ev !== null && searchState.isDisplayed() && ev.newURL) {
// This block occurs when clicking on an element in the navbar while
// in a search.
2022-01-19 21:36:15 +00:00
switchDisplayedElement(null);
2022-04-25 12:23:17 +00:00
const hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
2022-01-19 21:36:15 +00:00
if (browserSupportsHistoryApi()) {
// `window.location.search`` contains all the query parameters, not just `search`.
2022-01-10 13:57:43 +00:00
history.replaceState(null, "",
getNakedUrl() + window.location.search + "#" + hash);
2017-11-10 18:40:46 +00:00
}
2022-01-19 21:36:15 +00:00
const elem = document.getElementById(hash);
2017-11-06 20:14:37 +00:00
if (elem) {
elem.scrollIntoView();
}
}
// This part is used in case an element is not visible.
const pageId = window.location.hash.replace(/^#/, "");
if (savedHash !== pageId) {
savedHash = pageId;
if (pageId !== "") {
expandSection(pageId);
}
}
if (savedHash.startsWith("impl-")) {
// impl-disambiguated links, used by the search engine
// format: impl-X[-for-Y]/method.WHATEVER
// turn this into method.WHATEVER[-NUMBER]
const splitAt = savedHash.indexOf("/");
if (splitAt !== -1) {
const implId = savedHash.slice(0, splitAt);
const assocId = savedHash.slice(splitAt + 1);
const implElem = document.getElementById(implId);
if (implElem && implElem.parentElement.tagName === "SUMMARY" &&
implElem.parentElement.parentElement.tagName === "DETAILS") {
onEachLazy(implElem.parentElement.parentElement.querySelectorAll(
`[id^="${assocId}"]`),
item => {
const numbered = /([^-]+)-([0-9]+)/.exec(item.id);
if (item.id === assocId || (numbered && numbered[1] === assocId)) {
openParentDetails(item);
item.scrollIntoView();
// Let the section expand itself before trying to highlight
setTimeout(() => {
window.location.replace("#" + item.id);
}, 0);
}
}
);
}
}
}
}
function onHashChange(ev) {
// If we're in mobile mode, we should hide the sidebar in any case.
hideSidebar();
handleHashes(ev);
}
function openParentDetails(elem) {
while (elem) {
if (elem.tagName === "DETAILS") {
elem.open = true;
}
elem = elem.parentNode;
}
}
function expandSection(id) {
2021-05-08 12:21:57 +00:00
openParentDetails(document.getElementById(id));
}
2019-09-09 15:04:28 +00:00
function handleEscape(ev) {
2022-01-19 21:36:15 +00:00
searchState.clearInputTimeout();
searchState.hideResults();
ev.preventDefault();
searchState.defocus();
window.hideAllModals(true); // true = reset focus for tooltips
2018-03-18 15:32:41 +00:00
}
2018-03-18 15:32:41 +00:00
function handleShortcut(ev) {
// Don't interfere with browser shortcuts
const disableShortcuts = getSettingValue("disable-shortcuts") === "true";
if (ev.ctrlKey || ev.altKey || ev.metaKey || disableShortcuts) {
return;
}
if (document.activeElement.tagName === "INPUT" &&
document.activeElement.type !== "checkbox" &&
document.activeElement.type !== "radio") {
2018-03-18 15:32:41 +00:00
switch (getVirtualKey(ev)) {
case "Escape":
2019-09-09 15:04:28 +00:00
handleEscape(ev);
2018-03-18 15:32:41 +00:00
break;
}
2018-03-18 15:32:41 +00:00
} else {
switch (getVirtualKey(ev)) {
case "Escape":
2019-09-09 15:04:28 +00:00
handleEscape(ev);
2018-03-18 15:32:41 +00:00
break;
2018-03-18 15:32:41 +00:00
case "s":
case "S":
ev.preventDefault();
searchState.focus();
2018-03-18 15:32:41 +00:00
break;
2018-03-18 15:32:41 +00:00
case "+":
ev.preventDefault();
expandAllDocs();
break;
2018-03-18 15:32:41 +00:00
case "-":
ev.preventDefault();
collapseAllDocs();
2018-03-18 15:32:41 +00:00
break;
2018-03-18 15:32:41 +00:00
case "?":
showHelp();
2018-03-18 15:32:41 +00:00
break;
default:
2022-05-11 21:11:18 +00:00
break;
}
}
}
document.addEventListener("keypress", handleShortcut);
document.addEventListener("keydown", handleShortcut);
function addSidebarItems() {
if (!window.SIDEBAR_ITEMS) {
return;
}
const sidebar = document.getElementsByClassName("sidebar-elems")[0];
/**
* Append to the sidebar a "block" of links - a heading along with a list (`<ul>`) of items.
*
* @param {string} shortty - A short type name, like "primitive", "mod", or "macro"
* @param {string} id - The HTML id of the corresponding section on the module page.
* @param {string} longty - A long, capitalized, plural name, like "Primitive Types",
* "Modules", or "Macros".
*/
function block(shortty, id, longty) {
const filtered = window.SIDEBAR_ITEMS[shortty];
if (!filtered) {
return;
}
const modpath = hasClass(document.body, "mod") ? "../" : "";
2022-04-25 12:23:17 +00:00
const h3 = document.createElement("h3");
h3.innerHTML = `<a href="${modpath}index.html#${id}">${longty}</a>`;
2022-04-25 12:23:17 +00:00
const ul = document.createElement("ul");
ul.className = "block " + shortty;
for (const name of filtered) {
2022-04-25 12:23:17 +00:00
let path;
if (shortty === "mod") {
path = `${modpath}${name}/index.html`;
} else {
path = `${modpath}${shortty}.${name}.html`;
}
let current_page = document.location.href.toString();
if (current_page.endsWith("/")) {
current_page += "index.html";
}
2022-04-25 12:23:17 +00:00
const link = document.createElement("a");
link.href = path;
2023-09-08 01:45:24 +00:00
if (path === current_page) {
link.className = "current";
}
2017-04-14 14:37:09 +00:00
link.textContent = name;
2022-04-25 12:23:17 +00:00
const li = document.createElement("li");
2017-04-14 14:37:09 +00:00
li.appendChild(link);
ul.appendChild(li);
}
sidebar.appendChild(h3);
sidebar.appendChild(ul);
}
if (sidebar) {
// keep this synchronized with ItemSection::ALL in html/render/mod.rs
// Re-exports aren't shown here, because they don't have child pages
//block("reexport", "reexports", "Re-exports");
block("primitive", "primitives", "Primitive Types");
block("mod", "modules", "Modules");
block("macro", "macros", "Macros");
block("struct", "structs", "Structs");
block("enum", "enums", "Enums");
block("constant", "constants", "Constants");
block("static", "static", "Statics");
block("trait", "traits", "Traits");
block("fn", "functions", "Functions");
block("type", "types", "Type Aliases");
block("union", "unions", "Unions");
// No point, because these items don't appear in modules
//block("impl", "impls", "Implementations");
//block("tymethod", "tymethods", "Type Methods");
//block("method", "methods", "Methods");
//block("structfield", "fields", "Fields");
//block("variant", "variants", "Variants");
//block("associatedtype", "associated-types", "Associated Types");
//block("associatedconstant", "associated-consts", "Associated Constants");
block("foreigntype", "foreign-types", "Foreign Types");
block("keyword", "keywords", "Keywords");
block("opaque", "opaque-types", "Opaque Types");
block("attr", "attributes", "Attribute Macros");
block("derive", "derives", "Derive Macros");
block("traitalias", "trait-aliases", "Trait Aliases");
}
}
window.register_implementors = imp => {
2022-04-25 12:23:17 +00:00
const implementors = document.getElementById("implementors-list");
const synthetic_implementors = document.getElementById("synthetic-implementors-list");
const inlined_types = new Set();
2018-02-15 23:45:52 +00:00
const TEXT_IDX = 0;
const SYNTHETIC_IDX = 1;
const TYPES_IDX = 2;
2020-01-28 12:48:08 +00:00
if (synthetic_implementors) {
// This `inlined_types` variable is used to avoid having the same implementation
// showing up twice. For example "String" in the "Sync" doc page.
//
// By the way, this is only used by and useful for traits implemented automatically
// (like "Send" and "Sync").
onEachLazy(synthetic_implementors.getElementsByClassName("impl"), el => {
2022-04-25 12:23:17 +00:00
const aliases = el.getAttribute("data-aliases");
2020-01-28 12:48:08 +00:00
if (!aliases) {
return;
}
aliases.split(",").forEach(alias => {
2020-01-28 12:48:08 +00:00
inlined_types.add(alias);
});
});
2020-01-28 12:48:08 +00:00
}
2022-04-25 12:23:17 +00:00
let currentNbImpls = implementors.getElementsByClassName("impl").length;
const traitName = document.querySelector(".main-heading h1 > .trait").textContent;
2022-04-25 12:23:17 +00:00
const baseIdName = "impl-" + traitName + "-";
const libs = Object.getOwnPropertyNames(imp);
// We don't want to include impls from this JS file, when the HTML already has them.
// The current crate should always be ignored. Other crates that should also be
// ignored are included in the attribute `data-ignore-extern-crates`.
const script = document
.querySelector("script[data-ignore-extern-crates]");
const ignoreExternCrates = new Set(
(script ? script.getAttribute("data-ignore-extern-crates") : "").split(",")
);
2022-04-25 12:23:17 +00:00
for (const lib of libs) {
if (lib === window.currentCrate || ignoreExternCrates.has(lib)) {
2022-04-25 12:23:17 +00:00
continue;
}
const structs = imp[lib];
2018-02-10 19:34:46 +00:00
struct_loop:
2022-04-25 12:23:17 +00:00
for (const struct of structs) {
const list = struct[SYNTHETIC_IDX] ? synthetic_implementors : implementors;
Generate documentation for auto-trait impls A new section is added to both both struct and trait doc pages. On struct/enum pages, a new 'Auto Trait Implementations' section displays any synthetic implementations for auto traits. Currently, this is only done for Send and Sync. On trait pages, a new 'Auto Implementors' section displays all types which automatically implement the trait. Effectively, this is a list of all public types in the standard library. Synthesized impls for a particular auto trait ('synthetic impls') take into account generic bounds. For example, a type 'struct Foo<T>(T)' will have 'impl<T> Send for Foo<T> where T: Send' generated for it. Manual implementations of auto traits are also taken into account. If we have the following types: 'struct Foo<T>(T)' 'struct Wrapper<T>(Foo<T>)' 'unsafe impl<T> Send for Wrapper<T>' // pretend that Wrapper<T> makes this sound somehow Then Wrapper will have the following impl generated: 'impl<T> Send for Wrapper<T>' reflecting the fact that 'T: Send' need not hold for 'Wrapper<T>: Send' to hold Lifetimes, HRTBS, and projections (e.g. '<T as Iterator>::Item') are taken into account by synthetic impls However, if a type can *never* implement a particular auto trait (e.g. 'struct MyStruct<T>(*const T)'), then a negative impl will be generated (in this case, 'impl<T> !Send for MyStruct<T>') All of this means that a user should be able to copy-paste a synthetic impl into their code, without any observable changes in behavior (assuming the rest of the program remains unchanged).
2017-11-22 21:16:55 +00:00
// The types list is only used for synthetic impls.
// If this changes, `main.js` and `write_shared.rs` both need changed.
if (struct[SYNTHETIC_IDX]) {
for (const struct_type of struct[TYPES_IDX]) {
2022-04-25 12:23:17 +00:00
if (inlined_types.has(struct_type)) {
2018-02-15 23:45:52 +00:00
continue struct_loop;
}
2022-04-25 12:23:17 +00:00
inlined_types.add(struct_type);
Generate documentation for auto-trait impls A new section is added to both both struct and trait doc pages. On struct/enum pages, a new 'Auto Trait Implementations' section displays any synthetic implementations for auto traits. Currently, this is only done for Send and Sync. On trait pages, a new 'Auto Implementors' section displays all types which automatically implement the trait. Effectively, this is a list of all public types in the standard library. Synthesized impls for a particular auto trait ('synthetic impls') take into account generic bounds. For example, a type 'struct Foo<T>(T)' will have 'impl<T> Send for Foo<T> where T: Send' generated for it. Manual implementations of auto traits are also taken into account. If we have the following types: 'struct Foo<T>(T)' 'struct Wrapper<T>(Foo<T>)' 'unsafe impl<T> Send for Wrapper<T>' // pretend that Wrapper<T> makes this sound somehow Then Wrapper will have the following impl generated: 'impl<T> Send for Wrapper<T>' reflecting the fact that 'T: Send' need not hold for 'Wrapper<T>: Send' to hold Lifetimes, HRTBS, and projections (e.g. '<T as Iterator>::Item') are taken into account by synthetic impls However, if a type can *never* implement a particular auto trait (e.g. 'struct MyStruct<T>(*const T)'), then a negative impl will be generated (in this case, 'impl<T> !Send for MyStruct<T>') All of this means that a user should be able to copy-paste a synthetic impl into their code, without any observable changes in behavior (assuming the rest of the program remains unchanged).
2017-11-22 21:16:55 +00:00
}
}
2022-04-25 12:23:17 +00:00
const code = document.createElement("h3");
code.innerHTML = struct[TEXT_IDX];
addClass(code, "code-header");
2017-04-14 14:37:09 +00:00
onEachLazy(code.getElementsByTagName("a"), elem => {
2022-04-25 12:23:17 +00:00
const href = elem.getAttribute("href");
if (href && !/^(?:[a-z+]+:)?\/\//.test(href)) {
2021-01-18 11:03:53 +00:00
elem.setAttribute("href", window.rootPath + href);
2014-06-01 17:17:30 +00:00
}
});
2022-04-25 12:23:17 +00:00
const currentId = baseIdName + currentNbImpls;
const anchor = document.createElement("a");
anchor.href = "#" + currentId;
addClass(anchor, "anchor");
2022-04-25 12:23:17 +00:00
const display = document.createElement("div");
display.id = currentId;
2018-07-01 14:11:14 +00:00
addClass(display, "impl");
display.appendChild(anchor);
display.appendChild(code);
2018-07-01 14:11:14 +00:00
list.appendChild(display);
currentNbImpls += 1;
}
}
};
if (window.pending_implementors) {
window.register_implementors(window.pending_implementors);
}
function addSidebarCrates() {
if (!window.ALL_CRATES) {
return;
}
const sidebarElems = document.getElementsByClassName("sidebar-elems")[0];
if (!sidebarElems) {
return;
}
// Draw a convenient sidebar of known crates if we have a listing
const h3 = document.createElement("h3");
h3.innerHTML = "Crates";
const ul = document.createElement("ul");
ul.className = "block crate";
for (const crate of window.ALL_CRATES) {
const link = document.createElement("a");
link.href = window.rootPath + crate + "/index.html";
link.textContent = crate;
const li = document.createElement("li");
2023-09-08 01:45:24 +00:00
if (window.rootPath !== "./" && crate === window.currentCrate) {
li.className = "current";
}
li.appendChild(link);
ul.appendChild(li);
}
sidebarElems.appendChild(h3);
sidebarElems.appendChild(ul);
}
function expandAllDocs() {
const innerToggle = document.getElementById(toggleAllDocsId);
removeClass(innerToggle, "will-expand");
onEachLazy(document.getElementsByClassName("toggle"), e => {
if (!hasClass(e, "type-contents-toggle") && !hasClass(e, "more-examples-toggle")) {
e.open = true;
}
});
innerToggle.title = "collapse all docs";
innerToggle.children[0].innerText = "\u2212"; // "\u2212" is "" minus sign
}
function collapseAllDocs() {
const innerToggle = document.getElementById(toggleAllDocsId);
addClass(innerToggle, "will-expand");
onEachLazy(document.getElementsByClassName("toggle"), e => {
if (e.parentNode.id !== "implementations-list" ||
(!hasClass(e, "implementors-toggle") &&
!hasClass(e, "type-contents-toggle"))
) {
e.open = false;
}
});
innerToggle.title = "expand all docs";
innerToggle.children[0].innerText = "+";
}
2021-05-08 12:21:57 +00:00
function toggleAllDocs() {
2022-04-25 12:23:17 +00:00
const innerToggle = document.getElementById(toggleAllDocsId);
2018-11-26 16:17:38 +00:00
if (!innerToggle) {
return;
}
2018-11-26 16:17:38 +00:00
if (hasClass(innerToggle, "will-expand")) {
expandAllDocs();
} else {
collapseAllDocs();
}
}
(function() {
2022-04-25 12:23:17 +00:00
const toggles = document.getElementById(toggleAllDocsId);
2020-08-28 11:30:21 +00:00
if (toggles) {
toggles.onclick = toggleAllDocs;
}
2022-04-25 12:23:17 +00:00
const hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true";
const hideImplementations = getSettingValue("auto-hide-trait-implementations") === "true";
const hideLargeItemContents = getSettingValue("auto-hide-large-items") !== "false";
function setImplementorsTogglesOpen(id, open) {
2022-04-25 12:23:17 +00:00
const list = document.getElementById(id);
if (list !== null) {
onEachLazy(list.getElementsByClassName("implementors-toggle"), e => {
e.open = open;
});
}
}
if (hideImplementations) {
setImplementorsTogglesOpen("trait-implementations-list", false);
setImplementorsTogglesOpen("blanket-implementations-list", false);
}
onEachLazy(document.getElementsByClassName("toggle"), e => {
if (!hideLargeItemContents && hasClass(e, "type-contents-toggle")) {
e.open = true;
}
if (hideMethodDocs && hasClass(e, "method-toggle")) {
e.open = false;
}
});
}());
2017-04-14 14:37:09 +00:00
window.rustdoc_add_line_numbers_to_examples = () => {
onEachLazy(document.getElementsByClassName("rust-example-rendered"), x => {
const parent = x.parentNode;
const line_numbers = parent.querySelectorAll(".example-line-numbers");
if (line_numbers.length > 0) {
return;
}
const count = x.textContent.split("\n").length;
const elems = [];
for (let i = 0; i < count; ++i) {
elems.push(i + 1);
}
const node = document.createElement("pre");
addClass(node, "example-line-numbers");
node.innerHTML = elems.join("\n");
parent.insertBefore(node, x);
});
};
window.rustdoc_remove_line_numbers_from_examples = () => {
onEachLazy(document.getElementsByClassName("rust-example-rendered"), x => {
const parent = x.parentNode;
const line_numbers = parent.querySelectorAll(".example-line-numbers");
for (const node of line_numbers) {
parent.removeChild(node);
}
});
};
if (getSettingValue("line-numbers") === "true") {
window.rustdoc_add_line_numbers_to_examples();
}
2017-11-10 18:40:46 +00:00
function showSidebar() {
window.hideAllModals(false);
const sidebar = document.getElementsByClassName("sidebar")[0];
addClass(sidebar, "shown");
}
function hideSidebar() {
2022-04-25 12:23:17 +00:00
const sidebar = document.getElementsByClassName("sidebar")[0];
removeClass(sidebar, "shown");
}
window.addEventListener("resize", () => {
if (window.CURRENT_TOOLTIP_ELEMENT) {
// As a workaround to the behavior of `contains: layout` used in doc togglers,
// tooltip popovers are positioned using javascript.
//
// This means when the window is resized, we need to redo the layout.
const base = window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE;
const force_visible = base.TOOLTIP_FORCE_VISIBLE;
hideTooltip(false);
if (force_visible) {
showTooltip(base);
base.TOOLTIP_FORCE_VISIBLE = true;
}
}
});
const mainElem = document.getElementById(MAIN_ID);
if (mainElem) {
mainElem.addEventListener("click", hideSidebar);
}
onEachLazy(document.querySelectorAll("a[href^='#']"), el => {
// 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
// the height of the document so we wind up scrolled to the wrong place.
el.addEventListener("click", () => {
expandSection(el.hash.slice(1));
hideSidebar();
});
});
onEachLazy(document.querySelectorAll(".toggle > summary:not(.hideme)"), el => {
el.addEventListener("click", e => {
if (e.target.tagName !== "SUMMARY" && e.target.tagName !== "A") {
e.preventDefault();
}
});
});
/**
* Show a tooltip immediately.
*
* @param {DOMElement} e - The tooltip's anchor point. The DOM is consulted to figure
* out what the tooltip should contain, and where it should be
* positioned.
*/
function showTooltip(e) {
const notable_ty = e.getAttribute("data-notable-ty");
if (!window.NOTABLE_TRAITS && notable_ty) {
const data = document.getElementById("notable-traits-data");
if (data) {
window.NOTABLE_TRAITS = JSON.parse(data.innerText);
} else {
throw new Error("showTooltip() called with notable without any notable traits!");
}
}
// Make this function idempotent. If the tooltip is already shown, avoid doing extra work
// and leave it alone.
if (window.CURRENT_TOOLTIP_ELEMENT && window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE === e) {
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);
return;
}
window.hideAllModals(false);
const wrapper = document.createElement("div");
if (notable_ty) {
wrapper.innerHTML = "<div class=\"content\">" +
window.NOTABLE_TRAITS[notable_ty] + "</div>";
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
} else {
// Replace any `title` attribute with `data-title` to avoid double tooltips.
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
if (e.getAttribute("title") !== null) {
e.setAttribute("data-title", e.getAttribute("title"));
e.removeAttribute("title");
}
if (e.getAttribute("data-title") !== null) {
const titleContent = document.createElement("div");
titleContent.className = "content";
titleContent.appendChild(document.createTextNode(e.getAttribute("data-title")));
wrapper.appendChild(titleContent);
}
}
wrapper.className = "tooltip popover";
const focusCatcher = document.createElement("div");
focusCatcher.setAttribute("tabindex", "0");
focusCatcher.onfocus = hideTooltip;
wrapper.appendChild(focusCatcher);
const pos = e.getBoundingClientRect();
// 5px overlap so that the mouse can easily travel from place to place
wrapper.style.top = (pos.top + window.scrollY + pos.height) + "px";
wrapper.style.left = 0;
wrapper.style.right = "auto";
wrapper.style.visibility = "hidden";
const body = document.getElementsByTagName("body")[0];
body.appendChild(wrapper);
const wrapperPos = wrapper.getBoundingClientRect();
// offset so that the arrow points at the center of the "(i)"
const finalPos = pos.left + window.scrollX - wrapperPos.width + 24;
if (finalPos > 0) {
wrapper.style.left = finalPos + "px";
} else {
wrapper.style.setProperty(
"--popover-arrow-offset",
(wrapperPos.right - pos.right + 4) + "px"
);
}
wrapper.style.visibility = "";
window.CURRENT_TOOLTIP_ELEMENT = wrapper;
window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE = e;
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);
wrapper.onpointerenter = ev => {
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
// If this is a synthetic touch event, ignore it. A click event will be along shortly.
if (ev.pointerType !== "mouse") {
return;
}
clearTooltipHoverTimeout(e);
};
wrapper.onpointerleave = ev => {
// If this is a synthetic touch event, ignore it. A click event will be along shortly.
if (ev.pointerType !== "mouse") {
return;
}
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
if (!e.TOOLTIP_FORCE_VISIBLE && !elemIsInParent(ev.relatedTarget, e)) {
// See "Tooltip pointer leave gesture" below.
setTooltipHoverTimeout(e, false);
addClass(wrapper, "fade-out");
}
};
}
/**
* Show or hide the tooltip after a timeout. If a timeout was already set before this function
* was called, that timeout gets cleared. If the tooltip is already in the requested state,
* this function will still clear any pending timeout, but otherwise do nothing.
*
* @param {DOMElement} element - The tooltip's anchor point. The DOM is consulted to figure
* out what the tooltip should contain, and where it should be
* positioned.
* @param {boolean} show - If true, the tooltip will be made visible. If false, it will
* be hidden.
*/
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
function setTooltipHoverTimeout(element, show) {
clearTooltipHoverTimeout(element);
if (!show && !window.CURRENT_TOOLTIP_ELEMENT) {
// To "hide" an already hidden element, just cancel its timeout.
return;
}
if (show && window.CURRENT_TOOLTIP_ELEMENT) {
// To "show" an already visible element, just cancel its timeout.
return;
}
if (window.CURRENT_TOOLTIP_ELEMENT &&
window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE !== element) {
// Don't do anything if another tooltip is already visible.
return;
}
element.TOOLTIP_HOVER_TIMEOUT = setTimeout(() => {
if (show) {
showTooltip(element);
} else if (!element.TOOLTIP_FORCE_VISIBLE) {
hideTooltip(false);
}
}, show ? window.RUSTDOC_TOOLTIP_HOVER_MS : window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS);
}
/**
* If a show/hide timeout was set by `setTooltipHoverTimeout`, cancel it. If none exists,
* do nothing.
*
* @param {DOMElement} element - The tooltip's anchor point,
* as passed to `setTooltipHoverTimeout`.
*/
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
function clearTooltipHoverTimeout(element) {
if (element.TOOLTIP_HOVER_TIMEOUT !== undefined) {
removeClass(window.CURRENT_TOOLTIP_ELEMENT, "fade-out");
clearTimeout(element.TOOLTIP_HOVER_TIMEOUT);
delete element.TOOLTIP_HOVER_TIMEOUT;
}
}
function tooltipBlurHandler(event) {
if (window.CURRENT_TOOLTIP_ELEMENT &&
!elemIsInParent(document.activeElement, window.CURRENT_TOOLTIP_ELEMENT) &&
!elemIsInParent(event.relatedTarget, window.CURRENT_TOOLTIP_ELEMENT) &&
!elemIsInParent(document.activeElement, window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE) &&
!elemIsInParent(event.relatedTarget, window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE)
) {
// Work around a difference in the focus behaviour between Firefox, Chrome, and Safari.
// When I click the button on an already-opened tooltip popover, Safari
// hides the popover and then immediately shows it again, while everyone else hides it
// and it stays hidden.
//
// To work around this, make sure the click finishes being dispatched before
// hiding the popover. Since `hideTooltip()` is idempotent, this makes Safari behave
// consistently with the other two.
setTimeout(() => hideTooltip(false), 0);
}
}
/**
* Hide the current tooltip immediately.
*
* @param {boolean} focus - If set to `true`, move keyboard focus to the tooltip anchor point.
* If set to `false`, leave keyboard focus alone.
*/
function hideTooltip(focus) {
if (window.CURRENT_TOOLTIP_ELEMENT) {
if (window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE) {
if (focus) {
window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.focus();
}
window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE = false;
}
const body = document.getElementsByTagName("body")[0];
body.removeChild(window.CURRENT_TOOLTIP_ELEMENT);
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);
window.CURRENT_TOOLTIP_ELEMENT = null;
}
}
onEachLazy(document.getElementsByClassName("tooltip"), e => {
e.onclick = () => {
e.TOOLTIP_FORCE_VISIBLE = e.TOOLTIP_FORCE_VISIBLE ? false : true;
if (window.CURRENT_TOOLTIP_ELEMENT && !e.TOOLTIP_FORCE_VISIBLE) {
hideTooltip(true);
} else {
showTooltip(e);
window.CURRENT_TOOLTIP_ELEMENT.setAttribute("tabindex", "0");
window.CURRENT_TOOLTIP_ELEMENT.focus();
window.CURRENT_TOOLTIP_ELEMENT.onblur = tooltipBlurHandler;
}
return false;
};
e.onpointerenter = ev => {
// If this is a synthetic touch event, ignore it. A click event will be along shortly.
if (ev.pointerType !== "mouse") {
return;
}
setTooltipHoverTimeout(e, true);
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
};
e.onpointermove = ev => {
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
// If this is a synthetic touch event, ignore it. A click event will be along shortly.
if (ev.pointerType !== "mouse") {
return;
}
setTooltipHoverTimeout(e, true);
};
e.onpointerleave = ev => {
// If this is a synthetic touch event, ignore it. A click event will be along shortly.
if (ev.pointerType !== "mouse") {
return;
}
if (!e.TOOLTIP_FORCE_VISIBLE &&
!elemIsInParent(ev.relatedTarget, window.CURRENT_TOOLTIP_ELEMENT)) {
rustdoc: add interaction delays for tooltip popovers Designing a good hover microinteraction is a matter of guessing user intent from what are, literally, vague gestures. In this case, guessing if hovering in our out of the tooltip base is intentional or not. To figure this out, a few different techniques are used: * When the mouse pointer enters a tooltip anchor point, its hitbox is grown on the bottom, where the popover is/will appear. This was already there before this commit: search "hover tunnel" in rustdoc.css for the implementation. * This commit adds a delay when the mouse pointer enters the base anchor, in case the mouse pointer was just passing through and the user didn't want to open it. * This commit also adds a delay when the mouse pointer exits the tooltip's base anchor or its popover, before hiding it. * A fade-out animation is layered onto the pointer exit delay to immediately inform the user that they successfully dismissed the popover, while still providing a way for them to cancel it if it was a mistake and they still wanted to interact with it. * No animation is used for revealing it, because we don't want people to try to interact with an element while it's in the middle of fading in: either they're allowed to interact with it while it's fading in, meaning it can't serve as mistake- proofing for opening the popover, or they can't, but they might try and be frustrated. See also: * https://www.nngroup.com/articles/timing-exposing-content/ * https://www.nngroup.com/articles/tooltip-guidelines/ * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
2023-05-23 22:29:43 +00:00
// Tooltip pointer leave gesture:
//
// Designing a good hover microinteraction is a matter of guessing user
// intent from what are, literally, vague gestures. In this case, guessing if
// hovering in or out of the tooltip base is intentional or not.
//
// To figure this out, a few different techniques are used:
//
// * When the mouse pointer enters a tooltip anchor point, its hitbox is grown
// on the bottom, where the popover is/will appear. Search "hover tunnel" in
// rustdoc.css for the implementation.
// * There's a delay when the mouse pointer enters the popover base anchor, in
// case the mouse pointer was just passing through and the user didn't want
// to open it.
// * Similarly, a delay is added when exiting the anchor, or the popover
// itself, before hiding it.
// * A fade-out animation is layered onto the pointer exit delay to immediately
// inform the user that they successfully dismissed the popover, while still
// providing a way for them to cancel it if it was a mistake and they still
// wanted to interact with it.
// * No animation is used for revealing it, because we don't want people to try
// to interact with an element while it's in the middle of fading in: either
// they're allowed to interact with it while it's fading in, meaning it can't
// serve as mistake-proofing for the popover, or they can't, but
// they might try and be frustrated.
//
// See also:
// * https://www.nngroup.com/articles/timing-exposing-content/
// * https://www.nngroup.com/articles/tooltip-guidelines/
// * https://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown
setTooltipHoverTimeout(e, false);
addClass(window.CURRENT_TOOLTIP_ELEMENT, "fade-out");
}
};
});
2022-04-25 12:23:17 +00:00
const sidebar_menu_toggle = document.getElementsByClassName("sidebar-menu-toggle")[0];
if (sidebar_menu_toggle) {
sidebar_menu_toggle.addEventListener("click", () => {
2022-04-25 12:23:17 +00:00
const sidebar = document.getElementsByClassName("sidebar")[0];
if (!hasClass(sidebar, "shown")) {
showSidebar();
} else {
hideSidebar();
}
});
}
function helpBlurHandler(event) {
blurHandler(event, getHelpButton(), window.hidePopoverMenus);
}
function buildHelpMenu() {
2022-04-25 12:23:17 +00:00
const book_info = document.createElement("span");
const channel = getVar("channel");
book_info.className = "top";
book_info.innerHTML = `You can find more information in \
<a href="https://doc.rust-lang.org/${channel}/rustdoc/">the rustdoc book</a>.`;
2022-04-25 12:23:17 +00:00
const shortcuts = [
["?", "Show this help dialog"],
["S", "Focus the search field"],
["↑", "Move up in search results"],
["↓", "Move down in search results"],
2021-05-09 19:56:21 +00:00
["← / →", "Switch result tab (when results focused)"],
["&#9166;", "Go to active search result"],
["+", "Expand all sections"],
["-", "Collapse all sections"],
].map(x => "<dt>" +
x[0].split(" ")
2022-06-06 11:57:54 +00:00
.map((y, index) => ((index & 1) === 0 ? "<kbd>" + y + "</kbd>" : " " + y + " "))
.join("") + "</dt><dd>" + x[1] + "</dd>").join("");
2022-04-25 12:23:17 +00:00
const div_shortcuts = document.createElement("div");
addClass(div_shortcuts, "shortcuts");
div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
2022-04-25 12:23:17 +00:00
const infos = [
`For a full list of all search features, take a look <a \
href="https://doc.rust-lang.org/${channel}/rustdoc/how-to-read-rustdoc.html\
#the-search-interface">here</a>.`,
"Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \
2020-08-27 10:56:43 +00:00
restrict the search to a given item kind.",
"Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \
<code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, \
and <code>const</code>.",
"Search functions by type signature (e.g., <code>vec -&gt; usize</code> or \
<code>-&gt; vec</code> or <code>String, enum:Cow -&gt; bool</code>)",
"You can look for items with an exact name by putting double quotes around \
your request: <code>\"string\"</code>",
"Look for functions that accept or return \
<a href=\"https://doc.rust-lang.org/std/primitive.slice.html\">slices</a> and \
<a href=\"https://doc.rust-lang.org/std/primitive.array.html\">arrays</a> by writing \
square brackets (e.g., <code>-&gt; [u8]</code> or <code>[] -&gt; Option</code>)",
"Look for items inside another one by searching for a path: <code>vec::Vec</code>",
].map(x => "<p>" + x + "</p>").join("");
2022-04-25 12:23:17 +00:00
const div_infos = document.createElement("div");
addClass(div_infos, "infos");
div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
2022-04-25 12:23:17 +00:00
const rustdoc_version = document.createElement("span");
rustdoc_version.className = "bottom";
2022-04-25 12:23:17 +00:00
const rustdoc_version_code = document.createElement("code");
rustdoc_version_code.innerText = "rustdoc " + getVar("rustdoc-version");
rustdoc_version.appendChild(rustdoc_version_code);
const container = document.createElement("div");
if (!isHelpPage) {
container.className = "popover";
}
container.id = "help";
container.style.display = "none";
const side_by_side = document.createElement("div");
side_by_side.className = "side-by-side";
side_by_side.appendChild(div_shortcuts);
side_by_side.appendChild(div_infos);
container.appendChild(book_info);
container.appendChild(side_by_side);
container.appendChild(rustdoc_version);
if (isHelpPage) {
const help_section = document.createElement("section");
help_section.appendChild(container);
document.getElementById("main-content").appendChild(help_section);
container.style.display = "block";
} else {
const help_button = getHelpButton();
help_button.appendChild(container);
container.onblur = helpBlurHandler;
help_button.onblur = helpBlurHandler;
help_button.children[0].onblur = helpBlurHandler;
}
return container;
}
/**
* Hide popover menus, clickable tooltips, and the sidebar (if applicable).
*
* Pass "true" to reset focus for tooltip popovers.
*/
window.hideAllModals = switchFocus => {
hideSidebar();
window.hidePopoverMenus();
hideTooltip(switchFocus);
};
/**
* Hide all the popover menus.
*/
window.hidePopoverMenus = () => {
onEachLazy(document.querySelectorAll(".search-form .popover"), elem => {
elem.style.display = "none";
});
};
/**
* Returns the help menu element (not the button).
*
* @param {boolean} buildNeeded - If this argument is `false`, the help menu element won't be
* built if it doesn't exist.
*
* @return {HTMLElement}
*/
function getHelpMenu(buildNeeded) {
let menu = getHelpButton().querySelector(".popover");
if (!menu && buildNeeded) {
menu = buildHelpMenu();
}
return menu;
}
/**
* Show the help popup menu.
*/
function showHelp() {
// Prevent `blur` events from being dispatched as a result of closing
// other modals.
getHelpButton().querySelector("a").focus();
const menu = getHelpMenu(true);
if (menu.style.display === "none") {
window.hideAllModals();
menu.style.display = "";
}
}
if (isHelpPage) {
showHelp();
document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click", event => {
// Already on the help page, make help button a no-op.
const target = event.target;
if (target.tagName !== "A" ||
target.parentElement.id !== HELP_BUTTON_ID ||
event.ctrlKey ||
event.altKey ||
event.metaKey) {
return;
}
event.preventDefault();
});
} else {
document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click", event => {
// By default, have help button open docs in a popover.
// If user clicks with a moderator, though, use default browser behavior,
// probably opening in a new window or tab.
const target = event.target;
if (target.tagName !== "A" ||
target.parentElement.id !== HELP_BUTTON_ID ||
event.ctrlKey ||
event.altKey ||
event.metaKey) {
return;
}
event.preventDefault();
const menu = getHelpMenu(true);
const shouldShowHelp = menu.style.display === "none";
if (shouldShowHelp) {
showHelp();
} else {
window.hidePopoverMenus();
}
});
}
setMobileTopbar();
addSidebarItems();
addSidebarCrates();
onHashChange(null);
window.addEventListener("hashchange", onHashChange);
searchState.setup();
}());
// This section handles sidebar resizing
2023-09-08 01:45:24 +00:00
(function() {
const sidebarButton = document.getElementById("sidebar-button");
if (sidebarButton) {
sidebarButton.addEventListener("click", e => {
removeClass(document.documentElement, "hide-sidebar");
updateLocalStorage("hide-sidebar", "false");
e.preventDefault();
});
}
let currentPointerId = null;
const resizer = document.querySelector(".sidebar-resizer");
const sidebar = document.querySelector(".sidebar");
2023-09-08 01:45:24 +00:00
if (!resizer || !sidebar) {
return;
}
const isSrcPage = hasClass(document.body, "src");
function hideSidebar() {
if (isSrcPage) {
window.rustdocCloseSourceSidebar();
updateLocalStorage("src-sidebar-width", null);
document.documentElement.style.removeProperty("--src-sidebar-width");
} else {
addClass(document.documentElement, "hide-sidebar");
updateLocalStorage("hide-sidebar", "true");
updateLocalStorage("desktop-sidebar-width", null);
document.documentElement.style.removeProperty("--desktop-sidebar-width");
}
}
function showSidebar() {
if (isSrcPage) {
window.rustdocShowSourceSidebar();
} else {
removeClass(document.documentElement, "hide-sidebar");
updateLocalStorage("hide-sidebar", "false");
}
}
function changeSidebarSize(size) {
if (isSrcPage) {
updateLocalStorage("src-sidebar-width", size);
document.documentElement.style.setProperty("--src-sidebar-width", size + "px");
} else {
updateLocalStorage("desktop-sidebar-width", size);
document.documentElement.style.setProperty("--desktop-sidebar-width", size + "px");
}
}
function isSidebarHidden() {
return isSrcPage ?
!hasClass(document.documentElement, "src-sidebar-expanded") :
hasClass(document.documentElement, "hide-sidebar");
}
function resize(e) {
if (currentPointerId === null || currentPointerId !== e.pointerId) {
return;
}
e.preventDefault();
const pos = e.clientX - sidebar.offsetLeft - 3;
if (pos < 50) {
hideSidebar();
} else if (pos >= 100) {
// 100 is the size of the logo
// don't let the sidebar get smaller than that, or it'll get squished
if (isSidebarHidden()) {
showSidebar();
}
// don't let the sidebar get wider than 500
changeSidebarSize(Math.min(pos, window.innerWidth - 100, 500));
}
}
function stopResize(e) {
if (currentPointerId === null) {
return;
}
e.preventDefault();
removeClass(resizer, "active");
window.removeEventListener("pointermove", resize, false);
window.removeEventListener("pointerup", stopResize, false);
removeClass(document.documentElement, "sidebar-resizing");
if (resizer.releasePointerCapture) {
resizer.releasePointerCapture(currentPointerId);
currentPointerId = null;
}
}
function initResize(e) {
if (currentPointerId !== null || e.altKey || e.ctrlKey || e.metaKey || e.button !== 0) {
return;
}
if (resizer.setPointerCapture) {
resizer.setPointerCapture(e.pointerId);
if (!resizer.hasPointerCapture(e.pointerId)) {
// unable to capture pointer; something else has it
// on iOS, this usually means you long-clicked a link instead
resizer.releasePointerCapture(e.pointerId);
return;
}
currentPointerId = e.pointerId;
}
e.preventDefault();
window.addEventListener("pointermove", resize, false);
window.addEventListener("pointercancel", stopResize, false);
window.addEventListener("pointerup", stopResize, false);
addClass(resizer, "active");
addClass(document.documentElement, "sidebar-resizing");
}
resizer.addEventListener("pointerdown", initResize, false);
}());
// This section handles the copy button that appears next to the path breadcrumbs
(function() {
2022-04-25 12:23:17 +00:00
let reset_button_timeout = null;
2021-04-30 09:42:07 +00:00
const but = document.getElementById("copy-path");
if (!but) {
return;
}
but.onclick = () => {
2022-04-25 12:23:17 +00:00
const parent = but.parentElement;
const path = [];
2021-04-30 09:42:07 +00:00
onEach(parent.childNodes, child => {
2022-05-07 18:18:23 +00:00
if (child.tagName === "A") {
2021-04-30 09:42:07 +00:00
path.push(child.textContent);
}
});
2022-05-07 18:18:23 +00:00
const el = document.createElement("textarea");
el.value = path.join("::");
el.setAttribute("readonly", "");
2021-04-30 09:42:07 +00:00
// To not make it appear on the screen.
2022-05-07 18:18:23 +00:00
el.style.position = "absolute";
el.style.left = "-9999px";
2021-04-30 09:42:07 +00:00
document.body.appendChild(el);
el.select();
2022-05-07 18:18:23 +00:00
document.execCommand("copy");
2021-04-30 09:42:07 +00:00
document.body.removeChild(el);
// There is always one children, but multiple childNodes.
2022-05-07 18:18:23 +00:00
but.children[0].style.display = "none";
2022-04-25 12:23:17 +00:00
let tmp;
if (but.childNodes.length < 2) {
2022-05-07 18:18:23 +00:00
tmp = document.createTextNode("✓");
but.appendChild(tmp);
} else {
onEachLazy(but.childNodes, e => {
if (e.nodeType === Node.TEXT_NODE) {
tmp = e;
return true;
}
});
2022-05-07 18:18:23 +00:00
tmp.textContent = "✓";
}
2021-04-30 09:42:07 +00:00
if (reset_button_timeout !== null) {
window.clearTimeout(reset_button_timeout);
}
function reset_button() {
2022-05-07 18:18:23 +00:00
tmp.textContent = "";
2021-04-30 09:42:07 +00:00
reset_button_timeout = null;
but.children[0].style.display = "";
}
2021-04-30 09:42:07 +00:00
reset_button_timeout = window.setTimeout(reset_button, 1000);
};
2021-04-30 09:42:07 +00:00
}());