article.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. // Documentation licensed under CC BY 4.0
  2. // License available at https://creativecommons.org/licenses/by/4.0/
  3. // TODO(user): Bring in Closure library and compiler.
  4. var closure = window.closure || {};
  5. closure.docs = closure.docs || {};
  6. /** @define {string} */
  7. closure.docs.LOCATION = String(window.location);
  8. /**
  9. * Returns a value from the global `_JEKYLL_DATA` object, which contains the
  10. * 'page' and 'site' data from Jekyll. This allows to configure the JS
  11. * behavior from the frontmatter. It is effectively `goog.getObjectByName`,
  12. * except we're not currently depending on Closure.
  13. * @param {string} param
  14. * @return {*} Result, or undefined.
  15. */
  16. closure.docs.get = function(param) {
  17. var data = window['_JEKYLL_DATA'];
  18. return data && data[param];
  19. };
  20. /**
  21. * Applies the given function to each element.
  22. * @param {string} selector A query selector.
  23. * @param {function(!Element)} func
  24. */
  25. closure.docs.forEachElement = function(selector, func) {
  26. var elements = document.querySelectorAll(selector);
  27. for (var i = 0, length = elements.length; i < length; i++) {
  28. func(elements[i]);
  29. }
  30. };
  31. /**
  32. * Runs a callback on each heading.
  33. * @param {function(!Element, number)} func
  34. */
  35. closure.docs.forEachHeading = function(func) {
  36. closure.docs.forEachElement(
  37. 'article > h1, article > h2, article > h3, ' +
  38. 'article > h4, article > h5, article > h6',
  39. function(heading) {
  40. var match = /^h(\d)$/i.exec(heading.tagName);
  41. func(heading, Number(match[1]));
  42. });
  43. };
  44. /**
  45. * Adds a scroll listener to the document.
  46. * The listener adds a "scrolled" and a "down" class to the body element
  47. * to indicate (respectively) whether the page is scrolled at all, and
  48. * whether the last scroll was down.
  49. */
  50. closure.docs.addScrollListener = function() {
  51. // Add a scroll listener to handle body.scrolled and body.down
  52. var last = void 0;
  53. // Height difference between the scrolled and unscrolled header bars
  54. var threshold = 140;
  55. document.addEventListener('scroll', function() {
  56. var top = document.body.scrollTop;
  57. document.body.classList.toggle('scrolled', top > threshold);
  58. document.body.classList.toggle('down', top > last);
  59. last = top;
  60. });
  61. };
  62. /**
  63. * Add a listener so that clicking on #-only links calls scrollToHash
  64. * instead of the browser default.
  65. */
  66. closure.docs.interceptLinkClicks = function() {
  67. /**
  68. * Scrolls to the window's current hash. Note: this is required
  69. * because of the {position: fixed} banner at the top, which will
  70. * cover the heading if we let the browser scroll on its own.
  71. * Instead, we add a delta to ensure that the heading ends up
  72. * below the banner.
  73. */
  74. function scrollToHash() {
  75. var hash = window.location.hash.substring(1);
  76. if (hash) {
  77. var el = document.getElementById(hash);
  78. var delta = document.body.classList.contains('scrolled') ? 72 : 128;
  79. document.body.scrollTop = el.offsetTop - delta;
  80. }
  81. }
  82. document.addEventListener('click', function(e) {
  83. if (!e.target || e.target.tagName != 'A') return;
  84. var href = e.target.getAttribute('href');
  85. if (href && href[0] == '#') {
  86. window.location.hash = href;
  87. requestAnimationFrame(scrollToHash);
  88. e.preventDefault();
  89. }
  90. });
  91. // Also scroll to hash on initial page load.
  92. requestAnimationFrame(scrollToHash);
  93. };
  94. /**
  95. * Removes the first <h1> header in the article and writes it into
  96. * the header and title. This should be done before building the
  97. * TOC so that the title doesn't show up as an entry.
  98. */
  99. closure.docs.findTitle = function() {
  100. // Note: we need to skip the first (#top_of_page) element.
  101. var h1 = document.querySelectorAll('article > h1')[1];
  102. if (h1) {
  103. var pageTitle = h1.textContent;
  104. h1.remove();
  105. var title = document.querySelector('title');
  106. if (!title.textContent) title.textContent = pageTitle;
  107. var heading = document.querySelector('h1#top_of_page');
  108. if (heading && !heading.textContent) heading.textContent = pageTitle;
  109. }
  110. };
  111. /**
  112. * Iterates over heading elements to add/correct numbers.
  113. * Anything that looks like a number will be adjusted.
  114. * Specifically, one can simply write "### 1.1" for all
  115. * headings and this function will fill in the correct
  116. * number. Also assigns IDs if one isn't already given.
  117. */
  118. closure.docs.autoNumber = function() {
  119. var min = Number(closure.docs.get('page.toc.min') || 2);
  120. var nums = [];
  121. var ids = {};
  122. closure.docs.forEachHeading(function(heading, level) {
  123. if (level < min) return;
  124. // Don't do any numbering unless the heading starts with a digit,
  125. // though we do still need to pop numbers off before incrementing.
  126. while (nums.length > level - min + 1) {
  127. nums.pop();
  128. }
  129. if (!/^\d/.test(heading.textContent)) return;
  130. while (nums.length < level - min + 1) {
  131. nums.push(0);
  132. }
  133. nums[nums.length - 1]++;
  134. // Auto-generate an ID if necessary.
  135. if (!heading.id) {
  136. var base = '_' +
  137. heading.textContent.toLowerCase()
  138. .replace(/[^a-z]+/g, '-')
  139. .replace(/^-|-$/g, '');
  140. var suffix = '';
  141. while (base + suffix in ids) {
  142. suffix++;
  143. }
  144. heading.id = base + suffix;
  145. ids[base + suffix] = true;
  146. }
  147. // Correct the number.
  148. heading.textContent =
  149. heading.textContent.replace(/^\d+(\.\d+)*/, nums.join('.'));
  150. });
  151. };
  152. /**
  153. * Replaces the text content of intra-document links to match the
  154. * linked section's heading. This is necessary when auto-numbering
  155. * is used in order to get the right number in the text. It is
  156. * triggered by links whose text is exactly two or more question marks.
  157. */
  158. closure.docs.fixLinkText = function() {
  159. closure.docs.forEachElement('a', function(link) {
  160. var href = link.getAttribute('href');
  161. if (!/^#/.test(href) || !/^\?\?+$/.test(link.textContent)) return;
  162. var heading = document.getElementById(href.substring(1));
  163. if (heading) link.textContent = heading.textContent;
  164. // TODO(user): allow including/excluding the number?
  165. });
  166. };
  167. /**
  168. * Builds the table of contents. This should run after
  169. * autoNumber so that the correct text makes it in.
  170. */
  171. closure.docs.buildToc = function() {
  172. // Read a few page-level parameters to customize.
  173. var min = Number(closure.docs.get('page.toc.min') || 2);
  174. var max = Number(closure.docs.get('page.toc.max') || 3);
  175. // TODO(user): allow further customization of numbering?
  176. var stack = [];
  177. closure.docs.forEachHeading(function(heading, level) {
  178. if (level < min || level > max) return;
  179. var depth = level - min + 1;
  180. while (stack.length > depth) {
  181. stack.pop();
  182. }
  183. while (stack.length < depth) {
  184. var list = document.createElement('ul');
  185. // Add to the most recent 'li' item (unless this is the first entry).
  186. var prev = stack[stack.length - 1];
  187. if (prev) {
  188. if (!prev.lastChild) prev.appendChild(document.createElement('li'));
  189. prev.lastChild.appendChild(list);
  190. }
  191. stack.push(list);
  192. }
  193. var item = document.createElement('li');
  194. stack[stack.length - 1].appendChild(item);
  195. var link = document.createElement('a');
  196. item.appendChild(link);
  197. link.href = '#' + heading.id;
  198. link.textContent = heading.textContent;
  199. });
  200. // Finally add the toc to our toc elements.
  201. var toc = stack[0];
  202. closure.docs.forEachElement('nav.toc ul', function(ul) {
  203. if (toc && toc.innerHTML) {
  204. ul.innerHTML += toc.innerHTML;
  205. } else {
  206. ul.parentElement.remove(); // don't bother with TOC if it's empty
  207. }
  208. });
  209. };
  210. /**
  211. * Fix some syntax highlighting. Rouge does a poor job highlighting JS.
  212. * It marks every identifier as 'nx' regardless of how it is used, whereas
  213. * GitHub-flavored markdown highlights the final identifier in a qualified
  214. * function name as a function. This function finds any 'nx' identifier
  215. * that is followed by an open-paren and changes it to 'nf'.
  216. */
  217. closure.docs.fixSyntaxHighlighting = function() {
  218. closure.docs.forEachElement('.highlight .nx+.p', function(p) {
  219. if (p.textContent[0] == '(') p.previousElementSibling.className = 'nf';
  220. });
  221. };
  222. /**
  223. * Highlights callouts. A callout is a paragraph that begins with
  224. * 'NOTE:' or 'TIP:' or 'WARNING:' (or several others). These are
  225. * highlighted by adding the 'callout-*' to the classlist, where
  226. * '*' is 'note', 'tip', 'warning', etc.
  227. */
  228. closure.docs.highlightCallouts = function() {
  229. closure.docs.forEachElement('p', function(p) {
  230. var match = /^([A-Za-z]+):/.exec(p.textContent);
  231. if (match) p.classList.add('callout-' + match[1].toLowerCase());
  232. });
  233. };
  234. /**
  235. * Sets the URL on the edit link.
  236. */
  237. closure.docs.setEditLink = function() {
  238. var link = document.querySelector('a.edit');
  239. var match =
  240. /\/\/([^.]+).github.io\/([^/]+)\/(.*)$/.exec(closure.docs.LOCATION);
  241. if (!match || !link) return;
  242. link.href = [
  243. 'https://github.com', match[1], match[2], 'edit/master/doc',
  244. match[3] + '.md'
  245. ].join('/');
  246. };
  247. /**
  248. * Marks the current page and section as 'active' in nav menus.
  249. */
  250. closure.docs.markActiveNav = function() {
  251. // Absolutize link
  252. var abs = (function() {
  253. var link = document.createElement('a');
  254. return function(rel) {
  255. link.href = rel;
  256. return link.href;
  257. };
  258. })();
  259. // Checks for a prefix, returns everything after it if it exists
  260. var suffix = function(prefix, string) {
  261. return string.substring(0, prefix.length) == prefix ?
  262. string.substring(prefix.length) :
  263. '';
  264. };
  265. // Figure out the current page/section.
  266. var location = closure.docs.LOCATION;
  267. var page = location.replace(/\.(?:md|html)?/, '');
  268. var section = location.substring(0, location.lastIndexOf('/'));
  269. // If section was overridden in the page frontmatter, use that instead.
  270. var sectionParameter = closure.docs.get('page.section');
  271. if (sectionParameter != null) {
  272. var root = closure.docs.get('site.baseurl;') || '/';
  273. if (root.length > 1 && root[root.length - 1] == '/') {
  274. root = root.substring(0, root.length - 1);
  275. }
  276. section = abs(root + '/' + sectionParameter.replace(/^\/|\/$/g, ''));
  277. }
  278. // Set links active if we're currently visiting them.
  279. closure.docs.forEachElement('header nav a', function(a) {
  280. if (/^\/[^/]*$/.test(suffix(section, a.href))) {
  281. a.classList.add('active');
  282. }
  283. });
  284. closure.docs.forEachElement('nav.side a', function(a) {
  285. if (/^(\.html|\.md)?$/.test(suffix(page, a.href))) {
  286. a.classList.add('active');
  287. }
  288. });
  289. };
  290. /**
  291. * Kicks off Google Analytics. This is just a pretty-printed
  292. * version of the standard installation code.
  293. * @suppress {checkTypes}
  294. */
  295. closure.docs.startAnalytics = function() {
  296. var productKey = closure.docs.get('page.ga');
  297. if (!productKey) return;
  298. (function(i, s, o, g, r, a, m) {
  299. i['GoogleAnalyticsObject'] = r;
  300. i[r] = i[r] || function() {
  301. (i[r].q = i[r].q || []).push(arguments);
  302. }, i[r].l = 1 * new Date();
  303. a = s.createElement(o), m = s.getElementsByTagName(o)[0];
  304. a.async = 1;
  305. a.src = g;
  306. m.parentNode.insertBefore(a, m);
  307. })(window, document, 'script', '//www.google-analytics.com/analytics.js',
  308. 'ga');
  309. window['ga']('create', productKey, 'auto');
  310. window['ga']('send', 'pageview');
  311. };
  312. /**
  313. * Initialize everything.
  314. */
  315. closure.docs.initialize = function() {
  316. closure.docs.findTitle();
  317. closure.docs.autoNumber();
  318. closure.docs.buildToc();
  319. closure.docs.fixLinkText();
  320. closure.docs.fixSyntaxHighlighting();
  321. closure.docs.highlightCallouts();
  322. closure.docs.markActiveNav();
  323. closure.docs.addScrollListener();
  324. closure.docs.interceptLinkClicks();
  325. closure.docs.setEditLink();
  326. closure.docs.startAnalytics();
  327. };