public
Description: E4X-based template engine
Homepage:
Clone URL: git://github.com/bard/seethrough_js.git
seethrough_js / seethrough.js
100644 387 lines (326 sloc) 12.103 kb
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/*
* Copyright 2008 by Massimiliano Mirra
*
* This file is part of seethrough.
*
* seethrough is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* seethrough is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code
* versions of this program must display Appropriate Legal Notices, as
* required under Section 5 of the GNU General Public License version 3.
*
* Author: Massimiliano Mirra, <bard [at] hyperstruct [dot] net>
*
*/
 
 
var seethrough = {};
 
 
// TAG/ATTRIBUTE PROCESSORS
// ----------------------------------------------------------------------
 
seethrough.processors = {
    'http://hyperstruct.net/seethrough#js::attr': function() {
        // Apparently, an xml attribute object cannot be created by
        // itself, so we use a dummy element as attribute "factory".
        // Also, we want to create this element just once, not every
        // time we need to generate an attribute.
        var dummy = <dummy/>;
        return function stAttr(element, env, children) {
            var value = children(env);
            dummy.@[element.@name] = (typeof(value) === 'undefined') ? '' : value.toString();
            return dummy.@[element.@name];
        }
    },
 
    'http://hyperstruct.net/seethrough#js::condition': function(attrValue) {
        return function stCondition(element, env, children) {
            if(seethrough.getEnv(env, attrValue))
                return element.appendChild(children(env));
            else
                return new XML('');
        }
    },
 
    'http://hyperstruct.net/seethrough#js::disable': function(attrValue) {
        return function stDisable(element, env, children) {
            return attrValue == 'true' ? new XML('') : element;
        }
    },
 
    'http://hyperstruct.net/seethrough#js::replace': function(attrValue) {
        return function stReplace(element, env, children) {
            var envValue = seethrough.getEnv(env, attrValue);
            switch(typeof(envValue)) { // this should belong in
            case 'number':
            case 'string':
                return <dummy>{envValue}</dummy>.text();
            case 'xml':
                return envValue;
            default:
                throw new TypeError('Unhandled type for "' +
                                    envValue +
                                    '" (' + typeof(envValue) + ')');
            }
        }
    },
 
    'http://hyperstruct.net/seethrough#js::inspect': function(attrValue) {
        return function stInspect(element, env, children) {
            var envValue = seethrough.getEnv(env, attrValue);
            var representation;
            switch(typeof(envValue)) {
            case 'number':
            case 'string':
                representation = envValue;
                break;
            case 'xml':
                representation = envValue.toXMLString();
                break;
            case 'object':
                representation = envValue.toSource();
                break;
            default:
                throw new TypeError('Unhandled type for "' +
                                    envValue +
                                    '" (' + typeof(envValue) + ')');
            }
            // Force escaping
            return <dummy>{representation}</dummy>.text();
        }
    },
 
    'http://hyperstruct.net/seethrough#js::content': function(attrValue) {
        return function(element, env, children) {
            return element.appendChild(seethrough.getEnv(env, attrValue));
        }
    },
 
// 'http://hyperstruct.net/seethrough#js::extra': function(attrValue, children) {
// return function(element, env) {
// return element.appendChild(seethrough.getEnv(env, attrValue));
// }
// },
 
    'http://hyperstruct.net/seethrough#js::loop': function(attrValue) {
        var [iterName, collectionName] = attrValue.split(' ');
        return function stLoop(element, env, children) {
            var container = new XMLList();
            if(iterName in env)
                throw new Error('Overriding global name not yet supported.');
 
            // XXX copied from compile.element -- factor! cleanup!
 
            var collection = seethrough.getEnv(env, collectionName);
            for each(var envValue in collection) {
                env[iterName] = envValue;
 
                var xmlOut = element.copy();
 
                var xmlChildren = children(env);
                if(typeof(xmlChildren) == 'undefined')
                    return xmlOut;
 
                var xmlChild;
                for(var i=0,l=xmlChildren.length(); i<l; i++) {
                    xmlChild = xmlChildren[i];
                    if(xmlChild.nodeKind() == 'attribute')
                        xmlOut.@[xmlChild.name()] = xmlChild.toString();
                    else
                        xmlOut.appendChild(xmlChild);
                }
 
                container += xmlOut;
            }
            delete env[iterName];
            return container;
        }
    },
 
    'http://hyperstruct.net/seethrough#js::eval': function() {
        return function stEval(element, env, children) {
            return new XML(eval(children(env).toString()));
        }
    }
};
 
 
// ENVIRONMENT
// ----------------------------------------------------------------------
 
seethrough.getEnv = function(env, path) {
    function fold(fn, acc, seq) {
        Array.forEach(seq, function(item) { acc = fn(acc, item); });
        return acc;
    }
 
    try {
        var value = fold(
            function(subEnv, propName) { return subEnv[propName] },
            env,
            path.split('.'));
 
        if(typeof(value) == 'xml' && value.nodeKind() == 'attribute')
            return value.toString();
        else
            return value;
    } catch(e if e.name == 'TypeError') {
        return undefined;
    }
};
 
 
// COMPILATION
// ----------------------------------------------------------------------
 
seethrough.EMPTY = function() {
    return function() {};
};
 
seethrough.compile = function(xml) {
    var c = arguments.callee;
 
    // Rhino brings up XML lists of length 0, Spidermonkey doesn't.
    if(xml.length() > 1)
        return c.list(xml);
    else if(xml.length() == 0)
        return seethrough.EMPTY();
    else
        switch(xml.nodeKind()) {
        case 'element':
            return c.element(xml);
            break;
        case 'text':
            return c.text(xml);
            break;
        case 'comment':
            return c.comment(xml);
            break;
        default:
            throw new Error('Compile error: unhandled node kind. (' + xml.nodeKind() + ')');
        }
}
 
seethrough.compile.comment = function(xmlComment) {
    return function() {
        return xmlComment;
    }
}
 
seethrough.compile.text = function(xmlText) {
    return function() {
        return xmlText;
    }
};
 
seethrough.compile.list = function(xmlList) {
    d(' - Compiling children');
    var renderChildren = [];
    for each(var xmlNode in xmlList) {
        renderChildren.push(seethrough.compile(xmlNode));
    }
 
    return function(env) {
        d(' * Rendering children')
        var rendered = new XMLList();
        for each(var renderChild in renderChildren) {
            rendered += renderChild(env);
        }
        return rendered;
    };
};
 
seethrough.compile.element = function(xmlElement) {
    d('- Compiling element ' + xmlElement.name());
    var xmlBase = xmlElement.copy();
    delete xmlBase.*::*;
 
    var elementProcessors = seethrough.makeProcessors(xmlElement);
    if(elementProcessors.length > 0)
        d(' - ' + elementProcessors.length + ' processor(s) to apply');
 
    var children = seethrough.compile(xmlElement.children());
 
    var render;
    if(elementProcessors.length > 0)
        render = function(env) {
            var xmlOut = xmlBase.copy(); // ref to parent scope - leak
            d('* Rendering ' + xmlOut.name());
            for each(var fnStep in elementProcessors) {
                xmlOut = fnStep(xmlOut, env, children);
            }
            return xmlOut;
        };
    else
        render = function(env) {
            try { // why don't exceptions get surfaced here?
                var xmlOut = xmlBase.copy();
                d('* Rendering ' + xmlOut.name());
 
                xmlChildren = children(env); // undeclared?
                if(typeof(xmlChildren) == 'undefined')
                    return xmlOut;
 
                var xmlChild;
                for(var i=0,l=xmlChildren.length(); i<l; i++) {
                    xmlChild = xmlChildren[i];
                    if(xmlChild.nodeKind() == 'attribute') {
                        if(xmlChild.toString() != '')
                            xmlOut.@[xmlChild.name()] = xmlChild.toString();
                    }
                    else
                        xmlOut.appendChild(xmlChild);
                }
 
                return xmlOut;
            } catch(e) {
                d(e + '\n' + e.stack);
            }
        };
 
    render.src = xmlElement;
    return render;
};
 
seethrough.makeProcessors = function(element) {
    var steps = [], makeProcessor;
 
    function makeAttributeProcessor(attr) {
        var ns = attr.namespace();
        var attrValue = attr.toString();
        var processor = makeProcessor(attrValue);
        return function(element, env, children) {
            d(' * Applying processor for ' + attr.name());
            delete element.@ns::[attr.localName()];
            var result = processor(element, env, children);
            return result;
        }
    }
 
    // Handle attributes
    for each(var attr in element.@*::*) {
        makeProcessor = seethrough.processors[attr.name().toString()];
        if(makeProcessor)
            steps.push(makeAttributeProcessor(attr));
    }
 
    // Handle tag
    makeProcessor = seethrough.processors[element.name().toString()];
    if(makeProcessor)
        steps.push(makeProcessor());
 
    return steps;
};
 
 
// DEVELOPMENT UTILITIES
// ----------------------------------------------------------------------
 
function d(msg) {
    if(!d.on)
        return;
 
    if(!arguments.callee.printFn) {
        if(typeof(print) == 'function')
            // command-line spidermonkey
            arguments.callee.printFn = print;
        else if(typeof(app) == 'object' &&
                typeof(app.log) == 'function')
            // helma
            arguments.callee.printFn = function(s) { app.log(s) };
        else
            arguments.callee.printFn = function() {};
    }
 
    var output;
    var stack = (new Error()).stack;
    if(stack)
        output = stack.split('\n')[2] + ':' + msg;
    else
        output = msg;
 
    arguments.callee.printFn(output);
}
d.on = false;
 
 
// ENVIRONMENT-SPECIFIC: HELMA
// ----------------------------------------------------------------------
 
if(typeof(export) === 'function') {
 
    include('helma/file');
    import('helma/webapp/response');
 
    export('render', 'Response');
 
    function render(templateName, env) {
        // This should eventually be cached and only recompiled if
        // file changes.
 
        var template =
            seethrough.compile(
                new XML(
                    new File(
                        getResource(templateName + '.st'))
                        .readAll())
            );
        return template(env);
    }
 
    function Response(template, env) {
        return new helma.webapp.response.Response(render(template, env));
    }
}