custom.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. $(document).ready(() => {
  204. // Remove the search match highlights from the page, and adjust the URL in the
  205. // navigation history.
  206. const url = new URL(location.href);
  207. if (url.searchParams.has('highlight')) {
  208. Documentation.hideSearchWords();
  209. }
  210. // Initialize handlers for page scrolling and our custom sidebar.
  211. const mediaQuery = window.matchMedia('only screen and (min-width: 769px)');
  212. registerOnScrollEvent(mediaQuery);
  213. mediaQuery.addListener(registerOnScrollEvent);
  214. registerSidebarObserver(() => {
  215. registerOnScrollEvent(mediaQuery);
  216. });
  217. // Add line-break suggestions to the sidebar navigation items in the class reference section.
  218. //
  219. // Some class reference pages have very long PascalCase names, such as
  220. // VisualShaderNodeCurveXYZTexture
  221. // Those create issues for our layout, as we can neither make them wrap with CSS without
  222. // breaking normal article titles, nor is it good to have them overflow their containers.
  223. // So we use a <wbr> tag to insert mid-word suggestions for appropriate splits, so the browser
  224. // knows that it's okay to split it like
  225. // Visual Shader Node Curve XYZTexture
  226. // and add a new line at an opportune moment.
  227. const classReferenceLinks = document.querySelectorAll('.wy-menu-vertical > ul:last-of-type .reference.internal');
  228. for (const linkItem of classReferenceLinks) {
  229. let textNode = null;
  230. linkItem.childNodes.forEach(it => {
  231. if (it.nodeType === Node.TEXT_NODE) {
  232. // If this is a text node and if it needs to be updated, store a reference.
  233. let text = it.textContent;
  234. if (!(text.includes(" ") || text.length < 10)) {
  235. textNode = it;
  236. }
  237. }
  238. });
  239. if (textNode != null) {
  240. let text = textNode.textContent;
  241. // Add suggested line-breaks and replace the original text.
  242. // The regex looks for a lowercase letter followed by a number or an uppercase
  243. // letter. We avoid splitting at the last character in the name, though.
  244. text = text.replace(/([a-z])([A-Z0-9](?!$))/gm, '$1<wbr>$2');
  245. linkItem.removeChild(textNode);
  246. linkItem.insertAdjacentHTML('beforeend', text);
  247. }
  248. }
  249. // See `godot_is_latest` in conf.py
  250. const isLatest = document.querySelector('meta[name=doc_is_latest]').content.toLowerCase() === 'true';
  251. if (isLatest) {
  252. // Add a compatibility notice using JavaScript so it doesn't end up in the
  253. // automatically generated `meta description` tag.
  254. const baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
  255. // These lines only work as expected in the production environment, can't test this locally.
  256. const fallbackUrl = baseUrl.replace('/latest/', '/stable/');
  257. const homeUrl = baseUrl.split('/latest/')[0] + '/stable/';
  258. const searchUrl = homeUrl + 'search.html?q=';
  259. const noticeLink = document.querySelector('.latest-notice-link');
  260. // Insert a placeholder to display as we're making a request.
  261. noticeLink.innerHTML = `
  262. Checking the <a class="reference" href="${homeUrl}">stable version</a>
  263. of the documentation...
  264. `;
  265. // Make a HEAD request to the possible stable URL to check if the page exists.
  266. fetch(fallbackUrl, { method: 'HEAD' })
  267. .then((res) => {
  268. // We only check the HTTP status, which should tell us if the link is valid or not.
  269. if (res.status === 200) {
  270. noticeLink.innerHTML = `
  271. See the <a class="reference" href="${fallbackUrl}">stable version</a>
  272. of this documentation page instead.
  273. `;
  274. } else {
  275. // Err, just to fallthrough to catch.
  276. throw Error('Bad request');
  277. }
  278. })
  279. .catch((err) => {
  280. let message = `
  281. This page does not exist in the <a class="reference" href="${homeUrl}">stable version</a>
  282. of the documentation.
  283. `;
  284. // Also suggest a search query using the page's title. It should work with translations as well.
  285. // Note that we can't use the title tag as it has a permanent suffix. OG title doesn't, though.
  286. const titleMeta = document.querySelector('meta[property="og:title"]');
  287. if (typeof titleMeta !== 'undefined') {
  288. const pageTitle = titleMeta.getAttribute('content');
  289. message += `
  290. You can try searching for "<a class="reference" href="${searchUrl + encodeURIComponent(pageTitle)}">${pageTitle}</a>" instead.
  291. `;
  292. }
  293. noticeLink.innerHTML = message;
  294. });
  295. }
  296. // Load instant.page to prefetch pages upon hovering. This makes navigation feel
  297. // snappier. The script is dynamically appended as Read the Docs doesn't have
  298. // a way to add scripts with a "module" attribute.
  299. const instantPageScript = document.createElement('script');
  300. instantPageScript.toggleAttribute('module');
  301. /*! instant.page v5.1.0 - (C) 2019-2020 Alexandre Dieulot - https://instant.page/license */
  302. 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)}';
  303. document.head.appendChild(instantPageScript);
  304. // Make sections in the sidebar togglable.
  305. let hasCurrent = false;
  306. let menuHeaders = document.querySelectorAll('.wy-menu-vertical .caption[role=heading]');
  307. menuHeaders.forEach(it => {
  308. let connectedMenu = it.nextElementSibling;
  309. // Enable toggling.
  310. it.addEventListener('click', () => {
  311. if (connectedMenu.classList.contains('active')) {
  312. connectedMenu.classList.remove('active');
  313. it.classList.remove('active');
  314. } else {
  315. connectedMenu.classList.add('active');
  316. it.classList.add('active');
  317. }
  318. // Hide other sections.
  319. menuHeaders.forEach(ot => {
  320. if (ot !== it && ot.classList.contains('active')) {
  321. ot.nextElementSibling.classList.remove('active');
  322. ot.classList.remove('active');
  323. }
  324. });
  325. registerOnScrollEvent(mediaQuery);
  326. }, true);
  327. // Set the default state, expand our current section.
  328. if (connectedMenu.classList.contains('current')) {
  329. connectedMenu.classList.add('active');
  330. it.classList.add('active');
  331. hasCurrent = true;
  332. }
  333. });
  334. // Unfold the first (general information) section on the home page.
  335. if (!hasCurrent && menuHeaders.length > 0) {
  336. menuHeaders[0].classList.add('active');
  337. menuHeaders[0].nextElementSibling.classList.add('active');
  338. registerOnScrollEvent(mediaQuery);
  339. }
  340. });
  341. // Override the default implementation from doctools.js to avoid this behavior.
  342. Documentation.highlightSearchWords = function() {
  343. // Nope.
  344. }