learn.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. // Scrollbar Width function
  2. function getScrollBarWidth() {
  3. var inner = document.createElement('p');
  4. inner.style.width = "100%";
  5. inner.style.height = "200px";
  6. var outer = document.createElement('div');
  7. outer.style.position = "absolute";
  8. outer.style.top = "0px";
  9. outer.style.left = "0px";
  10. outer.style.visibility = "hidden";
  11. outer.style.width = "200px";
  12. outer.style.height = "150px";
  13. outer.style.overflow = "hidden";
  14. outer.appendChild(inner);
  15. document.body.appendChild(outer);
  16. var w1 = inner.offsetWidth;
  17. outer.style.overflow = 'scroll';
  18. var w2 = inner.offsetWidth;
  19. if (w1 == w2) w2 = outer.clientWidth;
  20. document.body.removeChild(outer);
  21. return (w1 - w2);
  22. };
  23. var topics = {};
  24. var hOP = topics.hasOwnProperty;
  25. var huePubSub = {
  26. subscribe: function(topic, listener, app) {
  27. if (!hOP.call(topics, topic)) {
  28. topics[topic] = [];
  29. }
  30. var index =
  31. topics[topic].push({
  32. listener: listener,
  33. app: app,
  34. status: 'running'
  35. }) - 1;
  36. return {
  37. remove: function() {
  38. delete topics[topic][index];
  39. }
  40. };
  41. },
  42. removeAll: function(topic) {
  43. topics[topic] = [];
  44. },
  45. subscribeOnce: function(topic, listener, app) {
  46. var ephemeral = this.subscribe(
  47. topic,
  48. function() {
  49. listener.apply(listener, arguments);
  50. ephemeral.remove();
  51. },
  52. app
  53. );
  54. },
  55. publish: function(topic, info) {
  56. if (!hOP.call(topics, topic)) {
  57. return;
  58. }
  59. topics[topic].forEach(item => {
  60. if (item.status === 'running') {
  61. item.listener(info);
  62. }
  63. });
  64. },
  65. getTopics: function() {
  66. return topics;
  67. },
  68. pauseAppSubscribers: function(app) {
  69. if (app) {
  70. Object.keys(topics).forEach(topicName => {
  71. topics[topicName].forEach(topic => {
  72. if (
  73. typeof topic.app !== 'undefined' &&
  74. topic.app !== null &&
  75. (topic.app === app || topic.app.split('-')[0] === app)
  76. ) {
  77. topic.status = 'paused';
  78. }
  79. });
  80. });
  81. }
  82. },
  83. resumeAppSubscribers: function(app) {
  84. if (app) {
  85. Object.keys(topics).forEach(topicName => {
  86. topics[topicName].forEach(topic => {
  87. if (
  88. typeof topic.app !== 'undefined' &&
  89. topic.app !== null &&
  90. (topic.app === app || topic.app.split('-')[0] === app)
  91. ) {
  92. topic.status = 'running';
  93. }
  94. });
  95. });
  96. }
  97. },
  98. clearAppSubscribers: function(app) {
  99. if (app) {
  100. Object.keys(topics).forEach(topicName => {
  101. topics[topicName] = topics[topicName].filter(obj => {
  102. return obj.app !== app;
  103. });
  104. });
  105. }
  106. }
  107. };
  108. (function ($, window, document, undefined) {
  109. var pluginName = "jHueScrollUp",
  110. defaults = {
  111. threshold: 100, // it displays it after 100 px of scroll
  112. scrollLeft: false
  113. };
  114. function Plugin(element, options) {
  115. this.element = element;
  116. this.options = $.extend({}, defaults, options);
  117. this._defaults = defaults;
  118. this._name = pluginName;
  119. if ($(element).attr('jHueScrollified') !== 'true') {
  120. this.setupScrollUp();
  121. }
  122. if (this.options.scrollLeft) {
  123. $(element).jHueScrollLeft(this.options.threshold);
  124. }
  125. }
  126. Plugin.prototype.setOptions = function (options) {
  127. this.options = $.extend({}, defaults, options);
  128. };
  129. Plugin.prototype.setupScrollUp = function () {
  130. var _this = this,
  131. link = null;
  132. if ($("#jHueScrollUpAnchor").length > 0) { // just one scroll up per page
  133. link = $("#jHueScrollUpAnchor");
  134. $(document).off("click", "#jHueScrollUpAnchor");
  135. } else {
  136. link = $("<a/>").attr("id", "jHueScrollUpAnchor").addClass("hueAnchor hueAnchorScroller").attr("href", "javascript:void(0)").html("<i class='fa fa-fw fa-chevron-up'></i>").appendTo('#body-inner');
  137. }
  138. $(_this.element).attr("jHueScrollified", "true");
  139. if ($(_this.element).is("body")) {
  140. setScrollBehavior($(window), $("body, html"));
  141. } else {
  142. setScrollBehavior($(_this.element), $(_this.element));
  143. }
  144. huePubSub.subscribe('reposition.scroll.anchor.up', function(){
  145. $('#jHueScrollUpAnchor').css('right', '70px');
  146. if (!$(_this.element).is('body') && $(_this.element).is(':visible')) {
  147. var adjustRight = $(window).width() - ($(_this.element).width() + $(_this.element).offset().left);
  148. if (adjustRight > 0) {
  149. $('#jHueScrollUpAnchor').css('right', adjustRight + 'px');
  150. }
  151. }
  152. });
  153. function setScrollBehavior(scrolled, scrollable) {
  154. scrolled.scroll(function () {
  155. if (scrolled.scrollTop() > _this.options.threshold) {
  156. if (link.is(":hidden")) {
  157. huePubSub.publish('reposition.scroll.anchor.up');
  158. link.fadeIn(200, function(){
  159. huePubSub.publish('reposition.scroll.anchor.up');
  160. });
  161. }
  162. if ($(_this.element).data("lastScrollTop") == null || $(_this.element).data("lastScrollTop") < scrolled.scrollTop()) {
  163. $("#jHueScrollUpAnchor").data("caller", scrollable);
  164. }
  165. $(_this.element).data("lastScrollTop", scrolled.scrollTop());
  166. }
  167. else {
  168. checkForAllScrolls();
  169. }
  170. });
  171. window.setTimeout(function() {
  172. huePubSub.publish('reposition.scroll.anchor.up');
  173. }, 0);
  174. }
  175. function checkForAllScrolls() {
  176. var _allOk = true;
  177. $(document).find("[jHueScrollified='true']").each(function (cnt, item) {
  178. if ($(item).is("body")) {
  179. if ($(window).scrollTop() > _this.options.threshold) {
  180. _allOk = false;
  181. $("#jHueScrollUpAnchor").data("caller", $("body, html"));
  182. }
  183. }
  184. else {
  185. if ($(item).scrollTop() > _this.options.threshold) {
  186. _allOk = false;
  187. $("#jHueScrollUpAnchor").data("caller", $(item));
  188. }
  189. }
  190. });
  191. if (_allOk) {
  192. link.fadeOut(200);
  193. $("#jHueScrollUpAnchor").data("caller", null);
  194. }
  195. }
  196. $(document).on("click", "#jHueScrollUpAnchor", function (event) {
  197. if ($("#jHueScrollUpAnchor").data("caller") != null) {
  198. $("#jHueScrollUpAnchor").data("caller").scrollTop(0);
  199. if ($(document).find("[jHueScrollified='true']").not($("#jHueScrollUpAnchor").data("caller")).is("body") && $(window).scrollTop() > _this.options.threshold) {
  200. $("#jHueScrollUpAnchor").data("caller", $("body, html"));
  201. } else {
  202. checkForAllScrolls();
  203. }
  204. }
  205. return false;
  206. });
  207. };
  208. $.fn[pluginName] = function (options) {
  209. return this.each(function () {
  210. $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
  211. });
  212. }
  213. $[pluginName] = function (options) {
  214. new Plugin($("body"), options);
  215. };
  216. })(jQuery, window, document);
  217. $(document).jHueScrollUp();
  218. function setMenuHeight() {
  219. $('#sidebar .highlightable').height($('#sidebar').innerHeight() - $('#header-wrapper').height() - 40);
  220. $('#sidebar .highlightable').perfectScrollbar('update');
  221. }
  222. function fallbackMessage(action) {
  223. var actionMsg = '';
  224. var actionKey = (action === 'cut' ? 'X' : 'C');
  225. if (/iPhone|iPad/i.test(navigator.userAgent)) {
  226. actionMsg = 'No support :(';
  227. }
  228. else if (/Mac/i.test(navigator.userAgent)) {
  229. actionMsg = 'Press ⌘-' + actionKey + ' to ' + action;
  230. }
  231. else {
  232. actionMsg = 'Press Ctrl-' + actionKey + ' to ' + action;
  233. }
  234. return actionMsg;
  235. }
  236. // for the window resize
  237. $(window).resize(function() {
  238. setMenuHeight();
  239. });
  240. // debouncing function from John Hann
  241. // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  242. (function($, sr) {
  243. var debounce = function(func, threshold, execAsap) {
  244. var timeout;
  245. return function debounced() {
  246. var obj = this, args = arguments;
  247. function delayed() {
  248. if (!execAsap)
  249. func.apply(obj, args);
  250. timeout = null;
  251. };
  252. if (timeout)
  253. clearTimeout(timeout);
  254. else if (execAsap)
  255. func.apply(obj, args);
  256. timeout = setTimeout(delayed, threshold || 100);
  257. };
  258. }
  259. // smartresize
  260. jQuery.fn[sr] = function(fn) { return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
  261. })(jQuery, 'smartresize');
  262. jQuery(document).ready(function() {
  263. jQuery('#sidebar .category-icon').on('click', function() {
  264. $( this ).toggleClass("fa-angle-down fa-angle-right") ;
  265. $( this ).parent().parent().children('ul').toggle() ;
  266. return false;
  267. });
  268. var sidebarStatus = searchStatus = 'open';
  269. $('#sidebar .highlightable').perfectScrollbar();
  270. setMenuHeight();
  271. jQuery('#overlay').on('click', function() {
  272. jQuery(document.body).toggleClass('sidebar-hidden');
  273. sidebarStatus = (jQuery(document.body).hasClass('sidebar-hidden') ? 'closed' : 'open');
  274. return false;
  275. });
  276. jQuery('[data-sidebar-toggle]').on('click', function() {
  277. jQuery(document.body).toggleClass('sidebar-hidden');
  278. sidebarStatus = (jQuery(document.body).hasClass('sidebar-hidden') ? 'closed' : 'open');
  279. return false;
  280. });
  281. jQuery('[data-clear-history-toggle]').on('click', function() {
  282. sessionStorage.clear();
  283. location.reload();
  284. return false;
  285. });
  286. jQuery('[data-search-toggle]').on('click', function() {
  287. if (sidebarStatus == 'closed') {
  288. jQuery('[data-sidebar-toggle]').trigger('click');
  289. jQuery(document.body).removeClass('searchbox-hidden');
  290. searchStatus = 'open';
  291. return false;
  292. }
  293. jQuery(document.body).toggleClass('searchbox-hidden');
  294. searchStatus = (jQuery(document.body).hasClass('searchbox-hidden') ? 'closed' : 'open');
  295. return false;
  296. });
  297. var ajax;
  298. jQuery('[data-search-input]').on('input', function() {
  299. var input = jQuery(this),
  300. value = input.val(),
  301. items = jQuery('[data-nav-id]');
  302. items.removeClass('search-match');
  303. if (!value.length) {
  304. $('ul.topics').removeClass('searched');
  305. items.css('display', 'block');
  306. sessionStorage.removeItem('search-value');
  307. $(".highlightable").unhighlight({ element: 'mark' })
  308. return;
  309. }
  310. sessionStorage.setItem('search-value', value);
  311. $(".highlightable").unhighlight({ element: 'mark' }).highlight(value, { element: 'mark' });
  312. if (ajax && ajax.abort) ajax.abort();
  313. jQuery('[data-search-clear]').on('click', function() {
  314. jQuery('[data-search-input]').val('').trigger('input');
  315. sessionStorage.removeItem('search-input');
  316. $(".highlightable").unhighlight({ element: 'mark' })
  317. });
  318. });
  319. $.expr[":"].contains = $.expr.createPseudo(function(arg) {
  320. return function( elem ) {
  321. return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
  322. };
  323. });
  324. if (sessionStorage.getItem('search-value')) {
  325. var searchValue = sessionStorage.getItem('search-value')
  326. $(document.body).removeClass('searchbox-hidden');
  327. $('[data-search-input]').val(searchValue);
  328. $('[data-search-input]').trigger('input');
  329. var searchedElem = $('#body-inner').find(':contains(' + searchValue + ')').get(0);
  330. if (searchedElem) {
  331. searchedElem.scrollIntoView(true);
  332. var scrolledY = window.scrollY;
  333. if(scrolledY){
  334. window.scroll(0, scrolledY - 125);
  335. }
  336. }
  337. }
  338. // clipboard
  339. var clipInit = false;
  340. $('code').each(function() {
  341. var code = $(this),
  342. text = code.text();
  343. if (text.length > 5) {
  344. if (!clipInit) {
  345. var text, clip = new Clipboard('.copy-to-clipboard', {
  346. text: function(trigger) {
  347. text = $(trigger).prev('code').text();
  348. return text.replace(/^\$\s/gm, '');
  349. }
  350. });
  351. var inPre;
  352. clip.on('success', function(e) {
  353. e.clearSelection();
  354. inPre = $(e.trigger).parent().prop('tagName') == 'PRE';
  355. $(e.trigger).attr('aria-label', 'Copied to clipboard!').addClass('tooltipped tooltipped-' + (inPre ? 'w' : 's'));
  356. });
  357. clip.on('error', function(e) {
  358. inPre = $(e.trigger).parent().prop('tagName') == 'PRE';
  359. $(e.trigger).attr('aria-label', fallbackMessage(e.action)).addClass('tooltipped tooltipped-' + (inPre ? 'w' : 's'));
  360. $(document).one('copy', function(){
  361. $(e.trigger).attr('aria-label', 'Copied to clipboard!').addClass('tooltipped tooltipped-' + (inPre ? 'w' : 's'));
  362. });
  363. });
  364. clipInit = true;
  365. }
  366. code.after('<span class="copy-to-clipboard" title="Copy to clipboard" />');
  367. code.next('.copy-to-clipboard').on('mouseleave', function() {
  368. $(this).attr('aria-label', null).removeClass('tooltipped tooltipped-s tooltipped-w');
  369. });
  370. }
  371. });
  372. // allow keyboard control for prev/next links
  373. jQuery(function() {
  374. jQuery('.nav-prev').click(function(){
  375. location.href = jQuery(this).attr('href');
  376. });
  377. jQuery('.nav-next').click(function() {
  378. location.href = jQuery(this).attr('href');
  379. });
  380. });
  381. jQuery('input, textarea').keydown(function (e) {
  382. // left and right arrow keys
  383. if (e.which == '37' || e.which == '39') {
  384. e.stopPropagation();
  385. }
  386. });
  387. jQuery(document).keydown(function(e) {
  388. // prev links - left arrow key
  389. if(e.which == '37') {
  390. jQuery('.nav.nav-prev').click();
  391. }
  392. // next links - right arrow key
  393. if(e.which == '39') {
  394. jQuery('.nav.nav-next').click();
  395. }
  396. });
  397. $('#top-bar a:not(:has(img)):not(.btn)').addClass('highlight');
  398. $('#body-inner a:not(:has(img)):not(.btn):not(a[rel="footnote"])').addClass('highlight');
  399. var touchsupport = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)
  400. if (!touchsupport){ // browser doesn't support touch
  401. $('#toc-menu').hover(function() {
  402. $('.progress').stop(true, false, true).fadeToggle(100);
  403. });
  404. $('.progress').hover(function() {
  405. $('.progress').stop(true, false, true).fadeToggle(100);
  406. });
  407. }
  408. if (touchsupport){ // browser does support touch
  409. $('#toc-menu').click(function() {
  410. $('.progress').stop(true, false, true).fadeToggle(100);
  411. });
  412. $('.progress').click(function() {
  413. $('.progress').stop(true, false, true).fadeToggle(100);
  414. });
  415. }
  416. /**
  417. * Fix anchor scrolling that hides behind top nav bar
  418. * Courtesy of https://stackoverflow.com/a/13067009/28106
  419. *
  420. * We could use pure css for this if only heading anchors were
  421. * involved, but this works for any anchor, including footnotes
  422. **/
  423. (function (document, history, location) {
  424. var HISTORY_SUPPORT = !!(history && history.pushState);
  425. var anchorScrolls = {
  426. ANCHOR_REGEX: /^#[^ ]+$/,
  427. OFFSET_HEIGHT_PX: 50,
  428. /**
  429. * Establish events, and fix initial scroll position if a hash is provided.
  430. */
  431. init: function () {
  432. this.scrollToCurrent();
  433. $(window).on('hashchange', $.proxy(this, 'scrollToCurrent'));
  434. $('body').on('click', 'a', $.proxy(this, 'delegateAnchors'));
  435. },
  436. /**
  437. * Return the offset amount to deduct from the normal scroll position.
  438. * Modify as appropriate to allow for dynamic calculations
  439. */
  440. getFixedOffset: function () {
  441. return this.OFFSET_HEIGHT_PX;
  442. },
  443. /**
  444. * If the provided href is an anchor which resolves to an element on the
  445. * page, scroll to it.
  446. * @param {String} href
  447. * @return {Boolean} - Was the href an anchor.
  448. */
  449. scrollIfAnchor: function (href, pushToHistory) {
  450. var match, anchorOffset;
  451. if (!this.ANCHOR_REGEX.test(href)) {
  452. return false;
  453. }
  454. match = document.getElementById(href.slice(1));
  455. if (match) {
  456. anchorOffset = $(match).offset().top - this.getFixedOffset();
  457. $('html, body').animate({ scrollTop: anchorOffset });
  458. // Add the state to history as-per normal anchor links
  459. if (HISTORY_SUPPORT && pushToHistory) {
  460. history.pushState({}, document.title, location.pathname + href);
  461. }
  462. }
  463. return !!match;
  464. },
  465. /**
  466. * Attempt to scroll to the current location's hash.
  467. */
  468. scrollToCurrent: function (e) {
  469. if (this.scrollIfAnchor(window.location.hash) && e) {
  470. e.preventDefault();
  471. }
  472. },
  473. /**
  474. * If the click event's target was an anchor, fix the scroll position.
  475. */
  476. delegateAnchors: function (e) {
  477. var elem = e.target;
  478. if (this.scrollIfAnchor(elem.getAttribute('href'), true)) {
  479. e.preventDefault();
  480. }
  481. }
  482. };
  483. $(document).ready($.proxy(anchorScrolls, 'init'));
  484. })(window.document, window.history, window.location);
  485. });
  486. jQuery(window).on('load', function() {
  487. function adjustForScrollbar() {
  488. if ((parseInt(jQuery('#body-inner').height()) + 83) >= jQuery('#body').height()) {
  489. jQuery('.nav.nav-next').css({ 'margin-right': getScrollBarWidth() });
  490. } else {
  491. jQuery('.nav.nav-next').css({ 'margin-right': 0 });
  492. }
  493. }
  494. // adjust sidebar for scrollbar
  495. adjustForScrollbar();
  496. jQuery(window).smartresize(function() {
  497. adjustForScrollbar();
  498. });
  499. // store this page in session
  500. sessionStorage.setItem(jQuery('body').data('url'), 1);
  501. // loop through the sessionStorage and see if something should be marked as visited
  502. for (var url in sessionStorage) {
  503. if (sessionStorage.getItem(url) == 1) jQuery('[data-nav-id="' + url + '"]').addClass('visited');
  504. }
  505. $(".highlightable").highlight(sessionStorage.getItem('search-value'), { element: 'mark' });
  506. });
  507. $(function() {
  508. $('a[rel="lightbox"]').featherlight({
  509. root: 'section#body'
  510. });
  511. });
  512. jQuery.extend({
  513. highlight: function(node, re, nodeName, className) {
  514. if (node.nodeType === 3) {
  515. var match = node.data.match(re);
  516. if (match) {
  517. var highlight = document.createElement(nodeName || 'span');
  518. highlight.className = className || 'highlight';
  519. var wordNode = node.splitText(match.index);
  520. wordNode.splitText(match[0].length);
  521. var wordClone = wordNode.cloneNode(true);
  522. highlight.appendChild(wordClone);
  523. wordNode.parentNode.replaceChild(highlight, wordNode);
  524. return 1; //skip added node in parent
  525. }
  526. } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
  527. !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
  528. !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
  529. for (var i = 0; i < node.childNodes.length; i++) {
  530. i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
  531. }
  532. }
  533. return 0;
  534. }
  535. });
  536. jQuery.fn.unhighlight = function(options) {
  537. var settings = {
  538. className: 'highlight',
  539. element: 'span'
  540. };
  541. jQuery.extend(settings, options);
  542. return this.find(settings.element + "." + settings.className).each(function() {
  543. var parent = this.parentNode;
  544. parent.replaceChild(this.firstChild, this);
  545. parent.normalize();
  546. }).end();
  547. };
  548. jQuery.fn.highlight = function(words, options) {
  549. var settings = {
  550. className: 'highlight',
  551. element: 'span',
  552. caseSensitive: false,
  553. wordsOnly: false
  554. };
  555. jQuery.extend(settings, options);
  556. if (!words) { return; }
  557. if (words.constructor === String) {
  558. words = [words];
  559. }
  560. words = jQuery.grep(words, function(word, i) {
  561. return word != '';
  562. });
  563. words = jQuery.map(words, function(word, i) {
  564. return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  565. });
  566. if (words.length == 0) { return this; }
  567. ;
  568. var flag = settings.caseSensitive ? "" : "i";
  569. var pattern = "(" + words.join("|") + ")";
  570. if (settings.wordsOnly) {
  571. pattern = "\\b" + pattern + "\\b";
  572. }
  573. var re = new RegExp(pattern, flag);
  574. return this.each(function() {
  575. jQuery.highlight(this, re, settings.element, settings.className);
  576. });
  577. };