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
/* DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
   Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License.
   You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and limitations under the License.*/

// converts .dre xml into dreemgl-compliant javascript. Supports methods, attributes, attribute declarations and handlers.
define(function(require){
        var fs = require('fs')
        var HTMLParser = require('$system/parse/htmlparser')

        var makeSpace = function(indent) {
                var out = '';
                for (var i = 0; i < indent; i++) {
                        out += '\t';
                }
                return out;
        }
        // filter out methods attributes and handlers
        var filterSpecial = function(child) {
                var name = child.tag;
                return name.indexOf('$') !== 0 && (! filterMethods(child)) && (! filterAttributes(child)) && (! filterHandlers(child));
        }
        var filterMethods = function(child) {
                return child.tag === 'method';
        }
        // compile methods to JS function bodies
        var toMethod = function(child) {
                var body = HTMLParser.reserialize(child.child[0]);
                var args = child.attr.args || ''
                var fn = 'function(' + args + ') {' + body + '}';
                return {attr: child.attr, body: fn};
        }
        var filterAttributes = function(child) {
                return child.tag === 'attribute';
        }
        var filterHandlers = function(child) {
                return child.tag === 'handler';
        }
        var capitalize = function(string) {
                return string.charAt(0).toUpperCase() + string.slice(1);
        }
        // like JSON.stringify, but preserves function( and Config( declarations
        var objToString = function(obj) {
                var out = '{';
                var keys = Object.keys(obj);
                for (var i = 0; i < keys.length; i++) {
                        var key = keys[i];
                        var val = obj[key];

                        out += key + ': ';
                        if (typeof val === 'object') {
                                out += objToString(val);
                        } else if (val.indexOf('function(') === 0 ||
                                                                 val.indexOf('Config({') === 0) {
                                // don't wrap Config or function(...) in quotes
                                out += val;
                        } else {
                                // fall back to string values
                                out += '"' + val + '"';
                        }
                        if (i < keys.length - 1) out += ', ';
                }
                out += '}';
                return out;
        }

        // convert a parsed tag and its children to nested function calls,
        // accumulating tag names
        var tagToFunc = function(child, indent, tagnames) {
                // console.log('tagToFunc', indent, child, child.attr)
                var outputthis = filterSpecial(child);
                var out = '';
                var attr = child.attr || {};
                var i;

                // add methods to attributes hash
                var methods = child.child && child.child.filter(filterMethods).map(toMethod);
                if (methods) {
                        for (i = 0; i < methods.length; i++) {
                                var method = methods[i];
                                attr[method.attr.name] = method.body;
                                // console.log('found method:', method)
                        }
                }

                // add attribute declarations
                var attributes = child.child && child.child.filter(filterAttributes);
                if (attributes && attributes.length) {
                        if (! attr.attributes) {
                                attr.attributes = {};
                        }
                        for (i = 0; i < attributes.length; i++) {
                                var attribute = attributes[i].attr;
                                var val = attribute.value;
                                var type = capitalize(attribute.type);
                                if (type === 'String') {
                                        val = '"' + val + '"';
                                }
                                // console.log('found attribute:', attribute, val, type)
                                attr.attributes[attribute.name] = 'Config({type: ' + type + ', value: ' + val + '})';
                        }
                }

                // add handlers
                var handlers = child.child && child.child.filter(filterHandlers).map(toMethod);
                if (handlers && handlers.length) {
                        if (! attr.attributes) {
                                attr.attributes = {};
                        }
                        var handlersByEvent = {};
                        // write out listener functions for each event
                        for (i = 0; i < handlers.length; i++) {
                                var handler = handlers[i];
                                // chop off leading 'on'
                                var attrname = handler.attr.event.substring(2);
                                // register listener for that event
                                if (! handlersByEvent[attrname]) handlersByEvent[attrname] = [];
                                handlersByEvent[attrname].push(handler.body);
                        }
                        for (var eventname in handlersByEvent) {
                                var listeners = handlersByEvent[eventname].join(', ')
                                attr.attributes[eventname] = 'Config({listeners: [' + listeners + ']})';
                        }
                }

                var children = child.child && child.child.filter(filterSpecial);
                var hasChildren = children && children.length;
                if (outputthis) {
                        out += makeSpace(indent);
                        // name
                        var tagname = child.tag;
                        if (! tagnames[tagname]) tagnames[tagname] = 0;
      tagnames[tagname]++;
                        out += tagname + '(';
                        // attributes
                        out += objToString(attr);
                        if (hasChildren) out += ',\n'
                }
                if (hasChildren) {
                        // children
                        indent++;
                        for (i = 0; i < children.length; i++) {
                                var newchild = children[i];
                                out += tagToFunc(newchild, indent, tagnames);
                                if (i !== children.length - 1) {
                                        out += ','
                                }
                                out += '\n';
                        }
                        indent--;
                }
                if (outputthis) {
                        if (hasChildren) out += makeSpace(indent);
                        out += ')';
                }
                return out;
        }

        // look for includes by name across server paths
        var findIncludes = function(tagnames) {
                var tagbypath = {};
                for (var i = 0; i < tagnames.length; i++) {
                        var tagname = tagnames[i];
                        for (var key in define.paths) {
                                var filepath = define.expandVariables('$' + key) + '/' + tagname + '.js';
                                // look for tagname file in expanded path
                                if (fs.existsSync(filepath)) {
                                        // add to the list of tags at that path
                                        if (! tagbypath[key]) {
                                                tagbypath[key] = [];
                                        }
                                        tagbypath[key].push(tagname);
                                        break;
                                }
                        }
    }
    // flatten to a list of path declarations and includes
    var includes = ['require'];
    for (var key in tagbypath) {
                        includes.push('$' + key + '$');
                        includes = includes.concat(tagbypath[key]);
    }
    return includes;
        }

        return function(dre) {
                // console.log('parsing .dre', dre);
                var parsed = HTMLParser(dre);
                // console.log('parsed', JSON.stringify(parsed.node));
    var tagnames = {};
    var body = tagToFunc(parsed.node, 2, tagnames);
    // find includes based on tags found
    var includes = findIncludes(Object.keys(tagnames));
                // console.log('includes', includes)
                var out = 'define.class(\'$server/composition\', function(' + includes.join(', ') + '){\n'
                out += '\tthis.render = function() {\n'
                out += '\t\treturn [\n';
                out += body;
                out += '\t\t];\n\t}\n});'
                // console.log('result', out, includes)
                return out;
        }
})