Built motion from commit 67e5df37.|2.0.66
[motion2.git] / apidoc / utils / handlebars_helper.js
1 define([
2     'locales',
3     'handlebars',
4     'diffMatchPatch'
5 ], function(locale, Handlebars, DiffMatchPatch) {
6
7     /**
8      * Return a text as markdown.
9      * Currently only a little helper to replace apidoc-inline Links (#Group:Name).
10      * Should be replaced with a full markdown lib.
11      * @param string text
12      */
13     Handlebars.registerHelper('markdown', function(text) {
14         if ( ! text ) {
15           return text;
16         }
17         text = text.replace(/((\[(.*?)\])?\(#)((.+?):(.+?))(\))/mg, function(match, p1, p2, p3, p4, p5, p6) {
18           var link = p3 || p5 + '/' + p6;
19           return '<a href="#api-' + p5 + '-' + p6 + '">' + link + '</a>';
20         });
21         return text;
22     });
23
24     /**
25      * start/stop timer for simple performance check.
26      */
27     var timer;
28     Handlebars.registerHelper('startTimer', function(text) {
29         timer = new Date();
30         return '';
31     });
32
33     Handlebars.registerHelper('stopTimer', function(text) {
34         console.log(new Date() - timer);
35         return '';
36     });
37
38     /**
39      * Return localized Text.
40      * @param string text
41      */
42     Handlebars.registerHelper('__', function(text) {
43         return locale.__(text);
44     });
45
46     /**
47      * Console log.
48      * @param mixed obj
49      */
50     Handlebars.registerHelper('cl', function(obj) {
51         console.log(obj);
52         return '';
53     });
54
55     /**
56      * Replace underscore with space.
57      * @param string text
58      */
59     Handlebars.registerHelper('underscoreToSpace', function(text) {
60         return text.replace(/(_+)/g, ' ');
61     });
62
63     /**
64      *
65      */
66     Handlebars.registerHelper('assign', function(name) {
67         if(arguments.length > 0) {
68             var type = typeof(arguments[1]);
69             var arg = null;
70             if(type === 'string' || type === 'number' || type === 'boolean') arg = arguments[1];
71             Handlebars.registerHelper(name, function() { return arg; });
72         }
73         return '';
74     });
75
76     /**
77      *
78      */
79     Handlebars.registerHelper('nl2br', function(text) {
80         return _handlebarsNewlineToBreak(text);
81     });
82
83     /**
84      *
85      */
86     Handlebars.registerHelper('if_eq', function(context, options) {
87         var compare = context;
88         // Get length if context is an object
89         if (context instanceof Object && ! (options.hash.compare instanceof Object))
90              compare = Object.keys(context).length;
91
92         if (compare === options.hash.compare)
93             return options.fn(this);
94
95         return options.inverse(this);
96     });
97
98     /**
99      *
100      */
101     Handlebars.registerHelper('if_gt', function(context, options) {
102         var compare = context;
103         // Get length if context is an object
104         if (context instanceof Object && ! (options.hash.compare instanceof Object))
105              compare = Object.keys(context).length;
106
107         if(compare > options.hash.compare)
108             return options.fn(this);
109
110         return options.inverse(this);
111     });
112
113     /**
114      *
115      */
116     var templateCache = {};
117     Handlebars.registerHelper('subTemplate', function(name, sourceContext) {
118         if ( ! templateCache[name])
119             templateCache[name] = Handlebars.compile($('#template-' + name).html());
120
121         var template = templateCache[name];
122         var templateContext = $.extend({}, this, sourceContext.hash);
123         return new Handlebars.SafeString( template(templateContext) );
124     });
125
126     /**
127      *
128      */
129     Handlebars.registerHelper('toLowerCase', function(value) {
130         return (value && typeof value === 'string') ? value.toLowerCase() : '';
131     });
132
133     /**
134      *
135      */
136     Handlebars.registerHelper('splitFill', function(value, splitChar, fillChar) {
137         var splits = value.split(splitChar);
138         return new Array(splits.length).join(fillChar) + splits[splits.length - 1];
139     });
140
141     /**
142      * Convert Newline to HTML-Break (nl2br).
143      *
144      * @param {String} text
145      * @returns {String}
146      */
147     function _handlebarsNewlineToBreak(text) {
148         return ('' + text).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
149     }
150
151     /**
152      *
153      */
154     Handlebars.registerHelper('each_compare_list_field', function(source, compare, options) {
155         var fieldName = options.hash.field;
156         var newSource = [];
157         if (source) {
158             source.forEach(function(entry) {
159                 var values = entry;
160                 values['key'] = entry[fieldName];
161                 newSource.push(values);
162             });
163         }
164
165         var newCompare = [];
166         if (compare) {
167             compare.forEach(function(entry) {
168                 var values = entry;
169                 values['key'] = entry[fieldName];
170                 newCompare.push(values);
171             });
172         }
173         return _handlebarsEachCompared('key', newSource, newCompare, options);
174     });
175
176     /**
177      *
178      */
179     Handlebars.registerHelper('each_compare_keys', function(source, compare, options) {
180         var newSource = [];
181         if (source) {
182             var sourceFields = Object.keys(source);
183             sourceFields.forEach(function(name) {
184                 var values = {};
185                 values['value'] = source[name];
186                 values['key'] = name;
187                 newSource.push(values);
188             });
189         }
190
191         var newCompare = [];
192         if (compare) {
193             var compareFields = Object.keys(compare);
194             compareFields.forEach(function(name) {
195                 var values = {};
196                 values['value'] = compare[name];
197                 values['key'] = name;
198                 newCompare.push(values);
199             });
200         }
201         return _handlebarsEachCompared('key', newSource, newCompare, options);
202     });
203
204     /**
205      *
206      */
207     Handlebars.registerHelper('each_compare_field', function(source, compare, options) {
208         return _handlebarsEachCompared('field', source, compare, options);
209     });
210
211     /**
212      *
213      */
214     Handlebars.registerHelper('each_compare_title', function(source, compare, options) {
215         return _handlebarsEachCompared('title', source, compare, options);
216     });
217
218     /**
219      *
220      */
221     Handlebars.registerHelper('reformat', function(source, type){
222         if (type == 'json')
223             try {
224                return JSON.stringify(JSON.parse(source.trim()),null, "    ");
225             } catch(e) {
226
227             }
228         return source
229     });
230
231     /**
232      *
233      */
234     Handlebars.registerHelper('showDiff', function(source, compare, options) {
235         var ds = '';
236         if(source === compare) {
237             ds = source;
238         } else {
239             if( ! source)
240                 return compare;
241
242             if( ! compare)
243                 return source;
244
245             var d = diffMatchPatch.diff_main(compare, source);
246             diffMatchPatch.diff_cleanupSemantic(d);
247             ds = diffMatchPatch.diff_prettyHtml(d);
248             ds = ds.replace(/&para;/gm, '');
249         }
250         if(options === 'nl2br')
251             ds = _handlebarsNewlineToBreak(ds);
252
253         return ds;
254     });
255
256     /**
257      *
258      */
259     function _handlebarsEachCompared(fieldname, source, compare, options)
260     {
261         var dataList = [];
262         var index = 0;
263         if(source) {
264             source.forEach(function(sourceEntry) {
265                 var found = false;
266                 if (compare) {
267                     compare.forEach(function(compareEntry) {
268                         if(sourceEntry[fieldname] === compareEntry[fieldname]) {
269                             var data = {
270                                 typeSame: true,
271                                 source: sourceEntry,
272                                 compare: compareEntry,
273                                 index: index
274                             };
275                             dataList.push(data);
276                             found = true;
277                             index++;
278                         }
279                     });
280                 }
281                 if ( ! found) {
282                     var data = {
283                         typeIns: true,
284                         source: sourceEntry,
285                         index: index
286                     };
287                     dataList.push(data);
288                     index++;
289                 }
290             });
291         }
292
293         if (compare) {
294             compare.forEach(function(compareEntry) {
295                 var found = false;
296                 if (source) {
297                     source.forEach(function(sourceEntry) {
298                         if(sourceEntry[fieldname] === compareEntry[fieldname])
299                             found = true;
300                     });
301                 }
302                 if ( ! found) {
303                     var data = {
304                         typeDel: true,
305                         compare: compareEntry,
306                         index: index
307                     };
308                     dataList.push(data);
309                     index++;
310                 }
311             });
312         }
313
314         var ret = '';
315         var length = dataList.length;
316         for (var index in dataList) {
317             if(index == (length - 1))
318                 dataList[index]['_last'] = true;
319             ret = ret + options.fn(dataList[index]);
320         }
321         return ret;
322     }
323
324     var diffMatchPatch = new DiffMatchPatch();
325
326     /**
327      * Overwrite Colors
328      */
329     DiffMatchPatch.prototype.diff_prettyHtml = function(diffs) {
330       var html = [];
331       var pattern_amp = /&/g;
332       var pattern_lt = /</g;
333       var pattern_gt = />/g;
334       var pattern_para = /\n/g;
335       for (var x = 0; x < diffs.length; x++) {
336         var op = diffs[x][0];    // Operation (insert, delete, equal)
337         var data = diffs[x][1];  // Text of change.
338         var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')
339             .replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');
340         switch (op) {
341           case DIFF_INSERT:
342             html[x] = '<ins>' + text + '</ins>';
343             break;
344           case DIFF_DELETE:
345             html[x] = '<del>' + text + '</del>';
346             break;
347           case DIFF_EQUAL:
348             html[x] = '<span>' + text + '</span>';
349             break;
350         }
351       }
352       return html.join('');
353     };
354
355     // Exports
356     return Handlebars;
357 });