diff options
Diffstat (limited to 'lib/backbone/summary.js')
-rw-r--r-- | lib/backbone/summary.js | 72 |
1 files changed, 69 insertions, 3 deletions
diff --git a/lib/backbone/summary.js b/lib/backbone/summary.js index aa52104..5775c8b 100644 --- a/lib/backbone/summary.js +++ b/lib/backbone/summary.js @@ -14,6 +14,7 @@ It's defined by a title, a reference, and children articles, the reference (ref) function TOCArticle(summary, title, ref, articles, parent) { this.summary = summary; this.title = title; + this.parent = parent; if (ref && location.isExternal(ref)) { throw error.ParsingError(new Error('SUMMARY can only contains relative locations')); @@ -50,6 +51,45 @@ TOCArticle.prototype.hasChildren = function() { return this.articles.length > 0; }; +// Return true if has an article as parent +TOCArticle.prototype.hasParent = function() { + return (this.parent instanceof TOCArticle); +}; + +// Return next article in the TOC +TOCArticle.prototype.next = function() { + var parentsArticles = this.parent.articles; + var pos = _.findIndex(parentsArticles, this); + + if ((pos + 1) >= parentsArticles.length) { + if (this.hasParent()) { + return this.parent.next(); + } else { + return null; + } + } else { + // next has the same parent + return parentsArticles[pos + 1]; + } +}; + +// Return previous article in the TOC +TOCArticle.prototype.prev = function() { + var parentsArticles = this.parent.articles; + var pos = _.findIndex(parentsArticles, this); + + if ((pos - 1) < 0) { + if (this.hasParent()) { + return this.parent.prev(); + } else { + return null; + } + } else { + // prev has the same parent + return parentsArticles[pos - 1]; + } +}; + /* A part of a ToC is a composed of a tree of articles. */ @@ -58,14 +98,17 @@ function TOCPart(summary, part) { this.summary = summary; this.articles = _.map(part.articles || part.chapters, function(article) { - return new TOCArticle(that.summary, article.title, article.path, article.articles); - }); + return new TOCArticle(that.summary, article.title, article.path, article.articles, this); + }, this); } // Iterate over all entries of the part TOCPart.prototype.walk = function(iter) { _.each(this.articles, function(article) { - iter(article); + if (iter(article) === false) { + return false; + } + article.walk(iter); }); }; @@ -109,6 +152,29 @@ Summary.prototype.walk = function(iter) { }); }; +// Find a specific article using a filter +Summary.prototype.find = function(filter) { + var result; + + this.walk(function(article) { + if (filter(article)) { + result = article; + return false; + } + }); + + return result; +}; + +// Return the first TOCArticle for a specific page (or path) +Summary.prototype.getByPage = function(page) { + if (!_.isString(page)) page = page.path; + + return this.find(function(article) { + return article.path == page; + }); +}; + // Return the count of articles in the summary Summary.prototype.count = function() { return this._length; |