summaryrefslogtreecommitdiffstats
path: root/lib/models/templateBlock.js
blob: ec7dc7c5a3dc6d3bc83529573ee14ef66dadae4a (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
var is = require('is');
var Immutable = require('immutable');

var Promise = require('../utils/promise');
var genKey = require('../utils/genKey');

var NODE_ENDARGS = '%%endargs%%';

var blockBodies = {};

var TemplateBlock = Immutable.Record({
    name:           String(),
    end:            String(),
    process:        Function(),
    blocks:         Immutable.List(),
    shortcuts:      Immutable.List(),
    post:           null,
    parse:          true
});

TemplateBlock.prototype.getName = function() {
    return this.get('name');
};

TemplateBlock.prototype.getPost = function() {
    return this.get('post');
};

TemplateBlock.prototype.getParse = function() {
    return this.get('parse');
};

TemplateBlock.prototype.getEndTag = function() {
    return this.get('end') || ('end' + this.getName());
};

TemplateBlock.prototype.getProcess = function() {
    return this.get('process');
};

TemplateBlock.prototype.getBlocks = function() {
    return this.get('blocks');
};

TemplateBlock.prototype.getShortcuts = function() {
    return this.get('shortcuts');
};

/**
    Return name for the nunjucks extension

    @return {String}
*/
TemplateBlock.prototype.getExtensionName = function() {
    return 'Block' + this.getName() + 'Extension';
};

/**
    Return a nunjucks extension to represents this block

    @return {Nunjucks.Extension}
*/
TemplateBlock.prototype.toNunjucksExt = function() {
    var that = this;
    var name = this.getName();
    var endTag = this.getEndTag();
    var blocks = this.getBlocks();

    var Ext = function () {
        this.tags = [name];

        this.parse = function(parser, nodes) {
            var lastBlockName = null;
            var lastBlockArgs = null;
            var allBlocks = blocks.concat([endTag]);

            // Parse first block
            var tok = parser.nextToken();
            lastBlockArgs = parser.parseSignature(null, true);
            parser.advanceAfterBlockEnd(tok.value);

            var args = new nodes.NodeList();
            var bodies = [];
            var blockNamesNode = new nodes.Array(tok.lineno, tok.colno);
            var blockArgCounts = new nodes.Array(tok.lineno, tok.colno);

            // Parse while we found "end<block>"
            do {
                // Read body
                var currentBody = parser.parseUntilBlocks.apply(parser, allBlocks);

                // Handle body with previous block name and args
                blockNamesNode.addChild(new nodes.Literal(args.lineno, args.colno, lastBlockName));
                blockArgCounts.addChild(new nodes.Literal(args.lineno, args.colno, lastBlockArgs.children.length));
                bodies.push(currentBody);

                // Append arguments of this block as arguments of the run function
                lastBlockArgs.children.forEach(function(child) {
                    args.addChild(child);
                });

                // Read new block
                lastBlockName = parser.nextToken().value;

                // Parse signature and move to the end of the block
                if (lastBlockName != endTag) {
                    lastBlockArgs = parser.parseSignature(null, true);
                }

                parser.advanceAfterBlockEnd(lastBlockName);
            } while (lastBlockName != endTag);

            args.addChild(blockNamesNode);
            args.addChild(blockArgCounts);
            args.addChild(new nodes.Literal(args.lineno, args.colno, NODE_ENDARGS));

            return new nodes.CallExtensionAsync(this, 'run', args, bodies);
        };

        this.run = function(context) {
            var fnArgs = Array.prototype.slice.call(arguments, 1);

            var args;
            var blocks = [];
            var bodies = [];
            var blockNames;
            var blockArgCounts;
            var callback;

            // Extract callback
            callback = fnArgs.pop();

            // Detect end of arguments
            var endArgIndex = fnArgs.indexOf(NODE_ENDARGS);

            // Extract arguments and bodies
            args = fnArgs.slice(0, endArgIndex);
            bodies = fnArgs.slice(endArgIndex + 1);

            // Extract block counts
            blockArgCounts = args.pop();
            blockNames = args.pop();

            // Recreate list of blocks
            blockNames.forEach(function(name, i) {
                var countArgs = blockArgCounts[i];
                var blockBody = bodies.shift();

                var blockArgs = countArgs > 0? args.slice(0, countArgs) : [];
                args = args.slice(countArgs);
                var blockKwargs = extractKwargs(blockArgs);

                blocks.push({
                    name: name,
                    body: blockBody(),
                    args: blockArgs,
                    kwargs: blockKwargs
                });
            });

            var mainBlock = blocks.shift();
            mainBlock.blocks = blocks;

            Promise()
            .then(function() {
                return that.applyBlock(mainBlock, context);
            })
            .then(function(result) {
                return that.blockResultToHtml(result);
            })
            .nodeify(callback);
        };
    };

    return Ext;
};

/**
    Apply a block to a content
    @param {Object} inner
    @param {Object} context
    @return {Promise<String>|String}
*/
TemplateBlock.prototype.applyBlock = function(inner, context) {
    var processFn = this.getProcess();

    inner = inner || {};
    inner.args = inner.args || [];
    inner.kwargs = inner.kwargs || {};
    inner.blocks = inner.blocks || [];

    var r = processFn.call(context, inner);

    if (Promise.isPromiseAlike(r)) {
        return r.then(this.handleBlockResult);
    } else {
        return this.handleBlockResult(r);
    }
};

/**
    Handle result from a block process function

    @param {Object} result
    @return {Object}
*/
TemplateBlock.prototype.handleBlockResult = function(result) {
    if (is.string(result)) {
        result = { body: result };
    }

    return result;
};

/**
    Convert a block result to HTML

    @param {Object} result
    @return {String}
*/
TemplateBlock.prototype.blockResultToHtml = function(result) {
    var parse = this.getParse();
    var indexedKey;
    var toIndex = (!parse) || (this.getPost() !== undefined);

    if (toIndex) {
        indexedKey = TemplateBlock.indexBlockResult(result);
    }

    // Parsable block, just return it
    if (parse) {
        return result.body;
    }

    // Return it as a position marker
    return '{{-%' + indexedKey + '%-}}';

};

/**
    Index a block result, and return the indexed key

    @param {Object} blk
    @return {String}
*/
TemplateBlock.indexBlockResult = function(blk) {
    var key = genKey();
    blockBodies[key] = blk;

    return key;
};

/**
    Extract kwargs from an arguments array

    @param {Array} args
    @return {Object}
*/
function extractKwargs(args) {
    var last = args[args.length - 1];
    return (is.object(last) && last.__keywords)? args.pop() : {};
}

module.exports = TemplateBlock;