custom.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. // Handle page scroll and adjust sidebar accordingly.
  2. // Each page has two scrolls: the main scroll, which is moving the content of the page;
  3. // and the sidebar scroll, which is moving the navigation in the sidebar.
  4. // We want the logo to gradually disappear as the main content is scrolled, giving
  5. // more room to the navigation on the left. This means adjusting the height
  6. // available to the navigation on the fly. There is also a banner below the navigation
  7. // that must be dealt with simultaneously.
  8. const registerOnScrollEvent = (function(){
  9. // Configuration.
  10. // The number of pixels the user must scroll by before the logo is completely hidden.
  11. const scrollTopPixels = 84;
  12. // The target margin to be applied to the navigation bar when the logo is hidden.
  13. const menuTopMargin = 70;
  14. // The max-height offset when the logo is completely visible.
  15. const menuHeightOffset_default = 162;
  16. // The max-height offset when the logo is completely hidden.
  17. const menuHeightOffset_fixed = 80;
  18. // The distance between the two max-height offset values above; used for intermediate values.
  19. const menuHeightOffset_diff = (menuHeightOffset_default - menuHeightOffset_fixed);
  20. // Media query handler.
  21. return function(mediaQuery) {
  22. // We only apply this logic to the "desktop" resolution (defined by a media query at the bottom).
  23. // This handler is executed when the result of the query evaluation changes, which means that
  24. // the page has moved between "desktop" and "mobile" states.
  25. // When entering the "desktop" state, we register scroll events and adjust elements on the page.
  26. // When entering the "mobile" state, we clean up any registered events and restore elements on the page
  27. // to their initial state.
  28. const $window = $(window);
  29. const $sidebar = $('.wy-side-scroll');
  30. const $search = $sidebar.children('.wy-side-nav-search');
  31. const $menu = $sidebar.children('.wy-menu-vertical');
  32. const $ethical = $sidebar.children('.ethical-rtd');
  33. // This padding is needed to correctly adjust the height of the scrollable area in the sidebar.
  34. // It has to have the same height as the ethical block, if there is one.
  35. let $menuPadding = $menu.children('.wy-menu-ethical-padding');
  36. if ($menuPadding.length == 0) {
  37. $menuPadding = $('<div class="wy-menu-ethical-padding"></div>');
  38. $menu.append($menuPadding);
  39. }
  40. if (mediaQuery.matches) {
  41. // Entering the "desktop" state.
  42. // The main scroll event handler.
  43. // Executed as the page is scrolled and once immediately as the page enters this state.
  44. const handleMainScroll = (currentScroll) => {
  45. if (currentScroll >= scrollTopPixels) {
  46. // After the page is scrolled below the threshold, we fix everything in place.
  47. $search.css('margin-top', `-${scrollTopPixels}px`);
  48. $menu.css('margin-top', `${menuTopMargin}px`);
  49. $menu.css('max-height', `calc(100% - ${menuHeightOffset_fixed}px)`);
  50. }
  51. else {
  52. // Between the top of the page and the threshold we calculate intermediate values
  53. // to guarantee a smooth transition.
  54. $search.css('margin-top', `-${currentScroll}px`);
  55. $menu.css('margin-top', `${menuTopMargin + (scrollTopPixels - currentScroll)}px`);
  56. if (currentScroll > 0) {
  57. const scrolledPercent = (scrollTopPixels - currentScroll) / scrollTopPixels;
  58. const offsetValue = menuHeightOffset_fixed + menuHeightOffset_diff * scrolledPercent;
  59. $menu.css('max-height', `calc(100% - ${offsetValue}px)`);
  60. } else {
  61. $menu.css('max-height', `calc(100% - ${menuHeightOffset_default}px)`);
  62. }
  63. }
  64. };
  65. // The sidebar scroll event handler.
  66. // Executed as the sidebar is scrolled as well as after the main scroll. This is needed
  67. // because the main scroll can affect the scrollable area of the sidebar.
  68. const handleSidebarScroll = () => {
  69. const menuElement = $menu.get(0);
  70. const menuScrollTop = $menu.scrollTop();
  71. const menuScrollBottom = menuElement.scrollHeight - (menuScrollTop + menuElement.offsetHeight);
  72. // As the navigation is scrolled we add a shadow to the top bar hanging over it.
  73. if (menuScrollTop > 0) {
  74. $search.addClass('fixed-and-scrolled');
  75. } else {
  76. $search.removeClass('fixed-and-scrolled');
  77. }
  78. // Near the bottom we start moving the sidebar banner into view.
  79. if (menuScrollBottom < ethicalOffsetBottom) {
  80. $ethical.css('display', 'block');
  81. $ethical.css('margin-top', `-${ethicalOffsetBottom - menuScrollBottom}px`);
  82. } else {
  83. $ethical.css('display', 'none');
  84. $ethical.css('margin-top', '0px');
  85. }
  86. };
  87. $search.addClass('fixed');
  88. $ethical.addClass('fixed');
  89. // Adjust the inner height of navigation so that the banner can be overlaid there later.
  90. const ethicalOffsetBottom = $ethical.height() || 0;
  91. if (ethicalOffsetBottom) {
  92. $menuPadding.css('height', `${ethicalOffsetBottom}px`);
  93. } else {
  94. $menuPadding.css('height', `0px`);
  95. }
  96. $window.scroll(function() {
  97. handleMainScroll(window.scrollY);
  98. handleSidebarScroll();
  99. });
  100. $menu.scroll(function() {
  101. handleSidebarScroll();
  102. });
  103. handleMainScroll(window.scrollY);
  104. handleSidebarScroll();
  105. } else {
  106. // Entering the "mobile" state.
  107. $window.unbind('scroll');
  108. $menu.unbind('scroll');
  109. $search.removeClass('fixed');
  110. $ethical.removeClass('fixed');
  111. $search.css('margin-top', `0px`);
  112. $menu.css('margin-top', `0px`);
  113. $menu.css('max-height', 'initial');
  114. $menuPadding.css('height', `0px`);
  115. $ethical.css('margin-top', '0px');
  116. $ethical.css('display', 'block');
  117. }
  118. };
  119. })();
  120. // Subscribe to DOM changes in the sidebar container, because there is a
  121. // banner that gets added at a later point, that we might not catch otherwise.
  122. const registerSidebarObserver = (function(){
  123. return function(callback) {
  124. const sidebarContainer = document.querySelector('.wy-side-scroll');
  125. let sidebarEthical = null;
  126. const registerEthicalObserver = () => {
  127. if (sidebarEthical) {
  128. // Do it only once.
  129. return;
  130. }
  131. sidebarEthical = sidebarContainer.querySelector('.ethical-rtd');
  132. if (!sidebarEthical) {
  133. // Do it only after we have the element there.
  134. return;
  135. }
  136. // This observer watches over the ethical block in sidebar, and all of its subtree.
  137. const ethicalObserverConfig = { childList: true, subtree: true };
  138. const ethicalObserverCallback = (mutationsList, observer) => {
  139. for (let mutation of mutationsList) {
  140. if (mutation.type !== 'childList') {
  141. continue;
  142. }
  143. callback();
  144. }
  145. };
  146. const ethicalObserver = new MutationObserver(ethicalObserverCallback);
  147. ethicalObserver.observe(sidebarEthical, ethicalObserverConfig);
  148. };
  149. registerEthicalObserver();
  150. // This observer watches over direct children of the main sidebar container.
  151. const observerConfig = { childList: true };
  152. const observerCallback = (mutationsList, observer) => {
  153. for (let mutation of mutationsList) {
  154. if (mutation.type !== 'childList') {
  155. continue;
  156. }
  157. callback();
  158. registerEthicalObserver();
  159. }
  160. };
  161. const observer = new MutationObserver(observerCallback);
  162. observer.observe(sidebarContainer, observerConfig);
  163. // Default TOC tree has links that immediately navigate to the selected page. Our
  164. // theme adds an extra button to fold and unfold the tree without navigating away.
  165. // But that means that the buttons are added after the initial load, so we need to
  166. // improvise to detect clicks on these buttons.
  167. const scrollElement = document.querySelector('.wy-menu-vertical');
  168. const registerLinkHandler = (linkChildren) => {
  169. linkChildren.forEach(it => {
  170. if (it.nodeType === Node.ELEMENT_NODE && it.classList.contains('toctree-expand')) {
  171. it.addEventListener('click', () => {
  172. // Toggling a different item will close the currently opened one,
  173. // which may shift the clicked item out of the view. We correct for that.
  174. const menuItem = it.parentNode;
  175. const baseScrollOffset = scrollElement.scrollTop + scrollElement.offsetTop;
  176. const maxScrollOffset = baseScrollOffset + scrollElement.offsetHeight;
  177. if (menuItem.offsetTop < baseScrollOffset || menuItem.offsetTop > maxScrollOffset) {
  178. menuItem.scrollIntoView();
  179. }
  180. callback();
  181. });
  182. }
  183. });
  184. }
  185. const navigationSections = document.querySelectorAll('.wy-menu-vertical ul');
  186. navigationSections.forEach(it => {
  187. if (it.previousSibling == null || typeof it.previousSibling === 'undefined' || it.previousSibling.tagName != 'A') {
  188. return;
  189. }
  190. const navigationLink = it.previousSibling;
  191. registerLinkHandler(navigationLink.childNodes);
  192. const linkObserverConfig = { childList: true };
  193. const linkObserverCallback = (mutationsList, observer) => {
  194. for (let mutation of mutationsList) {
  195. registerLinkHandler(mutation.addedNodes);
  196. }
  197. };
  198. const linkObserver = new MutationObserver(linkObserverCallback);
  199. linkObserver.observe(navigationLink, linkObserverConfig);
  200. });
  201. };
  202. })();
  203. /**
  204. * Registers Giscus if there's an #godot-giscus container.
  205. * @returns {void} Nothing.
  206. */
  207. const registerGiscus = function () {
  208. const giscusContainer = document.getElementById("godot-giscus");
  209. if (giscusContainer == null) {
  210. return;
  211. }
  212. const removeGiscusContainer = function() {
  213. giscusContainer.remove();
  214. };
  215. const pageNameMetaElement = Array.from(document.head.querySelectorAll("meta")).find((meta) => meta.name === "doc_pagename");
  216. if (pageNameMetaElement == null) {
  217. removeGiscusContainer();
  218. return;
  219. }
  220. const pageNameDenyList = [
  221. "search"
  222. ];
  223. if (pageNameDenyList.includes(pageNameMetaElement.content)) {
  224. removeGiscusContainer();
  225. return;
  226. }
  227. // Use https://giscus.app/ to regenerate the script tag if needed.
  228. // data-term is set to be language-independent and version-independent, so that comments can be centralized for each page.
  229. // This increases the likelihood that users will encounter comments on less frequently visited pages.
  230. const scriptElement = document.createElement("script");
  231. scriptElement.src = "https://giscus.app/client.js";
  232. scriptElement.crossOrigin = "anonymous";
  233. scriptElement.async = true;
  234. const dataset = {
  235. repo: "godotengine/godot-docs-user-notes",
  236. repoId: "R_kgDOKuNx0w",
  237. category: "User-contributed notes",
  238. categoryId: "DIC_kwDOKuNx084CbANb",
  239. mapping: "specific",
  240. term: pageNameMetaElement.content,
  241. strict: "1",
  242. reactionsEnabled: "0",
  243. emitMetadata: "0",
  244. inputPosition: "bottom",
  245. theme: "preferred_color_scheme",
  246. lang: "en",
  247. loading: "lazy",
  248. };
  249. for (const [key, value] of Object.entries(dataset)) {
  250. scriptElement.dataset[key] = value;
  251. }
  252. giscusContainer.append(scriptElement);
  253. };
  254. $(document).ready(() => {
  255. // Remove the search match highlights from the page, and adjust the URL in the
  256. // navigation history.
  257. const url = new URL(location.href);
  258. if (url.searchParams.has('highlight')) {
  259. Documentation.hideSearchWords();
  260. }
  261. window.addEventListener('keydown', function(event) {
  262. if (event.key === '/') {
  263. var searchField = document.querySelector('#rtd-search-form input[type=text]');
  264. if (document.activeElement !== searchField) {
  265. searchField.focus();
  266. searchField.select();
  267. event.preventDefault();
  268. }
  269. }
  270. });
  271. // Initialize handlers for page scrolling and our custom sidebar.
  272. const mediaQuery = window.matchMedia('only screen and (min-width: 769px)');
  273. registerOnScrollEvent(mediaQuery);
  274. mediaQuery.addListener(registerOnScrollEvent);
  275. registerSidebarObserver(() => {
  276. registerOnScrollEvent(mediaQuery);
  277. });
  278. // Add line-break suggestions to the sidebar navigation items in the class reference section.
  279. //
  280. // Some class reference pages have very long PascalCase names, such as
  281. // VisualShaderNodeCurveXYZTexture
  282. // Those create issues for our layout, as we can neither make them wrap with CSS without
  283. // breaking normal article titles, nor is it good to have them overflow their containers.
  284. // So we use a <wbr> tag to insert mid-word suggestions for appropriate splits, so the browser
  285. // knows that it's okay to split it like
  286. // Visual Shader Node Curve XYZTexture
  287. // and add a new line at an opportune moment.
  288. const classReferenceLinks = document.querySelectorAll('.wy-menu-vertical > ul:last-of-type .reference.internal');
  289. for (const linkItem of classReferenceLinks) {
  290. let textNode = null;
  291. linkItem.childNodes.forEach(it => {
  292. if (it.nodeType === Node.TEXT_NODE) {
  293. // If this is a text node and if it needs to be updated, store a reference.
  294. let text = it.textContent;
  295. if (!(text.includes(" ") || text.length < 10)) {
  296. textNode = it;
  297. }
  298. }
  299. });
  300. if (textNode != null) {
  301. let text = textNode.textContent;
  302. // Add suggested line-breaks and replace the original text.
  303. // The regex looks for a lowercase letter followed by a number or an uppercase
  304. // letter. We avoid splitting at the last character in the name, though.
  305. text = text.replace(/([a-z])([A-Z0-9](?!$))/gm, '$1<wbr>$2');
  306. linkItem.removeChild(textNode);
  307. linkItem.insertAdjacentHTML('beforeend', text);
  308. }
  309. }
  310. // Change indentation from spaces to tabs for codeblocks.
  311. const codeBlocks = document.querySelectorAll('.rst-content div[class^="highlight"] pre');
  312. for (const codeBlock of codeBlocks) {
  313. const classList = codeBlock.parentNode.parentNode.classList;
  314. if (!classList.contains('highlight-gdscript') && !classList.contains('highlight-cpp')) {
  315. // Only change indentation for GDScript and C++.
  316. continue;
  317. }
  318. let html = codeBlock.innerHTML.replace(/^(<span class="w">)?( {4})/gm, '\t');
  319. let html_old = "";
  320. while (html != html_old) {
  321. html_old = html;
  322. html = html.replace(/\t( {4})/gm, '\t\t')
  323. }
  324. codeBlock.innerHTML = html;
  325. }
  326. // See `godot_is_latest` in conf.py
  327. const isLatest = document.querySelector('meta[name=doc_is_latest]').content.toLowerCase() === 'true';
  328. if (isLatest) {
  329. // Add a compatibility notice using JavaScript so it doesn't end up in the
  330. // automatically generated `meta description` tag.
  331. const baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
  332. // These lines only work as expected in the production environment, can't test this locally.
  333. const fallbackUrl = baseUrl.replace('/latest/', '/stable/');
  334. const homeUrl = baseUrl.split('/latest/')[0] + '/stable/';
  335. const searchUrl = homeUrl + 'search.html?q=';
  336. const noticeLink = document.querySelector('.latest-notice-link');
  337. // Insert a placeholder to display as we're making a request.
  338. noticeLink.innerHTML = `
  339. Checking the <a class="reference" href="${homeUrl}">stable version</a>
  340. of the documentation...
  341. `;
  342. // Make a HEAD request to the possible stable URL to check if the page exists.
  343. fetch(fallbackUrl, { method: 'HEAD' })
  344. .then((res) => {
  345. // We only check the HTTP status, which should tell us if the link is valid or not.
  346. if (res.status === 200) {
  347. noticeLink.innerHTML = `
  348. See the <a class="reference" href="${fallbackUrl}">stable version</a>
  349. of this documentation page instead.
  350. `;
  351. } else {
  352. // Err, just to fallthrough to catch.
  353. throw Error('Bad request');
  354. }
  355. })
  356. .catch((err) => {
  357. let message = `
  358. This page does not exist in the <a class="reference" href="${homeUrl}">stable version</a>
  359. of the documentation.
  360. `;
  361. // Also suggest a search query using the page's title. It should work with translations as well.
  362. // Note that we can't use the title tag as it has a permanent suffix. OG title doesn't, though.
  363. const titleMeta = document.querySelector('meta[property="og:title"]');
  364. if (typeof titleMeta !== 'undefined') {
  365. const pageTitle = titleMeta.getAttribute('content');
  366. message += `
  367. You can try searching for "<a class="reference" href="${searchUrl + encodeURIComponent(pageTitle)}">${pageTitle}</a>" instead.
  368. `;
  369. }
  370. noticeLink.innerHTML = message;
  371. });
  372. }
  373. // Load instant.page to prefetch pages upon hovering. This makes navigation feel
  374. // snappier. The script is dynamically appended as Read the Docs doesn't have
  375. // a way to add scripts with a "module" attribute.
  376. const instantPageScript = document.createElement('script');
  377. instantPageScript.toggleAttribute('module');
  378. /*! instant.page v5.1.0 - (C) 2019-2020 Alexandre Dieulot - https://instant.page/license */
  379. instantPageScript.innerText = 'let t,e;const n=new Set,o=document.createElement("link"),i=o.relList&&o.relList.supports&&o.relList.supports("prefetch")&&window.IntersectionObserver&&"isIntersecting"in IntersectionObserverEntry.prototype,s="instantAllowQueryString"in document.body.dataset,a="instantAllowExternalLinks"in document.body.dataset,r="instantWhitelist"in document.body.dataset,c="instantMousedownShortcut"in document.body.dataset,d=1111;let l=65,u=!1,f=!1,m=!1;if("instantIntensity"in document.body.dataset){const t=document.body.dataset.instantIntensity;if("mousedown"==t.substr(0,"mousedown".length))u=!0,"mousedown-only"==t&&(f=!0);else if("viewport"==t.substr(0,"viewport".length))navigator.connection&&(navigator.connection.saveData||navigator.connection.effectiveType&&navigator.connection.effectiveType.includes("2g"))||("viewport"==t?document.documentElement.clientWidth*document.documentElement.clientHeight<45e4&&(m=!0):"viewport-all"==t&&(m=!0));else{const e=parseInt(t);isNaN(e)||(l=e)}}if(i){const n={capture:!0,passive:!0};if(f||document.addEventListener("touchstart",function(t){e=performance.now();const n=t.target.closest("a");if(!h(n))return;v(n.href)},n),u?c||document.addEventListener("mousedown",function(t){const e=t.target.closest("a");if(!h(e))return;v(e.href)},n):document.addEventListener("mouseover",function(n){if(performance.now()-e<d)return;const o=n.target.closest("a");if(!h(o))return;o.addEventListener("mouseout",p,{passive:!0}),t=setTimeout(()=>{v(o.href),t=void 0},l)},n),c&&document.addEventListener("mousedown",function(t){if(performance.now()-e<d)return;const n=t.target.closest("a");if(t.which>1||t.metaKey||t.ctrlKey)return;if(!n)return;n.addEventListener("click",function(t){1337!=t.detail&&t.preventDefault()},{capture:!0,passive:!1,once:!0});const o=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1,detail:1337});n.dispatchEvent(o)},n),m){let t;(t=window.requestIdleCallback?t=>{requestIdleCallback(t,{timeout:1500})}:t=>{t()})(()=>{const t=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const n=e.target;t.unobserve(n),v(n.href)}})});document.querySelectorAll("a").forEach(e=>{h(e)&&t.observe(e)})})}}function p(e){e.relatedTarget&&e.target.closest("a")==e.relatedTarget.closest("a")||t&&(clearTimeout(t),t=void 0)}function h(t){if(t&&t.href&&(!r||"instant"in t.dataset)&&(a||t.origin==location.origin||"instant"in t.dataset)&&["http:","https:"].includes(t.protocol)&&("http:"!=t.protocol||"https:"!=location.protocol)&&(s||!t.search||"instant"in t.dataset)&&!(t.hash&&t.pathname+t.search==location.pathname+location.search||"noInstant"in t.dataset))return!0}function v(t){if(n.has(t))return;const e=document.createElement("link");e.rel="prefetch",e.href=t,document.head.appendChild(e),n.add(t)}';
  380. document.head.appendChild(instantPageScript);
  381. // Make sections in the sidebar togglable.
  382. let hasCurrent = false;
  383. let menuHeaders = document.querySelectorAll('.wy-menu-vertical .caption[role=heading]');
  384. menuHeaders.forEach(it => {
  385. let connectedMenu = it.nextElementSibling;
  386. // Enable toggling.
  387. it.addEventListener('click', () => {
  388. if (connectedMenu.classList.contains('active')) {
  389. connectedMenu.classList.remove('active');
  390. it.classList.remove('active');
  391. } else {
  392. connectedMenu.classList.add('active');
  393. it.classList.add('active');
  394. }
  395. // Hide other sections.
  396. menuHeaders.forEach(ot => {
  397. if (ot !== it && ot.classList.contains('active')) {
  398. ot.nextElementSibling.classList.remove('active');
  399. ot.classList.remove('active');
  400. }
  401. });
  402. registerOnScrollEvent(mediaQuery);
  403. }, true);
  404. // Set the default state, expand our current section.
  405. if (connectedMenu.classList.contains('current')) {
  406. connectedMenu.classList.add('active');
  407. it.classList.add('active');
  408. hasCurrent = true;
  409. }
  410. });
  411. // Unfold the first (general information) section on the home page.
  412. if (!hasCurrent && menuHeaders.length > 0) {
  413. menuHeaders[0].classList.add('active');
  414. menuHeaders[0].nextElementSibling.classList.add('active');
  415. registerOnScrollEvent(mediaQuery);
  416. }
  417. // Giscus
  418. registerGiscus();
  419. });
  420. // Override the default implementation from doctools.js to avoid this behavior.
  421. Documentation.highlightSearchWords = function() {
  422. // Nope.
  423. }