quarto.js 27.7 KB
Newer Older
Ivan Merelli's avatar
Ivan Merelli committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
const sectionChanged = new CustomEvent("quarto-sectionChanged", {
  detail: {},
  bubbles: true,
  cancelable: false,
  composed: false,
});

const layoutMarginEls = () => {
  // Find any conflicting margin elements and add margins to the
  // top to prevent overlap
  const marginChildren = window.document.querySelectorAll(
    ".column-margin.column-container > * "
  );

  let lastBottom = 0;
  for (const marginChild of marginChildren) {
    if (marginChild.offsetParent !== null) {
      // clear the top margin so we recompute it
      marginChild.style.marginTop = null;
      const top = marginChild.getBoundingClientRect().top + window.scrollY;
      console.log({
        childtop: marginChild.getBoundingClientRect().top,
        scroll: window.scrollY,
        top,
        lastBottom,
      });
      if (top < lastBottom) {
        const margin = lastBottom - top;
        marginChild.style.marginTop = `${margin}px`;
      }
      const styles = window.getComputedStyle(marginChild);
      const marginTop = parseFloat(styles["marginTop"]);

      console.log({
        top,
        height: marginChild.getBoundingClientRect().height,
        marginTop,
        total: top + marginChild.getBoundingClientRect().height + marginTop,
      });
      lastBottom = top + marginChild.getBoundingClientRect().height + marginTop;
    }
  }
};

window.document.addEventListener("DOMContentLoaded", function (_event) {
  // Recompute the position of margin elements anytime the body size changes
  if (window.ResizeObserver) {
    const resizeObserver = new window.ResizeObserver(
      throttle(layoutMarginEls, 50)
    );
    resizeObserver.observe(window.document.body);
  }

  const tocEl = window.document.querySelector('nav.toc-active[role="doc-toc"]');
  const sidebarEl = window.document.getElementById("quarto-sidebar");
  const leftTocEl = window.document.getElementById("quarto-sidebar-toc-left");
  const marginSidebarEl = window.document.getElementById(
    "quarto-margin-sidebar"
  );
  // function to determine whether the element has a previous sibling that is active
  const prevSiblingIsActiveLink = (el) => {
    const sibling = el.previousElementSibling;
    if (sibling && sibling.tagName === "A") {
      return sibling.classList.contains("active");
    } else {
      return false;
    }
  };

  // fire slideEnter for bootstrap tab activations (for htmlwidget resize behavior)
  function fireSlideEnter(e) {
    const event = window.document.createEvent("Event");
    event.initEvent("slideenter", true, true);
    window.document.dispatchEvent(event);
  }
  const tabs = window.document.querySelectorAll('a[data-bs-toggle="tab"]');
  tabs.forEach((tab) => {
    tab.addEventListener("shown.bs.tab", fireSlideEnter);
  });

  // fire slideEnter for tabby tab activations (for htmlwidget resize behavior)
  document.addEventListener("tabby", fireSlideEnter, false);

  // Track scrolling and mark TOC links as active
  // get table of contents and sidebar (bail if we don't have at least one)
  const tocLinks = tocEl
    ? [...tocEl.querySelectorAll("a[data-scroll-target]")]
    : [];
  const makeActive = (link) => tocLinks[link].classList.add("active");
  const removeActive = (link) => tocLinks[link].classList.remove("active");
  const removeAllActive = () =>
    [...Array(tocLinks.length).keys()].forEach((link) => removeActive(link));

  // activate the anchor for a section associated with this TOC entry
  tocLinks.forEach((link) => {
    link.addEventListener("click", () => {
      if (link.href.indexOf("#") !== -1) {
        const anchor = link.href.split("#")[1];
        const heading = window.document.querySelector(
          `[data-anchor-id=${anchor}]`
        );
        if (heading) {
          // Add the class
          heading.classList.add("reveal-anchorjs-link");

          // function to show the anchor
          const handleMouseout = () => {
            heading.classList.remove("reveal-anchorjs-link");
            heading.removeEventListener("mouseout", handleMouseout);
          };

          // add a function to clear the anchor when the user mouses out of it
          heading.addEventListener("mouseout", handleMouseout);
        }
      }
    });
  });

  const sections = tocLinks.map((link) => {
    const target = link.getAttribute("data-scroll-target");
    if (target.startsWith("#")) {
      return window.document.getElementById(decodeURI(`${target.slice(1)}`));
    } else {
      return window.document.querySelector(decodeURI(`${target}`));
    }
  });

  const sectionMargin = 200;
  let currentActive = 0;
  // track whether we've initialized state the first time
  let init = false;

  const updateActiveLink = () => {
    // The index from bottom to top (e.g. reversed list)
    let sectionIndex = -1;
    if (
      window.innerHeight + window.pageYOffset >=
      window.document.body.offsetHeight
    ) {
      sectionIndex = 0;
    } else {
      sectionIndex = [...sections].reverse().findIndex((section) => {
        if (section) {
          return window.pageYOffset >= section.offsetTop - sectionMargin;
        } else {
          return false;
        }
      });
    }
    if (sectionIndex > -1) {
      const current = sections.length - sectionIndex - 1;
      if (current !== currentActive) {
        removeAllActive();
        currentActive = current;
        makeActive(current);
        if (init) {
          window.dispatchEvent(sectionChanged);
        }
        init = true;
      }
    }
  };

  const inHiddenRegion = (top, bottom, hiddenRegions) => {
    for (const region of hiddenRegions) {
      if (top <= region.bottom && bottom >= region.top) {
        return true;
      }
    }
    return false;
  };

  const categorySelector = "header.quarto-title-block .quarto-category";
  const activateCategories = (href) => {
    // Find any categories
    // Surround them with a link pointing back to:
    // #category=Authoring
    try {
      const categoryEls = window.document.querySelectorAll(categorySelector);
      for (const categoryEl of categoryEls) {
        const categoryText = categoryEl.textContent;
        if (categoryText) {
          const link = `${href}#category=${encodeURIComponent(categoryText)}`;
          const linkEl = window.document.createElement("a");
          linkEl.setAttribute("href", link);
          for (const child of categoryEl.childNodes) {
            linkEl.append(child);
          }
          categoryEl.appendChild(linkEl);
        }
      }
    } catch {
      // Ignore errors
    }
  };
  function hasTitleCategories() {
    return window.document.querySelector(categorySelector) !== null;
  }

  function offsetRelativeUrl(url) {
    const offset = getMeta("quarto:offset");
    return offset ? offset + url : url;
  }

  function offsetAbsoluteUrl(url) {
    const offset = getMeta("quarto:offset");
    const baseUrl = new URL(offset, window.location);

    const projRelativeUrl = url.replace(baseUrl, "");
    if (projRelativeUrl.startsWith("/")) {
      return projRelativeUrl;
    } else {
      return "/" + projRelativeUrl;
    }
  }

  // read a meta tag value
  function getMeta(metaName) {
    const metas = window.document.getElementsByTagName("meta");
    for (let i = 0; i < metas.length; i++) {
      if (metas[i].getAttribute("name") === metaName) {
        return metas[i].getAttribute("content");
      }
    }
    return "";
  }

  async function findAndActivateCategories() {
    const currentPagePath = offsetAbsoluteUrl(window.location.href);
    const response = await fetch(offsetRelativeUrl("listings.json"));
    if (response.status == 200) {
      return response.json().then(function (listingPaths) {
        const listingHrefs = [];
        for (const listingPath of listingPaths) {
          const pathWithoutLeadingSlash = listingPath.listing.substring(1);
          for (const item of listingPath.items) {
            if (
              item === currentPagePath ||
              item === currentPagePath + "index.html"
            ) {
              // Resolve this path against the offset to be sure
              // we already are using the correct path to the listing
              // (this adjusts the listing urls to be rooted against
              // whatever root the page is actually running against)
              const relative = offsetRelativeUrl(pathWithoutLeadingSlash);
              const baseUrl = window.location;
              const resolvedPath = new URL(relative, baseUrl);
              listingHrefs.push(resolvedPath.pathname);
              break;
            }
          }
        }

        // Look up the tree for a nearby linting and use that if we find one
        const nearestListing = findNearestParentListing(
          offsetAbsoluteUrl(window.location.pathname),
          listingHrefs
        );
        if (nearestListing) {
          activateCategories(nearestListing);
        } else {
          // See if the referrer is a listing page for this item
          const referredRelativePath = offsetAbsoluteUrl(document.referrer);
          const referrerListing = listingHrefs.find((listingHref) => {
            const isListingReferrer =
              listingHref === referredRelativePath ||
              listingHref === referredRelativePath + "index.html";
            return isListingReferrer;
          });

          if (referrerListing) {
            // Try to use the referrer if possible
            activateCategories(referrerListing);
          } else if (listingHrefs.length > 0) {
            // Otherwise, just fall back to the first listing
            activateCategories(listingHrefs[0]);
          }
        }
      });
    }
  }
  if (hasTitleCategories()) {
    findAndActivateCategories();
  }

  const findNearestParentListing = (href, listingHrefs) => {
    if (!href || !listingHrefs) {
      return undefined;
    }
    // Look up the tree for a nearby linting and use that if we find one
    const relativeParts = href.substring(1).split("/");
    while (relativeParts.length > 0) {
      const path = relativeParts.join("/");
      for (const listingHref of listingHrefs) {
        if (listingHref.startsWith(path)) {
          return listingHref;
        }
      }
      relativeParts.pop();
    }

    return undefined;
  };

  const manageSidebarVisiblity = (el, placeholderDescriptor) => {
    let isVisible = true;
    let elRect;

    return (hiddenRegions) => {
      if (el === null) {
        return;
      }

      // Find the last element of the TOC
      const lastChildEl = el.lastElementChild;

      if (lastChildEl) {
        // Converts the sidebar to a menu
        const convertToMenu = () => {
          for (const child of el.children) {
            child.style.opacity = 0;
            child.style.overflow = "hidden";
          }

          nexttick(() => {
            const toggleContainer = window.document.createElement("div");
            toggleContainer.style.width = "100%";
            toggleContainer.classList.add("zindex-over-content");
            toggleContainer.classList.add("quarto-sidebar-toggle");
            toggleContainer.classList.add("headroom-target"); // Marks this to be managed by headeroom
            toggleContainer.id = placeholderDescriptor.id;
            toggleContainer.style.position = "fixed";

            const toggleIcon = window.document.createElement("i");
            toggleIcon.classList.add("quarto-sidebar-toggle-icon");
            toggleIcon.classList.add("bi");
            toggleIcon.classList.add("bi-caret-down-fill");

            const toggleTitle = window.document.createElement("div");
            const titleEl = window.document.body.querySelector(
              placeholderDescriptor.titleSelector
            );
            if (titleEl) {
              toggleTitle.append(
                titleEl.textContent || titleEl.innerText,
                toggleIcon
              );
            }
            toggleTitle.classList.add("zindex-over-content");
            toggleTitle.classList.add("quarto-sidebar-toggle-title");
            toggleContainer.append(toggleTitle);

            const toggleContents = window.document.createElement("div");
            toggleContents.classList = el.classList;
            toggleContents.classList.add("zindex-over-content");
            toggleContents.classList.add("quarto-sidebar-toggle-contents");
            for (const child of el.children) {
              if (child.id === "toc-title") {
                continue;
              }

              const clone = child.cloneNode(true);
              clone.style.opacity = 1;
              clone.style.display = null;
              toggleContents.append(clone);
            }
            toggleContents.style.height = "0px";
            const positionToggle = () => {
              // position the element (top left of parent, same width as parent)
              if (!elRect) {
                elRect = el.getBoundingClientRect();
              }
              toggleContainer.style.left = `${elRect.left}px`;
              toggleContainer.style.top = `${elRect.top}px`;
              toggleContainer.style.width = `${elRect.width}px`;
            };
            positionToggle();

            toggleContainer.append(toggleContents);
            el.parentElement.prepend(toggleContainer);

            // Process clicks
            let tocShowing = false;
            // Allow the caller to control whether this is dismissed
            // when it is clicked (e.g. sidebar navigation supports
            // opening and closing the nav tree, so don't dismiss on click)
            const clickEl = placeholderDescriptor.dismissOnClick
              ? toggleContainer
              : toggleTitle;

            const closeToggle = () => {
              if (tocShowing) {
                toggleContainer.classList.remove("expanded");
                toggleContents.style.height = "0px";
                tocShowing = false;
              }
            };

            // Get rid of any expanded toggle if the user scrolls
            window.document.addEventListener(
              "scroll",
              throttle(() => {
                closeToggle();
              }, 50)
            );

            // Handle positioning of the toggle
            window.addEventListener(
              "resize",
              throttle(() => {
                elRect = undefined;
                positionToggle();
              }, 50)
            );

            window.addEventListener("quarto-hrChanged", () => {
              elRect = undefined;
            });

            // Process the click
            clickEl.onclick = () => {
              if (!tocShowing) {
                toggleContainer.classList.add("expanded");
                toggleContents.style.height = null;
                tocShowing = true;
              } else {
                closeToggle();
              }
            };
          });
        };

        // Converts a sidebar from a menu back to a sidebar
        const convertToSidebar = () => {
          for (const child of el.children) {
            child.style.opacity = 1;
            child.style.overflow = null;
          }

          const placeholderEl = window.document.getElementById(
            placeholderDescriptor.id
          );
          if (placeholderEl) {
            placeholderEl.remove();
          }

          el.classList.remove("rollup");
        };

        if (isReaderMode()) {
          convertToMenu();
          isVisible = false;
        } else {
          // Find the top and bottom o the element that is being managed
          const elTop = el.offsetTop;
          const elBottom =
            elTop + lastChildEl.offsetTop + lastChildEl.offsetHeight;

          if (!isVisible) {
            // If the element is current not visible reveal if there are
            // no conflicts with overlay regions
            if (!inHiddenRegion(elTop, elBottom, hiddenRegions)) {
              convertToSidebar();
              isVisible = true;
            }
          } else {
            // If the element is visible, hide it if it conflicts with overlay regions
            // and insert a placeholder toggle (or if we're in reader mode)
            if (inHiddenRegion(elTop, elBottom, hiddenRegions)) {
              convertToMenu();
              isVisible = false;
            }
          }
        }
      }
    };
  };

  const tabEls = document.querySelectorAll('a[data-bs-toggle="tab"]');
  for (const tabEl of tabEls) {
    const id = tabEl.getAttribute("data-bs-target");
    if (id) {
      const columnEl = document.querySelector(
        `${id} .column-margin, .tabset-margin-content`
      );
      if (columnEl)
        tabEl.addEventListener("shown.bs.tab", function (event) {
          const el = event.srcElement;
          if (el) {
            const visibleCls = `${el.id}-margin-content`;
            // walk up until we find a parent tabset
            let panelTabsetEl = el.parentElement;
            while (panelTabsetEl) {
              if (panelTabsetEl.classList.contains("panel-tabset")) {
                break;
              }
              panelTabsetEl = panelTabsetEl.parentElement;
            }

            if (panelTabsetEl) {
              const prevSib = panelTabsetEl.previousElementSibling;
              if (
                prevSib &&
                prevSib.classList.contains("tabset-margin-container")
              ) {
                const childNodes = prevSib.querySelectorAll(
                  ".tabset-margin-content"
                );
                for (const childEl of childNodes) {
                  if (childEl.classList.contains(visibleCls)) {
                    childEl.classList.remove("collapse");
                  } else {
                    childEl.classList.add("collapse");
                  }
                }
              }
            }
          }

          layoutMarginEls();
        });
    }
  }

  // Manage the visibility of the toc and the sidebar
  const marginScrollVisibility = manageSidebarVisiblity(marginSidebarEl, {
    id: "quarto-toc-toggle",
    titleSelector: "#toc-title",
    dismissOnClick: true,
  });
  const sidebarScrollVisiblity = manageSidebarVisiblity(sidebarEl, {
    id: "quarto-sidebarnav-toggle",
    titleSelector: ".title",
    dismissOnClick: false,
  });
  let tocLeftScrollVisibility;
  if (leftTocEl) {
    tocLeftScrollVisibility = manageSidebarVisiblity(leftTocEl, {
      id: "quarto-lefttoc-toggle",
      titleSelector: "#toc-title",
      dismissOnClick: true,
    });
  }

  // Find the first element that uses formatting in special columns
  const conflictingEls = window.document.body.querySelectorAll(
    '[class^="column-"], [class*=" column-"], aside, [class*="margin-caption"], [class*=" margin-caption"], [class*="margin-ref"], [class*=" margin-ref"]'
  );

  // Filter all the possibly conflicting elements into ones
  // the do conflict on the left or ride side
  const arrConflictingEls = Array.from(conflictingEls);
  const leftSideConflictEls = arrConflictingEls.filter((el) => {
    if (el.tagName === "ASIDE") {
      return false;
    }
    return Array.from(el.classList).find((className) => {
      return (
        className !== "column-body" &&
        className.startsWith("column-") &&
        !className.endsWith("right") &&
        !className.endsWith("container") &&
        className !== "column-margin"
      );
    });
  });
  const rightSideConflictEls = arrConflictingEls.filter((el) => {
    if (el.tagName === "ASIDE") {
      return true;
    }

    const hasMarginCaption = Array.from(el.classList).find((className) => {
      return className == "margin-caption";
    });
    if (hasMarginCaption) {
      return true;
    }

    return Array.from(el.classList).find((className) => {
      return (
        className !== "column-body" &&
        !className.endsWith("container") &&
        className.startsWith("column-") &&
        !className.endsWith("left")
      );
    });
  });

  const kOverlapPaddingSize = 10;
  function toRegions(els) {
    return els.map((el) => {
      const boundRect = el.getBoundingClientRect();
      const top =
        boundRect.top +
        document.documentElement.scrollTop -
        kOverlapPaddingSize;
      return {
        top,
        bottom: top + el.scrollHeight + 2 * kOverlapPaddingSize,
      };
    });
  }

  let hasObserved = false;
  const visibleItemObserver = (els) => {
    let visibleElements = [...els];
    const intersectionObserver = new IntersectionObserver(
      (entries, _observer) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            if (visibleElements.indexOf(entry.target) === -1) {
              visibleElements.push(entry.target);
            }
          } else {
            visibleElements = visibleElements.filter((visibleEntry) => {
              return visibleEntry !== entry;
            });
          }
        });

        if (!hasObserved) {
          hideOverlappedSidebars();
        }
        hasObserved = true;
      },
      {}
    );
    els.forEach((el) => {
      intersectionObserver.observe(el);
    });

    return {
      getVisibleEntries: () => {
        return visibleElements;
      },
    };
  };

  const rightElementObserver = visibleItemObserver(rightSideConflictEls);
  const leftElementObserver = visibleItemObserver(leftSideConflictEls);

  const hideOverlappedSidebars = () => {
    marginScrollVisibility(toRegions(rightElementObserver.getVisibleEntries()));
    sidebarScrollVisiblity(toRegions(leftElementObserver.getVisibleEntries()));
    if (tocLeftScrollVisibility) {
      tocLeftScrollVisibility(
        toRegions(leftElementObserver.getVisibleEntries())
      );
    }
  };

  window.quartoToggleReader = () => {
    // Applies a slow class (or removes it)
    // to update the transition speed
    const slowTransition = (slow) => {
      const manageTransition = (id, slow) => {
        const el = document.getElementById(id);
        if (el) {
          if (slow) {
            el.classList.add("slow");
          } else {
            el.classList.remove("slow");
          }
        }
      };

      manageTransition("TOC", slow);
      manageTransition("quarto-sidebar", slow);
    };
    const readerMode = !isReaderMode();
    setReaderModeValue(readerMode);

    // If we're entering reader mode, slow the transition
    if (readerMode) {
      slowTransition(readerMode);
    }
    highlightReaderToggle(readerMode);
    hideOverlappedSidebars();

    // If we're exiting reader mode, restore the non-slow transition
    if (!readerMode) {
      slowTransition(!readerMode);
    }
  };

  const highlightReaderToggle = (readerMode) => {
    const els = document.querySelectorAll(".quarto-reader-toggle");
    if (els) {
      els.forEach((el) => {
        if (readerMode) {
          el.classList.add("reader");
        } else {
          el.classList.remove("reader");
        }
      });
    }
  };

  const setReaderModeValue = (val) => {
    if (window.location.protocol !== "file:") {
      window.localStorage.setItem("quarto-reader-mode", val);
    } else {
      localReaderMode = val;
    }
  };

  const isReaderMode = () => {
    if (window.location.protocol !== "file:") {
      return window.localStorage.getItem("quarto-reader-mode") === "true";
    } else {
      return localReaderMode;
    }
  };
  let localReaderMode = null;

  const tocOpenDepthStr = tocEl?.getAttribute("data-toc-expanded");
  const tocOpenDepth = tocOpenDepthStr ? Number(tocOpenDepthStr) : 1;

  // Walk the TOC and collapse/expand nodes
  // Nodes are expanded if:
  // - they are top level
  // - they have children that are 'active' links
  // - they are directly below an link that is 'active'
  const walk = (el, depth) => {
    // Tick depth when we enter a UL
    if (el.tagName === "UL") {
      depth = depth + 1;
    }

    // It this is active link
    let isActiveNode = false;
    if (el.tagName === "A" && el.classList.contains("active")) {
      isActiveNode = true;
    }

    // See if there is an active child to this element
    let hasActiveChild = false;
    for (child of el.children) {
      hasActiveChild = walk(child, depth) || hasActiveChild;
    }

    // Process the collapse state if this is an UL
    if (el.tagName === "UL") {
      if (tocOpenDepth === -1 && depth > 1) {
        el.classList.add("collapse");
      } else if (
        depth <= tocOpenDepth ||
        hasActiveChild ||
        prevSiblingIsActiveLink(el)
      ) {
        el.classList.remove("collapse");
      } else {
        el.classList.add("collapse");
      }

      // untick depth when we leave a UL
      depth = depth - 1;
    }
    return hasActiveChild || isActiveNode;
  };

  // walk the TOC and expand / collapse any items that should be shown

  if (tocEl) {
    walk(tocEl, 0);
    updateActiveLink();
  }

  // Throttle the scroll event and walk peridiocally
  window.document.addEventListener(
    "scroll",
    throttle(() => {
      if (tocEl) {
        updateActiveLink();
        walk(tocEl, 0);
      }
      if (!isReaderMode()) {
        hideOverlappedSidebars();
      }
    }, 5)
  );
  window.addEventListener(
    "resize",
    throttle(() => {
      if (!isReaderMode()) {
        hideOverlappedSidebars();
      }
    }, 10)
  );
  hideOverlappedSidebars();
  highlightReaderToggle(isReaderMode());
});

// grouped tabsets
window.addEventListener("pageshow", (_event) => {
  function getTabSettings() {
    const data = localStorage.getItem("quarto-persistent-tabsets-data");
    if (!data) {
      localStorage.setItem("quarto-persistent-tabsets-data", "{}");
      return {};
    }
    if (data) {
      return JSON.parse(data);
    }
  }

  function setTabSettings(data) {
    localStorage.setItem(
      "quarto-persistent-tabsets-data",
      JSON.stringify(data)
    );
  }

  function setTabState(groupName, groupValue) {
    const data = getTabSettings();
    data[groupName] = groupValue;
    setTabSettings(data);
  }

  function toggleTab(tab, active) {
    const tabPanelId = tab.getAttribute("aria-controls");
    const tabPanel = document.getElementById(tabPanelId);
    if (active) {
      tab.classList.add("active");
      tabPanel.classList.add("active");
    } else {
      tab.classList.remove("active");
      tabPanel.classList.remove("active");
    }
  }

  function toggleAll(selectedGroup, selectorsToSync) {
    for (const [thisGroup, tabs] of Object.entries(selectorsToSync)) {
      const active = selectedGroup === thisGroup;
      for (const tab of tabs) {
        toggleTab(tab, active);
      }
    }
  }

  function findSelectorsToSyncByLanguage() {
    const result = {};
    const tabs = Array.from(
      document.querySelectorAll(`div[data-group] a[id^='tabset-']`)
    );
    for (const item of tabs) {
      const div = item.parentElement.parentElement.parentElement;
      const group = div.getAttribute("data-group");
      if (!result[group]) {
        result[group] = {};
      }
      const selectorsToSync = result[group];
      const value = item.innerHTML;
      if (!selectorsToSync[value]) {
        selectorsToSync[value] = [];
      }
      selectorsToSync[value].push(item);
    }
    return result;
  }

  function setupSelectorSync() {
    const selectorsToSync = findSelectorsToSyncByLanguage();
    Object.entries(selectorsToSync).forEach(([group, tabSetsByValue]) => {
      Object.entries(tabSetsByValue).forEach(([value, items]) => {
        items.forEach((item) => {
          item.addEventListener("click", (_event) => {
            setTabState(group, value);
            toggleAll(value, selectorsToSync[group]);
          });
        });
      });
    });
    return selectorsToSync;
  }

  const selectorsToSync = setupSelectorSync();
  for (const [group, selectedName] of Object.entries(getTabSettings())) {
    const selectors = selectorsToSync[group];
    // it's possible that stale state gives us empty selections, so we explicitly check here.
    if (selectors) {
      toggleAll(selectedName, selectors);
    }
  }
});

function throttle(func, wait) {
  let waiting = false;
  return function () {
    if (!waiting) {
      func.apply(this, arguments);
      waiting = true;
      setTimeout(function () {
        waiting = false;
      }, wait);
    }
  };
}

function nexttick(func) {
  return setTimeout(func, 0);
}