summaryrefslogtreecommitdiffstats
path: root/lib/modifiers/summary/insertArticle.js
blob: d97943e349522def93baec97f321624013fb535f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
var is = require('is');
var SummaryArticle = require('../../models/summaryArticle');
var editArticle = require('./editArticle');
var indexArticleLevels = require('./indexArticleLevels');

/**
    Insert an article in a summary at a specific position

    @param {Summary} summary
    @param {String|Article} level: level to insert after
    @param {Article} article
    @return {Summary}
*/
function insertArticle(summary, level, article) {
    article = SummaryArticle(article);
    level = is.string(level)? level : level.getLevel();

    var parent = summary.getParent(level);
    if (!parent) {
        return summary;
    }

    // Find the index to insert at
    var articles = parent.getArticles();
    var index = articles.findIndex(function(art) {
        return art.getLevel() === level;
    });
    if (!index) {
        return summary;
    }

    // Insert the article at the right index
    articles = articles.insert(index, article);

    // Reindex the level from here
    parent = parent.set('articles', articles);
    parent = indexArticleLevels(parent);

    return editArticle(summary, parent.getLevel(), parent);
}

module.exports = insertArticle;