quarto.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. const sectionChanged = new CustomEvent("quarto-sectionChanged", {
  2. detail: {},
  3. bubbles: true,
  4. cancelable: false,
  5. composed: false,
  6. });
  7. const layoutMarginEls = () => {
  8. // Find any conflicting margin elements and add margins to the
  9. // top to prevent overlap
  10. const marginChildren = window.document.querySelectorAll(
  11. ".column-margin.column-container > * "
  12. );
  13. let lastBottom = 0;
  14. for (const marginChild of marginChildren) {
  15. if (marginChild.offsetParent !== null) {
  16. // clear the top margin so we recompute it
  17. marginChild.style.marginTop = null;
  18. const top = marginChild.getBoundingClientRect().top + window.scrollY;
  19. console.log({
  20. childtop: marginChild.getBoundingClientRect().top,
  21. scroll: window.scrollY,
  22. top,
  23. lastBottom,
  24. });
  25. if (top < lastBottom) {
  26. const margin = lastBottom - top;
  27. marginChild.style.marginTop = `${margin}px`;
  28. }
  29. const styles = window.getComputedStyle(marginChild);
  30. const marginTop = parseFloat(styles["marginTop"]);
  31. console.log({
  32. top,
  33. height: marginChild.getBoundingClientRect().height,
  34. marginTop,
  35. total: top + marginChild.getBoundingClientRect().height + marginTop,
  36. });
  37. lastBottom = top + marginChild.getBoundingClientRect().height + marginTop;
  38. }
  39. }
  40. };
  41. window.document.addEventListener("DOMContentLoaded", function (_event) {
  42. // Recompute the position of margin elements anytime the body size changes
  43. if (window.ResizeObserver) {
  44. const resizeObserver = new window.ResizeObserver(
  45. throttle(layoutMarginEls, 50)
  46. );
  47. resizeObserver.observe(window.document.body);
  48. }
  49. const tocEl = window.document.querySelector('nav.toc-active[role="doc-toc"]');
  50. const sidebarEl = window.document.getElementById("quarto-sidebar");
  51. const leftTocEl = window.document.getElementById("quarto-sidebar-toc-left");
  52. const marginSidebarEl = window.document.getElementById(
  53. "quarto-margin-sidebar"
  54. );
  55. // function to determine whether the element has a previous sibling that is active
  56. const prevSiblingIsActiveLink = (el) => {
  57. const sibling = el.previousElementSibling;
  58. if (sibling && sibling.tagName === "A") {
  59. return sibling.classList.contains("active");
  60. } else {
  61. return false;
  62. }
  63. };
  64. // fire slideEnter for bootstrap tab activations (for htmlwidget resize behavior)
  65. function fireSlideEnter(e) {
  66. const event = window.document.createEvent("Event");
  67. event.initEvent("slideenter", true, true);
  68. window.document.dispatchEvent(event);
  69. }
  70. const tabs = window.document.querySelectorAll('a[data-bs-toggle="tab"]');
  71. tabs.forEach((tab) => {
  72. tab.addEventListener("shown.bs.tab", fireSlideEnter);
  73. });
  74. // fire slideEnter for tabby tab activations (for htmlwidget resize behavior)
  75. document.addEventListener("tabby", fireSlideEnter, false);
  76. // Track scrolling and mark TOC links as active
  77. // get table of contents and sidebar (bail if we don't have at least one)
  78. const tocLinks = tocEl
  79. ? [...tocEl.querySelectorAll("a[data-scroll-target]")]
  80. : [];
  81. const makeActive = (link) => tocLinks[link].classList.add("active");
  82. const removeActive = (link) => tocLinks[link].classList.remove("active");
  83. const removeAllActive = () =>
  84. [...Array(tocLinks.length).keys()].forEach((link) => removeActive(link));
  85. // activate the anchor for a section associated with this TOC entry
  86. tocLinks.forEach((link) => {
  87. link.addEventListener("click", () => {
  88. if (link.href.indexOf("#") !== -1) {
  89. const anchor = link.href.split("#")[1];
  90. const heading = window.document.querySelector(
  91. `[data-anchor-id=${anchor}]`
  92. );
  93. if (heading) {
  94. // Add the class
  95. heading.classList.add("reveal-anchorjs-link");
  96. // function to show the anchor
  97. const handleMouseout = () => {
  98. heading.classList.remove("reveal-anchorjs-link");
  99. heading.removeEventListener("mouseout", handleMouseout);
  100. };
  101. // add a function to clear the anchor when the user mouses out of it
  102. heading.addEventListener("mouseout", handleMouseout);
  103. }
  104. }
  105. });
  106. });
  107. const sections = tocLinks.map((link) => {
  108. const target = link.getAttribute("data-scroll-target");
  109. if (target.startsWith("#")) {
  110. return window.document.getElementById(decodeURI(`${target.slice(1)}`));
  111. } else {
  112. return window.document.querySelector(decodeURI(`${target}`));
  113. }
  114. });
  115. const sectionMargin = 200;
  116. let currentActive = 0;
  117. // track whether we've initialized state the first time
  118. let init = false;
  119. const updateActiveLink = () => {
  120. // The index from bottom to top (e.g. reversed list)
  121. let sectionIndex = -1;
  122. if (
  123. window.innerHeight + window.pageYOffset >=
  124. window.document.body.offsetHeight
  125. ) {
  126. sectionIndex = 0;
  127. } else {
  128. sectionIndex = [...sections].reverse().findIndex((section) => {
  129. if (section) {
  130. return window.pageYOffset >= section.offsetTop - sectionMargin;
  131. } else {
  132. return false;
  133. }
  134. });
  135. }
  136. if (sectionIndex > -1) {
  137. const current = sections.length - sectionIndex - 1;
  138. if (current !== currentActive) {
  139. removeAllActive();
  140. currentActive = current;
  141. makeActive(current);
  142. if (init) {
  143. window.dispatchEvent(sectionChanged);
  144. }
  145. init = true;
  146. }
  147. }
  148. };
  149. const inHiddenRegion = (top, bottom, hiddenRegions) => {
  150. for (const region of hiddenRegions) {
  151. if (top <= region.bottom && bottom >= region.top) {
  152. return true;
  153. }
  154. }
  155. return false;
  156. };
  157. const categorySelector = "header.quarto-title-block .quarto-category";
  158. const activateCategories = (href) => {
  159. // Find any categories
  160. // Surround them with a link pointing back to:
  161. // #category=Authoring
  162. try {
  163. const categoryEls = window.document.querySelectorAll(categorySelector);
  164. for (const categoryEl of categoryEls) {
  165. const categoryText = categoryEl.textContent;
  166. if (categoryText) {
  167. const link = `${href}#category=${encodeURIComponent(categoryText)}`;
  168. const linkEl = window.document.createElement("a");
  169. linkEl.setAttribute("href", link);
  170. for (const child of categoryEl.childNodes) {
  171. linkEl.append(child);
  172. }
  173. categoryEl.appendChild(linkEl);
  174. }
  175. }
  176. } catch {
  177. // Ignore errors
  178. }
  179. };
  180. function hasTitleCategories() {
  181. return window.document.querySelector(categorySelector) !== null;
  182. }
  183. function offsetRelativeUrl(url) {
  184. const offset = getMeta("quarto:offset");
  185. return offset ? offset + url : url;
  186. }
  187. function offsetAbsoluteUrl(url) {
  188. const offset = getMeta("quarto:offset");
  189. const baseUrl = new URL(offset, window.location);
  190. const projRelativeUrl = url.replace(baseUrl, "");
  191. if (projRelativeUrl.startsWith("/")) {
  192. return projRelativeUrl;
  193. } else {
  194. return "/" + projRelativeUrl;
  195. }
  196. }
  197. // read a meta tag value
  198. function getMeta(metaName) {
  199. const metas = window.document.getElementsByTagName("meta");
  200. for (let i = 0; i < metas.length; i++) {
  201. if (metas[i].getAttribute("name") === metaName) {
  202. return metas[i].getAttribute("content");
  203. }
  204. }
  205. return "";
  206. }
  207. async function findAndActivateCategories() {
  208. const currentPagePath = offsetAbsoluteUrl(window.location.href);
  209. const response = await fetch(offsetRelativeUrl("listings.json"));
  210. if (response.status == 200) {
  211. return response.json().then(function (listingPaths) {
  212. const listingHrefs = [];
  213. for (const listingPath of listingPaths) {
  214. const pathWithoutLeadingSlash = listingPath.listing.substring(1);
  215. for (const item of listingPath.items) {
  216. if (
  217. item === currentPagePath ||
  218. item === currentPagePath + "index.html"
  219. ) {
  220. // Resolve this path against the offset to be sure
  221. // we already are using the correct path to the listing
  222. // (this adjusts the listing urls to be rooted against
  223. // whatever root the page is actually running against)
  224. const relative = offsetRelativeUrl(pathWithoutLeadingSlash);
  225. const baseUrl = window.location;
  226. const resolvedPath = new URL(relative, baseUrl);
  227. listingHrefs.push(resolvedPath.pathname);
  228. break;
  229. }
  230. }
  231. }
  232. // Look up the tree for a nearby linting and use that if we find one
  233. const nearestListing = findNearestParentListing(
  234. offsetAbsoluteUrl(window.location.pathname),
  235. listingHrefs
  236. );
  237. if (nearestListing) {
  238. activateCategories(nearestListing);
  239. } else {
  240. // See if the referrer is a listing page for this item
  241. const referredRelativePath = offsetAbsoluteUrl(document.referrer);
  242. const referrerListing = listingHrefs.find((listingHref) => {
  243. const isListingReferrer =
  244. listingHref === referredRelativePath ||
  245. listingHref === referredRelativePath + "index.html";
  246. return isListingReferrer;
  247. });
  248. if (referrerListing) {
  249. // Try to use the referrer if possible
  250. activateCategories(referrerListing);
  251. } else if (listingHrefs.length > 0) {
  252. // Otherwise, just fall back to the first listing
  253. activateCategories(listingHrefs[0]);
  254. }
  255. }
  256. });
  257. }
  258. }
  259. if (hasTitleCategories()) {
  260. findAndActivateCategories();
  261. }
  262. const findNearestParentListing = (href, listingHrefs) => {
  263. if (!href || !listingHrefs) {
  264. return undefined;
  265. }
  266. // Look up the tree for a nearby linting and use that if we find one
  267. const relativeParts = href.substring(1).split("/");
  268. while (relativeParts.length > 0) {
  269. const path = relativeParts.join("/");
  270. for (const listingHref of listingHrefs) {
  271. if (listingHref.startsWith(path)) {
  272. return listingHref;
  273. }
  274. }
  275. relativeParts.pop();
  276. }
  277. return undefined;
  278. };
  279. const manageSidebarVisiblity = (el, placeholderDescriptor) => {
  280. let isVisible = true;
  281. let elRect;
  282. return (hiddenRegions) => {
  283. if (el === null) {
  284. return;
  285. }
  286. // Find the last element of the TOC
  287. const lastChildEl = el.lastElementChild;
  288. if (lastChildEl) {
  289. // Converts the sidebar to a menu
  290. const convertToMenu = () => {
  291. for (const child of el.children) {
  292. child.style.opacity = 0;
  293. child.style.overflow = "hidden";
  294. }
  295. nexttick(() => {
  296. const toggleContainer = window.document.createElement("div");
  297. toggleContainer.style.width = "100%";
  298. toggleContainer.classList.add("zindex-over-content");
  299. toggleContainer.classList.add("quarto-sidebar-toggle");
  300. toggleContainer.classList.add("headroom-target"); // Marks this to be managed by headeroom
  301. toggleContainer.id = placeholderDescriptor.id;
  302. toggleContainer.style.position = "fixed";
  303. const toggleIcon = window.document.createElement("i");
  304. toggleIcon.classList.add("quarto-sidebar-toggle-icon");
  305. toggleIcon.classList.add("bi");
  306. toggleIcon.classList.add("bi-caret-down-fill");
  307. const toggleTitle = window.document.createElement("div");
  308. const titleEl = window.document.body.querySelector(
  309. placeholderDescriptor.titleSelector
  310. );
  311. if (titleEl) {
  312. toggleTitle.append(
  313. titleEl.textContent || titleEl.innerText,
  314. toggleIcon
  315. );
  316. }
  317. toggleTitle.classList.add("zindex-over-content");
  318. toggleTitle.classList.add("quarto-sidebar-toggle-title");
  319. toggleContainer.append(toggleTitle);
  320. const toggleContents = window.document.createElement("div");
  321. toggleContents.classList = el.classList;
  322. toggleContents.classList.add("zindex-over-content");
  323. toggleContents.classList.add("quarto-sidebar-toggle-contents");
  324. for (const child of el.children) {
  325. if (child.id === "toc-title") {
  326. continue;
  327. }
  328. const clone = child.cloneNode(true);
  329. clone.style.opacity = 1;
  330. clone.style.display = null;
  331. toggleContents.append(clone);
  332. }
  333. toggleContents.style.height = "0px";
  334. const positionToggle = () => {
  335. // position the element (top left of parent, same width as parent)
  336. if (!elRect) {
  337. elRect = el.getBoundingClientRect();
  338. }
  339. toggleContainer.style.left = `${elRect.left}px`;
  340. toggleContainer.style.top = `${elRect.top}px`;
  341. toggleContainer.style.width = `${elRect.width}px`;
  342. };
  343. positionToggle();
  344. toggleContainer.append(toggleContents);
  345. el.parentElement.prepend(toggleContainer);
  346. // Process clicks
  347. let tocShowing = false;
  348. // Allow the caller to control whether this is dismissed
  349. // when it is clicked (e.g. sidebar navigation supports
  350. // opening and closing the nav tree, so don't dismiss on click)
  351. const clickEl = placeholderDescriptor.dismissOnClick
  352. ? toggleContainer
  353. : toggleTitle;
  354. const closeToggle = () => {
  355. if (tocShowing) {
  356. toggleContainer.classList.remove("expanded");
  357. toggleContents.style.height = "0px";
  358. tocShowing = false;
  359. }
  360. };
  361. // Get rid of any expanded toggle if the user scrolls
  362. window.document.addEventListener(
  363. "scroll",
  364. throttle(() => {
  365. closeToggle();
  366. }, 50)
  367. );
  368. // Handle positioning of the toggle
  369. window.addEventListener(
  370. "resize",
  371. throttle(() => {
  372. elRect = undefined;
  373. positionToggle();
  374. }, 50)
  375. );
  376. window.addEventListener("quarto-hrChanged", () => {
  377. elRect = undefined;
  378. });
  379. // Process the click
  380. clickEl.onclick = () => {
  381. if (!tocShowing) {
  382. toggleContainer.classList.add("expanded");
  383. toggleContents.style.height = null;
  384. tocShowing = true;
  385. } else {
  386. closeToggle();
  387. }
  388. };
  389. });
  390. };
  391. // Converts a sidebar from a menu back to a sidebar
  392. const convertToSidebar = () => {
  393. for (const child of el.children) {
  394. child.style.opacity = 1;
  395. child.style.overflow = null;
  396. }
  397. const placeholderEl = window.document.getElementById(
  398. placeholderDescriptor.id
  399. );
  400. if (placeholderEl) {
  401. placeholderEl.remove();
  402. }
  403. el.classList.remove("rollup");
  404. };
  405. if (isReaderMode()) {
  406. convertToMenu();
  407. isVisible = false;
  408. } else {
  409. // Find the top and bottom o the element that is being managed
  410. const elTop = el.offsetTop;
  411. const elBottom =
  412. elTop + lastChildEl.offsetTop + lastChildEl.offsetHeight;
  413. if (!isVisible) {
  414. // If the element is current not visible reveal if there are
  415. // no conflicts with overlay regions
  416. if (!inHiddenRegion(elTop, elBottom, hiddenRegions)) {
  417. convertToSidebar();
  418. isVisible = true;
  419. }
  420. } else {
  421. // If the element is visible, hide it if it conflicts with overlay regions
  422. // and insert a placeholder toggle (or if we're in reader mode)
  423. if (inHiddenRegion(elTop, elBottom, hiddenRegions)) {
  424. convertToMenu();
  425. isVisible = false;
  426. }
  427. }
  428. }
  429. }
  430. };
  431. };
  432. const tabEls = document.querySelectorAll('a[data-bs-toggle="tab"]');
  433. for (const tabEl of tabEls) {
  434. const id = tabEl.getAttribute("data-bs-target");
  435. if (id) {
  436. const columnEl = document.querySelector(
  437. `${id} .column-margin, .tabset-margin-content`
  438. );
  439. if (columnEl)
  440. tabEl.addEventListener("shown.bs.tab", function (event) {
  441. const el = event.srcElement;
  442. if (el) {
  443. const visibleCls = `${el.id}-margin-content`;
  444. // walk up until we find a parent tabset
  445. let panelTabsetEl = el.parentElement;
  446. while (panelTabsetEl) {
  447. if (panelTabsetEl.classList.contains("panel-tabset")) {
  448. break;
  449. }
  450. panelTabsetEl = panelTabsetEl.parentElement;
  451. }
  452. if (panelTabsetEl) {
  453. const prevSib = panelTabsetEl.previousElementSibling;
  454. if (
  455. prevSib &&
  456. prevSib.classList.contains("tabset-margin-container")
  457. ) {
  458. const childNodes = prevSib.querySelectorAll(
  459. ".tabset-margin-content"
  460. );
  461. for (const childEl of childNodes) {
  462. if (childEl.classList.contains(visibleCls)) {
  463. childEl.classList.remove("collapse");
  464. } else {
  465. childEl.classList.add("collapse");
  466. }
  467. }
  468. }
  469. }
  470. }
  471. layoutMarginEls();
  472. });
  473. }
  474. }
  475. // Manage the visibility of the toc and the sidebar
  476. const marginScrollVisibility = manageSidebarVisiblity(marginSidebarEl, {
  477. id: "quarto-toc-toggle",
  478. titleSelector: "#toc-title",
  479. dismissOnClick: true,
  480. });
  481. const sidebarScrollVisiblity = manageSidebarVisiblity(sidebarEl, {
  482. id: "quarto-sidebarnav-toggle",
  483. titleSelector: ".title",
  484. dismissOnClick: false,
  485. });
  486. let tocLeftScrollVisibility;
  487. if (leftTocEl) {
  488. tocLeftScrollVisibility = manageSidebarVisiblity(leftTocEl, {
  489. id: "quarto-lefttoc-toggle",
  490. titleSelector: "#toc-title",
  491. dismissOnClick: true,
  492. });
  493. }
  494. // Find the first element that uses formatting in special columns
  495. const conflictingEls = window.document.body.querySelectorAll(
  496. '[class^="column-"], [class*=" column-"], aside, [class*="margin-caption"], [class*=" margin-caption"], [class*="margin-ref"], [class*=" margin-ref"]'
  497. );
  498. // Filter all the possibly conflicting elements into ones
  499. // the do conflict on the left or ride side
  500. const arrConflictingEls = Array.from(conflictingEls);
  501. const leftSideConflictEls = arrConflictingEls.filter((el) => {
  502. if (el.tagName === "ASIDE") {
  503. return false;
  504. }
  505. return Array.from(el.classList).find((className) => {
  506. return (
  507. className !== "column-body" &&
  508. className.startsWith("column-") &&
  509. !className.endsWith("right") &&
  510. !className.endsWith("container") &&
  511. className !== "column-margin"
  512. );
  513. });
  514. });
  515. const rightSideConflictEls = arrConflictingEls.filter((el) => {
  516. if (el.tagName === "ASIDE") {
  517. return true;
  518. }
  519. const hasMarginCaption = Array.from(el.classList).find((className) => {
  520. return className == "margin-caption";
  521. });
  522. if (hasMarginCaption) {
  523. return true;
  524. }
  525. return Array.from(el.classList).find((className) => {
  526. return (
  527. className !== "column-body" &&
  528. !className.endsWith("container") &&
  529. className.startsWith("column-") &&
  530. !className.endsWith("left")
  531. );
  532. });
  533. });
  534. const kOverlapPaddingSize = 10;
  535. function toRegions(els) {
  536. return els.map((el) => {
  537. const boundRect = el.getBoundingClientRect();
  538. const top =
  539. boundRect.top +
  540. document.documentElement.scrollTop -
  541. kOverlapPaddingSize;
  542. return {
  543. top,
  544. bottom: top + el.scrollHeight + 2 * kOverlapPaddingSize,
  545. };
  546. });
  547. }
  548. let hasObserved = false;
  549. const visibleItemObserver = (els) => {
  550. let visibleElements = [...els];
  551. const intersectionObserver = new IntersectionObserver(
  552. (entries, _observer) => {
  553. entries.forEach((entry) => {
  554. if (entry.isIntersecting) {
  555. if (visibleElements.indexOf(entry.target) === -1) {
  556. visibleElements.push(entry.target);
  557. }
  558. } else {
  559. visibleElements = visibleElements.filter((visibleEntry) => {
  560. return visibleEntry !== entry;
  561. });
  562. }
  563. });
  564. if (!hasObserved) {
  565. hideOverlappedSidebars();
  566. }
  567. hasObserved = true;
  568. },
  569. {}
  570. );
  571. els.forEach((el) => {
  572. intersectionObserver.observe(el);
  573. });
  574. return {
  575. getVisibleEntries: () => {
  576. return visibleElements;
  577. },
  578. };
  579. };
  580. const rightElementObserver = visibleItemObserver(rightSideConflictEls);
  581. const leftElementObserver = visibleItemObserver(leftSideConflictEls);
  582. const hideOverlappedSidebars = () => {
  583. marginScrollVisibility(toRegions(rightElementObserver.getVisibleEntries()));
  584. sidebarScrollVisiblity(toRegions(leftElementObserver.getVisibleEntries()));
  585. if (tocLeftScrollVisibility) {
  586. tocLeftScrollVisibility(
  587. toRegions(leftElementObserver.getVisibleEntries())
  588. );
  589. }
  590. };
  591. window.quartoToggleReader = () => {
  592. // Applies a slow class (or removes it)
  593. // to update the transition speed
  594. const slowTransition = (slow) => {
  595. const manageTransition = (id, slow) => {
  596. const el = document.getElementById(id);
  597. if (el) {
  598. if (slow) {
  599. el.classList.add("slow");
  600. } else {
  601. el.classList.remove("slow");
  602. }
  603. }
  604. };
  605. manageTransition("TOC", slow);
  606. manageTransition("quarto-sidebar", slow);
  607. };
  608. const readerMode = !isReaderMode();
  609. setReaderModeValue(readerMode);
  610. // If we're entering reader mode, slow the transition
  611. if (readerMode) {
  612. slowTransition(readerMode);
  613. }
  614. highlightReaderToggle(readerMode);
  615. hideOverlappedSidebars();
  616. // If we're exiting reader mode, restore the non-slow transition
  617. if (!readerMode) {
  618. slowTransition(!readerMode);
  619. }
  620. };
  621. const highlightReaderToggle = (readerMode) => {
  622. const els = document.querySelectorAll(".quarto-reader-toggle");
  623. if (els) {
  624. els.forEach((el) => {
  625. if (readerMode) {
  626. el.classList.add("reader");
  627. } else {
  628. el.classList.remove("reader");
  629. }
  630. });
  631. }
  632. };
  633. const setReaderModeValue = (val) => {
  634. if (window.location.protocol !== "file:") {
  635. window.localStorage.setItem("quarto-reader-mode", val);
  636. } else {
  637. localReaderMode = val;
  638. }
  639. };
  640. const isReaderMode = () => {
  641. if (window.location.protocol !== "file:") {
  642. return window.localStorage.getItem("quarto-reader-mode") === "true";
  643. } else {
  644. return localReaderMode;
  645. }
  646. };
  647. let localReaderMode = null;
  648. const tocOpenDepthStr = tocEl?.getAttribute("data-toc-expanded");
  649. const tocOpenDepth = tocOpenDepthStr ? Number(tocOpenDepthStr) : 1;
  650. // Walk the TOC and collapse/expand nodes
  651. // Nodes are expanded if:
  652. // - they are top level
  653. // - they have children that are 'active' links
  654. // - they are directly below an link that is 'active'
  655. const walk = (el, depth) => {
  656. // Tick depth when we enter a UL
  657. if (el.tagName === "UL") {
  658. depth = depth + 1;
  659. }
  660. // It this is active link
  661. let isActiveNode = false;
  662. if (el.tagName === "A" && el.classList.contains("active")) {
  663. isActiveNode = true;
  664. }
  665. // See if there is an active child to this element
  666. let hasActiveChild = false;
  667. for (child of el.children) {
  668. hasActiveChild = walk(child, depth) || hasActiveChild;
  669. }
  670. // Process the collapse state if this is an UL
  671. if (el.tagName === "UL") {
  672. if (tocOpenDepth === -1 && depth > 1) {
  673. el.classList.add("collapse");
  674. } else if (
  675. depth <= tocOpenDepth ||
  676. hasActiveChild ||
  677. prevSiblingIsActiveLink(el)
  678. ) {
  679. el.classList.remove("collapse");
  680. } else {
  681. el.classList.add("collapse");
  682. }
  683. // untick depth when we leave a UL
  684. depth = depth - 1;
  685. }
  686. return hasActiveChild || isActiveNode;
  687. };
  688. // walk the TOC and expand / collapse any items that should be shown
  689. if (tocEl) {
  690. walk(tocEl, 0);
  691. updateActiveLink();
  692. }
  693. // Throttle the scroll event and walk peridiocally
  694. window.document.addEventListener(
  695. "scroll",
  696. throttle(() => {
  697. if (tocEl) {
  698. updateActiveLink();
  699. walk(tocEl, 0);
  700. }
  701. if (!isReaderMode()) {
  702. hideOverlappedSidebars();
  703. }
  704. }, 5)
  705. );
  706. window.addEventListener(
  707. "resize",
  708. throttle(() => {
  709. if (!isReaderMode()) {
  710. hideOverlappedSidebars();
  711. }
  712. }, 10)
  713. );
  714. hideOverlappedSidebars();
  715. highlightReaderToggle(isReaderMode());
  716. });
  717. // grouped tabsets
  718. window.addEventListener("pageshow", (_event) => {
  719. function getTabSettings() {
  720. const data = localStorage.getItem("quarto-persistent-tabsets-data");
  721. if (!data) {
  722. localStorage.setItem("quarto-persistent-tabsets-data", "{}");
  723. return {};
  724. }
  725. if (data) {
  726. return JSON.parse(data);
  727. }
  728. }
  729. function setTabSettings(data) {
  730. localStorage.setItem(
  731. "quarto-persistent-tabsets-data",
  732. JSON.stringify(data)
  733. );
  734. }
  735. function setTabState(groupName, groupValue) {
  736. const data = getTabSettings();
  737. data[groupName] = groupValue;
  738. setTabSettings(data);
  739. }
  740. function toggleTab(tab, active) {
  741. const tabPanelId = tab.getAttribute("aria-controls");
  742. const tabPanel = document.getElementById(tabPanelId);
  743. if (active) {
  744. tab.classList.add("active");
  745. tabPanel.classList.add("active");
  746. } else {
  747. tab.classList.remove("active");
  748. tabPanel.classList.remove("active");
  749. }
  750. }
  751. function toggleAll(selectedGroup, selectorsToSync) {
  752. for (const [thisGroup, tabs] of Object.entries(selectorsToSync)) {
  753. const active = selectedGroup === thisGroup;
  754. for (const tab of tabs) {
  755. toggleTab(tab, active);
  756. }
  757. }
  758. }
  759. function findSelectorsToSyncByLanguage() {
  760. const result = {};
  761. const tabs = Array.from(
  762. document.querySelectorAll(`div[data-group] a[id^='tabset-']`)
  763. );
  764. for (const item of tabs) {
  765. const div = item.parentElement.parentElement.parentElement;
  766. const group = div.getAttribute("data-group");
  767. if (!result[group]) {
  768. result[group] = {};
  769. }
  770. const selectorsToSync = result[group];
  771. const value = item.innerHTML;
  772. if (!selectorsToSync[value]) {
  773. selectorsToSync[value] = [];
  774. }
  775. selectorsToSync[value].push(item);
  776. }
  777. return result;
  778. }
  779. function setupSelectorSync() {
  780. const selectorsToSync = findSelectorsToSyncByLanguage();
  781. Object.entries(selectorsToSync).forEach(([group, tabSetsByValue]) => {
  782. Object.entries(tabSetsByValue).forEach(([value, items]) => {
  783. items.forEach((item) => {
  784. item.addEventListener("click", (_event) => {
  785. setTabState(group, value);
  786. toggleAll(value, selectorsToSync[group]);
  787. });
  788. });
  789. });
  790. });
  791. return selectorsToSync;
  792. }
  793. const selectorsToSync = setupSelectorSync();
  794. for (const [group, selectedName] of Object.entries(getTabSettings())) {
  795. const selectors = selectorsToSync[group];
  796. // it's possible that stale state gives us empty selections, so we explicitly check here.
  797. if (selectors) {
  798. toggleAll(selectedName, selectors);
  799. }
  800. }
  801. });
  802. function throttle(func, wait) {
  803. let waiting = false;
  804. return function () {
  805. if (!waiting) {
  806. func.apply(this, arguments);
  807. waiting = true;
  808. setTimeout(function () {
  809. waiting = false;
  810. }, wait);
  811. }
  812. };
  813. }
  814. function nexttick(func) {
  815. return setTimeout(func, 0);
  816. }