diff --git a/Gemfile b/Gemfile index 755165be089..1f110835436 100644 --- a/Gemfile +++ b/Gemfile @@ -9,3 +9,4 @@ gem 'redcarpet', '~> 3.2.2' gem 'rake', '~> 10.4.2' gem 'therubyracer', '~> 0.12.1', platforms: :ruby +gem 'nokogiri' diff --git a/Gemfile.lock b/Gemfile.lock index ce2594750e3..a7140494a16 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -78,6 +78,7 @@ GEM rouge (~> 1.0) minitest (5.6.1) multi_json (1.11.0) + nokogiri (1.5.6) padrino-helpers (0.12.5) i18n (~> 0.6, >= 0.6.7) padrino-support (= 0.12.5) @@ -127,6 +128,7 @@ DEPENDENCIES middleman (~> 3.3.10) middleman-gh-pages (~> 0.0.3) middleman-syntax (~> 2.0.0) + nokogiri rake (~> 10.4.2) redcarpet (~> 3.2.2) rouge (~> 1.9.0) diff --git a/config.rb b/config.rb index cd9a362f6ad..ba1a07d3c0e 100644 --- a/config.rb +++ b/config.rb @@ -22,6 +22,74 @@ activate :relative_assets set :relative_links, true +require 'nokogiri' + +helpers do + def body_for(resource) + resource.render(layout: nil) + end + + def doc_for(resource) + html = body_for(resource) + Nokogiri::HTML::DocumentFragment.parse(html) + end + + def create_level_html(heading_id, toc_level, toc_section, tocText, tocInner) + link = '%2%3' + .gsub('%1', heading_id.to_s) + .gsub('%2', tocText) + .gsub('%3', tocInner ? tocInner : ''); + '
  • %3
  • ' + .gsub('%1', toc_level == 1 ? ' tocify-header' : '') + .gsub('%2', toc_section.to_s) + .gsub('%3', link) + .gsub('%4', heading_id.to_s) + .gsub('%5', tocInner.length > 0 ? ' has-subheader' : '') + end + + def table_of_contents(resource) + toc_html = '' + toc_level = 1 + toc_section = 1 + level_html = '' + + doc_for(resource).css('h1').each do |h1| + ct = h1.xpath('count(following-sibling::h1)') + h2s = h1.xpath("following-sibling::h2[count(following-sibling::h1)=#{ct}]") + + level_html = ''; + inner_section = 0; + + h2s.map.each do |h2| + inner_section += 1; + + level_html += create_level_html(h2.attribute('id'), + toc_level + 1, + toc_section + inner_section, + h2.text, + '') + end + if level_html.length > 0 + level_html = ''; + end + + toc_html += create_level_html(id = h1.attribute('id'), + toc_level, + toc_section, + h1.text, + level_html); + + toc_section += 1 + inner_section; + end + + if toc_html.length > 0 + toc_html = ''; + end + + return toc_html + end +end + # Build Configuration configure :build do activate :minify_css diff --git a/source/javascripts/app/es6shim.js b/source/javascripts/app/es6shim.js new file mode 100644 index 00000000000..4eed043221a --- /dev/null +++ b/source/javascripts/app/es6shim.js @@ -0,0 +1,31 @@ +if (!Object.assign) { + Object.defineProperty(Object, 'assign', { + enumerable: false, + configurable: true, + writable: true, + value: function(target, firstSource) { + 'use strict'; + if (target === undefined || target === null) { + throw new TypeError('Cannot convert first argument to object'); + } + + var to = Object(target); + for (var i = 1; i < arguments.length; i++) { + var nextSource = arguments[i]; + if (nextSource === undefined || nextSource === null) { + continue; + } + + var keysArray = Object.keys(Object(nextSource)); + for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { + var nextKey = keysArray[nextIndex]; + var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); + if (desc !== undefined && desc.enumerable) { + to[nextKey] = nextSource[nextKey]; + } + } + } + return to; + } + }); +} diff --git a/source/javascripts/app/toc.js b/source/javascripts/app/toc.js index c88b67f2b70..440644e7a9a 100644 --- a/source/javascripts/app/toc.js +++ b/source/javascripts/app/toc.js @@ -7,21 +7,7 @@ }; var makeToc = function() { - global.toc = $("#toc").tocify({ - selectors: 'h1, h2', - extendPage: false, - theme: 'none', - smoothScroll: false, - showEffectSpeed: 0, - hideEffectSpeed: 180, - ignoreSelector: '.toc-ignore', - highlightOffset: 60, - scrollTo: -1, - scrollHistory: true, - hashGenerator: function (text, element) { - return element.prop('id'); - } - }).data('toc-tocify'); + global.toc = new Tocify($('#toc'), {}); $("#nav-button").click(function() { $(".tocify-wrapper").toggleClass('open'); @@ -37,7 +23,7 @@ // instead of displaying an ugly animation function animate () { setTimeout(function() { - toc.setOption('showEffectSpeed', 180); + // toc.setOption('showEffectSpeed', 180); }, 50); } diff --git a/source/javascripts/app/tocify.js b/source/javascripts/app/tocify.js new file mode 100644 index 00000000000..8d193f90385 --- /dev/null +++ b/source/javascripts/app/tocify.js @@ -0,0 +1,282 @@ +(function (global) { + 'use strict'; + + var focusClass = 'tocify-focus'; + var headerClass = 'tocify-header'; + var subheaderClass = 'tocify-subheader'; + var defaultOptions = { + selectors: 'h1, h2', + highlightOffset: 40, + highlightDefault: true, + highlightOnScroll: true, + history: true, + scrollHistory: true, + showAndHide: true, + showAndHideOnScroll: true, + showEffect: "slideDown", + showEffectSpeed: "medium", + hideEffect: "slideUp", + hideEffectSpeed: "medium", + smoothScroll: false, + scrollTo: -1 + }; + + function Tocify(element, options) { + this.options = Object.assign({}, defaultOptions, options); + this.headings = $(this.options.selectors); + this.element = $(element); + + this.cachedAnchors = []; + this.cachedHeights = {}; + + this._setEventHandlers(); + + var self = this; + $(window).load(function() { + self._setActiveElement(true); + }); + } + + Tocify.prototype._setEventHandlers = function() { + var self = this; + var $window = $(window); + $window.on('resize', function tocifyResize() { + self.calculateHeights(); + }); + + this.element.on("click", "li > a", function tocifyClick(event) { + var hash = $(event.target).parent().attr("data-heading"); + if(self.options.history) { + self._addToHistory(hash); + } + event.preventDefault(); + + // Removes highlighting from all of the list item's + this.element.find("." + focusClass).removeClass(focusClass); + + // Highlights the current list item that was clicked + $(event.target).parent().addClass(focusClass); + + // If the showAndHide option is true + if (this.options.showAndHide) { + var elem = $('li[data-heading="' + hash + '"]'); + + this._triggerShow(elem); + } + + this._scrollTo(hash); + }.bind(this)); + + $window.on("scroll", function tocifyScroll() { + var self = this; + // The zero timeout ensures the following code is run after the scroll events + setTimeout(function() { + if (self.cachedAnchors.length == 0) { + self.calculateHeights(); + } + + var scrollTop = $(window).scrollTop(); + + var closestAnchorIdx = null; + // Determines the index of the closest anchor + self.cachedAnchors.forEach(function(idx) { + if (self.cachedHeights[idx] - scrollTop <= 0) { + closestAnchorIdx = idx; + } + }); + if (closestAnchorIdx === null) { + closestAnchorIdx = self.cachedAnchors[0]; + } + + var elem = $('li[data-heading="' + closestAnchorIdx + '"]'); + + if (self.options.highlightOnScroll && elem.length && !elem.hasClass(focusClass)) { + // Removes highlighting from all of the list item's + self.element.find("." + focusClass).removeClass(focusClass); + + // Highlights the corresponding list item + elem.addClass(focusClass); + } + + if (self.options.scrollHistory) { + self._addToHistory(closestAnchorIdx); + } + + if (self.options.showAndHideOnScroll && self.options.showAndHide) { + self._triggerShow(elem); + } + }, 0); + }.bind(this)); + }; + + Tocify.prototype._addToHistory = function(hash) { + if (hash !== undefined && window.location.hash !== "#" + hash) { + if (history.replaceState) { + history.replaceState({}, "", "#" + hash); + // provide a fallback + } else { + var scrollV = document.body.scrollTop; + var scrollH = document.body.scrollLeft; + location.hash = "#" + hash; + document.body.scrollTop = scrollV; + document.body.scrollLeft = scrollH; + } + } + }; + + Tocify.prototype._scrollTo = function(hash) { + var duration = this.options.smoothScroll || 0, + scrollTo = this.options.scrollTo; + + // Animates the html and body element scrolltops + $("html, body").animate({ + // Sets the jQuery `scrollTop` to the top offset of the HTML div tag that matches the current list item's `data-unique` tag + "scrollTop": ($('#' + hash).offset().top - scrollTo) + "px" + }, { + // Sets the smoothScroll animation time duration to the smoothScrollSpeed option + "duration": duration + }); + }; + + Tocify.prototype._triggerShow = function(elem) { + var subheaderChild = elem.children('.' + subheaderClass); + if (subheaderChild.length) { + // Shows the next sub-header element + this.show(subheaderChild); + } + else if (elem.parent().is('.' + subheaderClass)) { + // Shows the parent sub-header element + this.show(elem.parent()); + } + else if (elem.is('.' + headerClass)) { + this.hide($('.' + subheaderClass)); + } + }; + + Tocify.prototype.show = function(elem) { + if (!elem.is(":visible")) { + //Determines what jQuery effect to use + switch (this.options.showEffect) { + + //Uses `no effect` + case "none": + + elem.show(); + + break; + + //Uses the jQuery `show` special effect + case "show": + + elem.show(this.options.showEffectSpeed); + + break; + + //Uses the jQuery `slideDown` special effect + case "slideDown": + + elem.slideDown(this.options.showEffectSpeed); + + break; + + //Uses the jQuery `fadeIn` special effect + case "fadeIn": + + elem.fadeIn(this.options.showEffectSpeed); + + break; + + //If none of the above options were passed, then a `jQueryUI show effect` is expected + default: + + elem.show(); + + break; + + } + } + + // If the current subheader parent element is a header + if (elem.parent().is('.' + headerClass)) { + // Hides all non-active sub-headers + this.hide($('.' + subheaderClass).not(elem)); + } + + // If the current subheader parent element is not a header + /*else { + // Hides all non-active sub-headers + this.hide($('.' + subheaderClass).not(elem.closest('.' + headerClass).find('.' + subheaderClass).not(elem.siblings()))); + }*/ + }; + + Tocify.prototype.hide = function(elem) { + //Determines what jQuery effect to use + switch (this.options.hideEffect) { + + // Uses `no effect` + case "none": + + elem.hide(); + + break; + + // Uses the jQuery `hide` special effect + case "hide": + + elem.hide(this.options.hideEffectSpeed); + + break; + + // Uses the jQuery `slideUp` special effect + case "slideUp": + + elem.slideUp(this.options.hideEffectSpeed); + + break; + + // Uses the jQuery `fadeOut` special effect + case "fadeOut": + + elem.fadeOut(this.options.hideEffectSpeed); + + break; + + // If none of the above options were passed, then a `jqueryUI hide effect` is expected + default: + + elem.hide(); + + break; + + } + }; + + Tocify.prototype._setActiveElement = function(pageload) { + var hash = window.location.hash.substring(1); + + $('.' + focusClass).removeClass(focusClass); + if (hash.length) { + var menuEntry = $('li[data-heading=' + hash + ']'); + menuEntry.addClass(focusClass); + } else if (pageload && this.options.highlightDefault) { + // Highlights the first TOC item if no other items are highlighted + this.element.find('li').first().addClass(focusClass); + } + }; + + Tocify.prototype.calculateHeights = function() { + this.cachedHeights = {}; + this.cachedAnchors.length = 0; + + for (var i = 0; i < this.headings.length; i++) { + var heading = this.headings[i]; + var idx = heading.id; + var distance = $(heading).offset().top; + + this.cachedHeights[idx] = distance; + this.cachedAnchors.push(idx); + } + }; + + global.Tocify = Tocify; +})(window); diff --git a/source/javascripts/lib/jquery.tocify.js b/source/javascripts/lib/jquery.tocify.js deleted file mode 100644 index f791bf86246..00000000000 --- a/source/javascripts/lib/jquery.tocify.js +++ /dev/null @@ -1,1043 +0,0 @@ -//= require ./jquery_ui -/* jquery Tocify - v1.8.0 - 2013-09-16 -* http://www.gregfranko.com/jquery.tocify.js/ -* Copyright (c) 2013 Greg Franko; Licensed MIT -* Modified lightly by Robert Lord to fix a bug I found, -* and also so it adds ids to headers -* also because I want height caching, since the -* height lookup for h1s and h2s was causing serious -* lag spikes below 30 fps */ - -// Immediately-Invoked Function Expression (IIFE) [Ben Alman Blog Post](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) that calls another IIFE that contains all of the plugin logic. I used this pattern so that anyone viewing this code would not have to scroll to the bottom of the page to view the local parameters that were passed to the main IIFE. -(function(tocify) { - - // ECMAScript 5 Strict Mode: [John Resig Blog Post](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/) - "use strict"; - - // Calls the second IIFE and locally passes in the global jQuery, window, and document objects - tocify(window.jQuery, window, document); - -} - -// Locally passes in `jQuery`, the `window` object, the `document` object, and an `undefined` variable. The `jQuery`, `window` and `document` objects are passed in locally, to improve performance, since javascript first searches for a variable match within the local variables set before searching the global variables set. All of the global variables are also passed in locally to be minifier friendly. `undefined` can be passed in locally, because it is not a reserved word in JavaScript. -(function($, window, document, undefined) { - - // ECMAScript 5 Strict Mode: [John Resig Blog Post](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/) - "use strict"; - - var tocClassName = "tocify", - tocClass = "." + tocClassName, - tocFocusClassName = "tocify-focus", - tocHoverClassName = "tocify-hover", - hideTocClassName = "tocify-hide", - hideTocClass = "." + hideTocClassName, - headerClassName = "tocify-header", - headerClass = "." + headerClassName, - subheaderClassName = "tocify-subheader", - subheaderClass = "." + subheaderClassName, - itemClassName = "tocify-item", - itemClass = "." + itemClassName, - extendPageClassName = "tocify-extend-page", - extendPageClass = "." + extendPageClassName; - - // Calling the jQueryUI Widget Factory Method - $.widget("toc.tocify", { - - //Plugin version - version: "1.8.0", - - // These options will be used as defaults - options: { - - // **context**: Accepts String: Any jQuery selector - // The container element that holds all of the elements used to generate the table of contents - context: "body", - - // **ignoreSelector**: Accepts String: Any jQuery selector - // A selector to any element that would be matched by selectors that you wish to be ignored - ignoreSelector: null, - - // **selectors**: Accepts an Array of Strings: Any jQuery selectors - // The element's used to generate the table of contents. The order is very important since it will determine the table of content's nesting structure - selectors: "h1, h2, h3", - - // **showAndHide**: Accepts a boolean: true or false - // Used to determine if elements should be shown and hidden - showAndHide: true, - - // **showEffect**: Accepts String: "none", "fadeIn", "show", or "slideDown" - // Used to display any of the table of contents nested items - showEffect: "slideDown", - - // **showEffectSpeed**: Accepts Number (milliseconds) or String: "slow", "medium", or "fast" - // The time duration of the show animation - showEffectSpeed: "medium", - - // **hideEffect**: Accepts String: "none", "fadeOut", "hide", or "slideUp" - // Used to hide any of the table of contents nested items - hideEffect: "slideUp", - - // **hideEffectSpeed**: Accepts Number (milliseconds) or String: "slow", "medium", or "fast" - // The time duration of the hide animation - hideEffectSpeed: "medium", - - // **smoothScroll**: Accepts a boolean: true or false - // Determines if a jQuery animation should be used to scroll to specific table of contents items on the page - smoothScroll: true, - - // **smoothScrollSpeed**: Accepts Number (milliseconds) or String: "slow", "medium", or "fast" - // The time duration of the smoothScroll animation - smoothScrollSpeed: "medium", - - // **scrollTo**: Accepts Number (pixels) - // The amount of space between the top of page and the selected table of contents item after the page has been scrolled - scrollTo: 0, - - // **showAndHideOnScroll**: Accepts a boolean: true or false - // Determines if table of contents nested items should be shown and hidden while scrolling - showAndHideOnScroll: true, - - // **highlightOnScroll**: Accepts a boolean: true or false - // Determines if table of contents nested items should be highlighted (set to a different color) while scrolling - highlightOnScroll: true, - - // **highlightOffset**: Accepts a number - // The offset distance in pixels to trigger the next active table of contents item - highlightOffset: 40, - - // **theme**: Accepts a string: "bootstrap", "jqueryui", or "none" - // Determines if Twitter Bootstrap, jQueryUI, or Tocify classes should be added to the table of contents - theme: "bootstrap", - - // **extendPage**: Accepts a boolean: true or false - // If a user scrolls to the bottom of the page and the page is not tall enough to scroll to the last table of contents item, then the page height is increased - extendPage: true, - - // **extendPageOffset**: Accepts a number: pixels - // How close to the bottom of the page a user must scroll before the page is extended - extendPageOffset: 100, - - // **history**: Accepts a boolean: true or false - // Adds a hash to the page url to maintain history - history: true, - - // **scrollHistory**: Accepts a boolean: true or false - // Adds a hash to the page url, to maintain history, when scrolling to a TOC item - scrollHistory: false, - - // **hashGenerator**: How the hash value (the anchor segment of the URL, following the - // # character) will be generated. - // - // "compact" (default) - #CompressesEverythingTogether - // "pretty" - #looks-like-a-nice-url-and-is-easily-readable - // function(text, element){} - Your own hash generation function that accepts the text as an - // argument, and returns the hash value. - hashGenerator: "compact", - - // **highlightDefault**: Accepts a boolean: true or false - // Set's the first TOC item as active if no other TOC item is active. - highlightDefault: true - - }, - - // _Create - // ------- - // Constructs the plugin. Only called once. - _create: function() { - - var self = this; - - self.tocifyWrapper = $('.tocify-wrapper'); - self.extendPageScroll = true; - - // Internal array that keeps track of all TOC items (Helps to recognize if there are duplicate TOC item strings) - self.items = []; - - // Generates the HTML for the dynamic table of contents - self._generateToc(); - - // Caches heights and anchors - self.cachedHeights = [], - self.cachedAnchors = []; - - // Adds CSS classes to the newly generated table of contents HTML - self._addCSSClasses(); - - self.webkit = (function() { - - for(var prop in window) { - - if(prop) { - - if(prop.toLowerCase().indexOf("webkit") !== -1) { - - return true; - - } - - } - - } - - return false; - - }()); - - // Adds jQuery event handlers to the newly generated table of contents - self._setEventHandlers(); - - // Binding to the Window load event to make sure the correct scrollTop is calculated - $(window).load(function() { - - // Sets the active TOC item - self._setActiveElement(true); - - // Once all animations on the page are complete, this callback function will be called - $("html, body").promise().done(function() { - - setTimeout(function() { - - self.extendPageScroll = false; - - },0); - - }); - - }); - - }, - - // _generateToc - // ------------ - // Generates the HTML for the dynamic table of contents - _generateToc: function() { - - // _Local variables_ - - // Stores the plugin context in the self variable - var self = this, - - // All of the HTML tags found within the context provided (i.e. body) that match the top level jQuery selector above - firstElem, - - // Instantiated variable that will store the top level newly created unordered list DOM element - ul, - ignoreSelector = self.options.ignoreSelector; - - // If the selectors option has a comma within the string - if(this.options.selectors.indexOf(",") !== -1) { - - // Grabs the first selector from the string - firstElem = $(this.options.context).find(this.options.selectors.replace(/ /g,"").substr(0, this.options.selectors.indexOf(","))); - - } - - // If the selectors option does not have a comman within the string - else { - - // Grabs the first selector from the string and makes sure there are no spaces - firstElem = $(this.options.context).find(this.options.selectors.replace(/ /g,"")); - - } - - if(!firstElem.length) { - - self.element.addClass(hideTocClassName); - - return; - - } - - self.element.addClass(tocClassName); - - // Loops through each top level selector - firstElem.each(function(index) { - - //If the element matches the ignoreSelector then we skip it - if($(this).is(ignoreSelector)) { - return; - } - - // Creates an unordered list HTML element and adds a dynamic ID and standard class name - ul = $("