1 /* global addClass, hasClass, removeClass, onEach */
4 // Scroll code block to put the given code location in the middle of the viewer
5 function scrollToLoc(elt, loc) {
6 var wrapper = elt.querySelector(".code-wrapper");
7 var halfHeight = wrapper.offsetHeight / 2;
8 var lines = elt.querySelector('.line-numbers');
9 var offsetMid = (lines.children[loc[0]].offsetTop
10 + lines.children[loc[1]].offsetTop) / 2;
11 var scrollOffset = offsetMid - halfHeight;
12 lines.scrollTo(0, scrollOffset);
13 elt.querySelector(".rust").scrollTo(0, scrollOffset);
16 function updateScrapedExample(example) {
17 var locs = JSON.parse(example.attributes.getNamedItem("data-locs").textContent);
19 var highlights = example.querySelectorAll('.highlight');
20 var link = example.querySelector('.scraped-example-title a');
22 if (locs.length > 1) {
23 // Toggle through list of examples in a given file
24 var onChangeLoc = function(changeIndex) {
25 removeClass(highlights[locIndex], 'focus');
27 scrollToLoc(example, locs[locIndex][0]);
28 addClass(highlights[locIndex], 'focus');
30 var url = locs[locIndex][1];
31 var title = locs[locIndex][2];
34 link.innerHTML = title;
37 example.querySelector('.prev')
38 .addEventListener('click', function() {
39 onChangeLoc(function() {
40 locIndex = (locIndex - 1 + locs.length) % locs.length;
44 example.querySelector('.next')
45 .addEventListener('click', function() {
46 onChangeLoc(function() {
47 locIndex = (locIndex + 1) % locs.length;
52 var expandButton = example.querySelector('.expand');
54 expandButton.addEventListener('click', function () {
55 if (hasClass(example, "expanded")) {
56 removeClass(example, "expanded");
57 scrollToLoc(example, locs[0][0]);
59 addClass(example, "expanded");
64 // Start with the first example in view
65 scrollToLoc(example, locs[0][0]);
68 var firstExamples = document.querySelectorAll('.scraped-example-list > .scraped-example');
69 onEach(firstExamples, updateScrapedExample);
70 onEach(document.querySelectorAll('.more-examples-toggle'), function(toggle) {
71 // Allow users to click the left border of the <details> section to close it,
72 // since the section can be large and finding the [+] button is annoying.
73 toggle.querySelector('.toggle-line').addEventListener('click', function() {
77 var moreExamples = toggle.querySelectorAll('.scraped-example');
78 toggle.querySelector('summary').addEventListener('click', function() {
79 // Wrapping in setTimeout ensures the update happens after the elements are actually
80 // visible. This is necessary since updateScrapedExample calls scrollToLoc which
81 // depends on offsetHeight, a property that requires an element to be visible to
83 setTimeout(function() { onEach(moreExamples, updateScrapedExample); });