From 4fe062085324c50f2cfa062258559cf31858ef5f Mon Sep 17 00:00:00 2001 From: Sheogorath Date: Wed, 4 Jul 2018 02:22:48 +0200 Subject: Refactor generation of ToC This replaces the existing iterative implementation of the ToC generation with an recursive one. This also solves the problem of skipped headers which causes wrong leveling of them. Signed-off-by: Sheogorath --- public/vendor/md-toc.js | 100 ++++++++++++++++++++++++++---------------------- 1 file changed, 55 insertions(+), 45 deletions(-) (limited to 'public/vendor') diff --git a/public/vendor/md-toc.js b/public/vendor/md-toc.js index 3457d465..55817830 100644 --- a/public/vendor/md-toc.js +++ b/public/vendor/md-toc.js @@ -44,59 +44,69 @@ } } - Toc.prototype._createTocContent = function () { - this._elTitleElementsLen = this.elTitleElements.length - if (!this._elTitleElementsLen) return - this.tocContent = '' - this._tempLists = [] + Toc.prototype._createTocContent = function recursiveToc(level = 0, titleElements = [], titleNames = [], ulClass = undefined) { + // Inititalize our elements from the toc object + // which is only available on level 0 + if (level === 0) { + titleElements = this.elTitleElements + titleNames = this._elTitlesNames + ulClass = this.ulClass + } + var titleElementsLen = titleElements.length + // No need to do anything for an empty ToC + if (!titleElementsLen) return - for (var i = 0; i < this._elTitleElementsLen; i++) { - var j = i + 1 - this._elTitleElement = this.elTitleElements[i] - this._elTitleElementName = this._elTitleElement.tagName - this._elTitleElementTitle = this._elTitleElement.textContent.replace(/"/g, '"') - this._elTitleElementText = (typeof this.process === 'function' ? this.process(this._elTitleElement) : this._elTitleElement.innerHTML).replace(/<(?:.|\n)*?>/gm, '') - var id = this._elTitleElement.getAttribute('id') - if (!id) { - this._elTitleElement.setAttribute('id', 'tip' + i) - id = '#tip' + i - } else { - id = '#' + id - } + this.tocContent = '' + var content = '' + this._elTitleElementText + '' + for (var element; element = titleElements.shift();) { + var elementTag = element.tagName.toLowerCase() - if (j !== this._elTitleElementsLen) { - this._elNextTitleElementName = this.elTitleElements[j].tagName - if (this._elTitleElementName !== this._elNextTitleElementName) { - var checkColse = false - var y = 1 - for (var t = this._tempLists.length - 1; t >= 0; t--) { - if (this._tempLists[t].tagName === this._elNextTitleElementName) { - checkColse = true - break - } - y++ - } - if (checkColse) { - this.tocContent += new Array(y + 1).join('') - this._tempLists.length = this._tempLists.length - y - } else { - this._tempLists.push(this._elTitleElement) - if (this.ulClass) { this.tocContent += '' + + // Set ToC content of the level 0 everything else pass things to the upper level! + if (level === 0) { + this.tocContent = content + } else { + return content + } } Toc.prototype._showToc = function () { -- cgit v1.2.3