8aeef2392416d434462005d3d2f20b54bf23f898
[platform/framework/web/web-ui-fw.git] / libs / js / jquery-mobile-1.0.1pre / experiments / converter / jquery.tmpl.js
1 /*
2  * Copy of http://github.com/nje/jquery-tmpl/raw/master/jquery.tmpl.js at f827fb68417bc14ab9f6ae889421d5fea4cb2859
3  * jQuery Templating Plugin
4  * Copyright 2010, John Resig
5  * Dual licensed under the MIT or GPL Version 2 licenses.
6  */
7 (function( jQuery, undefined ){
8         var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
9                 newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];
10
11         function newTmplItem( options, parentItem, fn, data ) {
12                 // Returns a template item data structure for a new rendered instance of a template (a 'template item').
13                 // The content field is a hierarchical array of strings and nested items (to be
14                 // removed and replaced by nodes field of dom elements, once inserted in DOM).
15                 var newItem = {
16                         data: data || (parentItem ? parentItem.data : {}),
17                         _wrap: parentItem ? parentItem._wrap : null,
18                         tmpl: null,
19                         parent: parentItem || null,
20                         nodes: [],
21                         calls: tiCalls,
22                         nest: tiNest,
23                         wrap: tiWrap,
24                         html: tiHtml,
25                         update: tiUpdate
26                 };
27                 if ( options ) {
28                         jQuery.extend( newItem, options, { nodes: [], parent: parentItem } );
29                 }
30                 if ( fn ) {
31                         // Build the hierarchical content to be used during insertion into DOM
32                         newItem.tmpl = fn;
33                         newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem );
34                         newItem.key = ++itemKey;
35                         // Keep track of new template item, until it is stored as jQuery Data on DOM element
36                         (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
37                 }
38                 return newItem;
39         }
40
41         // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
42         jQuery.each({
43                 appendTo: "append",
44                 prependTo: "prepend",
45                 insertBefore: "before",
46                 insertAfter: "after",
47                 replaceAll: "replaceWith"
48         }, function( name, original ) {
49                 jQuery.fn[ name ] = function( selector ) {
50                         var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems,
51                                 parent = this.length === 1 && this[0].parentNode;
52
53                         appendToTmplItems = newTmplItems || {};
54                         if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
55                                 insert[ original ]( this[0] );
56                                 ret = this;
57                         } else {
58                                 for ( i = 0, l = insert.length; i < l; i++ ) {
59                                         cloneIndex = i;
60                                         elems = (i > 0 ? this.clone(true) : this).get();
61                                         jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
62                                         ret = ret.concat( elems );
63                                 }
64                                 cloneIndex = 0;
65                                 ret = this.pushStack( ret, name, insert.selector );
66                         }
67                         tmplItems = appendToTmplItems;
68                         appendToTmplItems = null;
69                         jQuery.tmpl.complete( tmplItems );
70                         return ret;
71                 };
72         });
73
74         jQuery.fn.extend({
75                 // Use first wrapped element as template markup.
76                 // Return wrapped set of template items, obtained by rendering template against data.
77                 tmpl: function( data, options, parentItem ) {
78                         return jQuery.tmpl( this[0], data, options, parentItem );
79                 },
80
81                 // Find which rendered template item the first wrapped DOM element belongs to
82                 tmplItem: function() {
83                         return jQuery.tmplItem( this[0] );
84                 },
85
86                 // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
87                 template: function( name ) {
88                         return jQuery.template( name, this[0] );
89                 },
90
91                 domManip: function( args, table, callback, options ) {
92                         // This appears to be a bug in the appendTo, etc. implementation
93                         // it should be doing .call() instead of .apply(). See #6227
94                         if ( args[0] && args[0].nodeType ) {
95                                 var dmArgs = jQuery.makeArray( arguments ), argsLength = args.length, i = 0, tmplItem;
96                                 while ( i < argsLength && !(tmplItem = jQuery.data( args[i++], "tmplItem" ))) {}
97                                 if ( argsLength > 1 ) {
98                                         dmArgs[0] = [jQuery.makeArray( args )];
99                                 }
100                                 if ( tmplItem && cloneIndex ) {
101                                         dmArgs[2] = function( fragClone ) {
102                                                 // Handler called by oldManip when rendered template has been inserted into DOM.
103                                                 jQuery.tmpl.afterManip( this, fragClone, callback );
104                                         };
105                                 }
106                                 oldManip.apply( this, dmArgs );
107                         } else {
108                                 oldManip.apply( this, arguments );
109                         }
110                         cloneIndex = 0;
111                         if ( !appendToTmplItems ) {
112                                 jQuery.tmpl.complete( newTmplItems );
113                         }
114                         return this;
115                 }
116         });
117
118         jQuery.extend({
119                 // Return wrapped set of template items, obtained by rendering template against data.
120                 tmpl: function( tmpl, data, options, parentItem ) {
121                         var ret, topLevel = !parentItem;
122                         if ( topLevel ) {
123                                 // This is a top-level tmpl call (not from a nested template using {{tmpl}})
124                                 parentItem = topTmplItem;
125                                 tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
126                                 wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
127                         } else if ( !tmpl ) {
128                                 // The template item is already associated with DOM - this is a refresh.
129                                 // Re-evaluate rendered template for the parentItem
130                                 tmpl = parentItem.tmpl;
131                                 newTmplItems[parentItem.key] = parentItem;
132                                 parentItem.nodes = [];
133                                 if ( parentItem.wrapped ) {
134                                         updateWrapped( parentItem, parentItem.wrapped );
135                                 }
136                                 // Rebuild, without creating a new template item
137                                 return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
138                         }
139                         if ( !tmpl ) {
140                                 return []; // Could throw...
141                         }
142                         if ( typeof data === "function" ) {
143                                 data = data.call( parentItem || {} );
144                         }
145                         if ( options && options.wrapped ) {
146                                 updateWrapped( options, options.wrapped );
147                         }
148                         ret = jQuery.isArray( data ) ? 
149                                 jQuery.map( data, function( dataItem ) {
150                                         return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
151                                 }) :
152                                 [ newTmplItem( options, parentItem, tmpl, data ) ];
153
154                         return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
155                 },
156
157                 // Return rendered template item for an element.
158                 tmplItem: function( elem ) {
159                         var tmplItem;
160                         if ( elem instanceof jQuery ) {
161                                 elem = elem[0];
162                         }
163                         while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
164                         return tmplItem || topTmplItem;
165                 },
166
167                 // Set:
168                 // Use $.template( name, tmpl ) to cache a named template,
169                 // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
170                 // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.
171
172                 // Get:
173                 // Use $.template( name ) to access a cached template.
174                 // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
175                 // will return the compiled template, without adding a name reference.
176                 // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
177                 // to $.template( null, templateString )
178                 template: function( name, tmpl ) {
179                         if (tmpl) {
180                                 // Compile template and associate with name
181                                 if ( typeof tmpl === "string" ) {
182                                         // This is an HTML string being passed directly in.
183                                         tmpl = buildTmplFn( tmpl )
184                                 } else if ( tmpl instanceof jQuery ) {
185                                         tmpl = tmpl[0] || {};
186                                 }
187                                 if ( tmpl.nodeType ) {
188                                         // If this is a template block, use cached copy, or generate tmpl function and cache.
189                                         tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML ));
190                                 }
191                                 return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
192                         }
193                         // Return named compiled template
194                         return name ? (typeof name !== "string" ? jQuery.template( null, name ): 
195                                 (jQuery.template[name] || 
196                                         // If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) 
197                                         jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; 
198                 },
199
200                 encode: function( text ) {
201                         // Do HTML encoding replacing < > & and ' and " by corresponding entities.
202                         return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
203                 }
204         });
205
206         jQuery.extend( jQuery.tmpl, {
207                 tag: {
208                         "tmpl": {
209                                 _default: { $2: "null" },
210                                 open: "if($notnull_1){_=_.concat($item.nest($1,$2));}"
211                                 // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
212                                 // This means that {{tmpl foo}} treats foo as a template (which IS a function). 
213                                 // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
214                         },
215                         "wrap": {
216                                 _default: { $2: "null" },
217                                 open: "$item.calls(_,$1,$2);_=[];",
218                                 close: "call=$item.calls();_=call._.concat($item.wrap(call,_));"
219                         },
220                         "each": {
221                                 _default: { $2: "$index, $value" },
222                                 open: "if($notnull_1){$.each($1a,function($2){with(this){",
223                                 close: "}});}"
224                         },
225                         "if": {
226                                 open: "if(($notnull_1) && $1a){",
227                                 close: "}"
228                         },
229                         "else": {
230                                 _default: { $1: "true" },
231                                 open: "}else if(($notnull_1) && $1a){"
232                         },
233                         "html": {
234                                 // Unecoded expression evaluation. 
235                                 open: "if($notnull_1){_.push($1a);}"
236                         },
237                         "=": {
238                                 // Encoded expression evaluation. Abbreviated form is ${}.
239                                 _default: { $1: "$data" },
240                                 open: "if($notnull_1){_.push($.encode($1a));}"
241                         },
242                         "!": {
243                                 // Comment tag. Skipped by parser
244                                 open: ""
245                         }
246                 },
247
248                 // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
249                 complete: function( items ) {
250                         newTmplItems = {};
251                 },
252
253                 // Call this from code which overrides domManip, or equivalent
254                 // Manage cloning/storing template items etc.
255                 afterManip: function afterManip( elem, fragClone, callback ) {
256                         // Provides cloned fragment ready for fixup prior to and after insertion into DOM
257                         var content = fragClone.nodeType === 11 ?
258                                 jQuery.makeArray(fragClone.childNodes) :
259                                 fragClone.nodeType === 1 ? [fragClone] : [];
260
261                         // Return fragment to original caller (e.g. append) for DOM insertion
262                         callback.call( elem, fragClone );
263
264                         // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
265                         storeTmplItems( content );
266                         cloneIndex++;
267                 }
268         });
269
270         //========================== Private helper functions, used by code above ==========================
271
272         function build( tmplItem, nested, content ) {
273                 // Convert hierarchical content into flat string array 
274                 // and finally return array of fragments ready for DOM insertion
275                 var frag, ret = content ? jQuery.map( content, function( item ) {
276                         return (typeof item === "string") ? 
277                                 // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
278                                 (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) :
279                                 // This is a child template item. Build nested template.
280                                 build( item, tmplItem, item._ctnt );
281                 }) : 
282                 // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. 
283                 tmplItem;
284                 if ( nested ) {
285                         return ret;
286                 }
287
288                 // top-level template
289                 ret = ret.join("");
290
291                 // Support templates which have initial or final text nodes, or consist only of text
292                 // Also support HTML entities within the HTML markup.
293                 ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) {
294                         frag = jQuery( middle ).get();
295
296                         storeTmplItems( frag );
297                         if ( before ) {
298                                 frag = unencode( before ).concat(frag);
299                         }
300                         if ( after ) {
301                                 frag = frag.concat(unencode( after ));
302                         }
303                 });
304                 return frag ? frag : unencode( ret );
305         }
306
307         function unencode( text ) {
308                 // Use createElement, since createTextNode will not render HTML entities correctly
309                 var el = document.createElement( "div" );
310                 el.innerHTML = text;
311                 return jQuery.makeArray(el.childNodes);
312         }
313
314         // Generate a reusable function that will serve to render a template against data
315         function buildTmplFn( markup ) {
316                 return new Function("jQuery","$item",
317                         "var $=jQuery,call,_=[],$data=$item.data;" +
318
319                         // Introduce the data as local variables using with(){}
320                         "with($data){_.push('" +
321
322                         // Convert the template into pure JavaScript
323                         jQuery.trim(markup)
324                                 .replace( /([\\'])/g, "\\$1" )
325                                 .replace( /[\r\t\n]/g, " " )
326                                 .replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
327                                 .replace( /\{\{(\/?)(\w+|.)(?:\(((?:.(?!\}\}))*?)?\))?(?:\s+(.*?)?)?(\((.*?)\))?\s*\}\}/g,
328                                 function( all, slash, type, fnargs, target, parens, args ) {
329                                         var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect;
330                                         if ( !tag ) {
331                                                 throw "Template command not found: " + type;
332                                         }
333                                         def = tag._default || [];
334                                         if ( parens && !/\w$/.test(target)) {
335                                                 target += parens;
336                                                 parens = "";
337                                         }
338                                         if ( target ) {
339                                                 target = unescape( target ); 
340                                                 args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : "");
341                                                 // Support for target being things like a.toLowerCase();
342                                                 // In that case don't call with template item as 'this' pointer. Just evaluate...
343                                                 expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target;
344                                                 exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
345                                         } else {
346                                                 exprAutoFnDetect = expr = def.$1 || "null";
347                                         }
348                                         fnargs = unescape( fnargs );
349                                         return "');" + 
350                                                 tag[ slash ? "close" : "open" ]
351                                                         .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" )
352                                                         .split( "$1a" ).join( exprAutoFnDetect )
353                                                         .split( "$1" ).join( expr )
354                                                         .split( "$2" ).join( fnargs ?
355                                                                 fnargs.replace( /\s*([^\(]+)\s*(\((.*?)\))?/g, function( all, name, parens, params ) {
356                                                                         params = params ? ("," + params + ")") : (parens ? ")" : "");
357                                                                         return params ? ("(" + name + ").call($item" + params) : all;
358                                                                 })
359                                                                 : (def.$2||"")
360                                                         ) +
361                                                 "_.push('";
362                                 }) +
363                         "');}return _;"
364                 );
365         }
366         function updateWrapped( options, wrapped ) {
367                 // Build the wrapped content. 
368                 options._wrap = build( options, true, 
369                         // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
370                         jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()]
371                 ).join("");
372         }
373
374         function unescape( args ) {
375                 return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
376         }
377         function outerHtml( elem ) {
378                 var div = document.createElement("div");
379                 div.appendChild( elem.cloneNode(true) );
380                 return div.innerHTML;
381         }
382
383         // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
384         function storeTmplItems( content ) {
385                 var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
386                 for ( i = 0, l = content.length; i < l; i++ ) {
387                         if ( (elem = content[i]).nodeType !== 1 ) {
388                                 continue;
389                         }
390                         elems = elem.getElementsByTagName("*");
391                         for ( m = elems.length - 1; m >= 0; m-- ) {
392                                 processItemKey( elems[m] );
393                         }
394                         processItemKey( elem );
395                 }
396                 function processItemKey( el ) {
397                         var pntKey, pntNode = el, pntItem, tmplItem, key;
398                         // Ensure that each rendered template inserted into the DOM has its own template item,
399                         if ( (key = el.getAttribute( tmplItmAtt ))) {
400                                 while ((pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { }
401                                 if ( pntKey !== key ) {
402                                         // The next ancestor with a _tmplitem expando is on a different key than this one.
403                                         // So this is a top-level element within this template item
404                                         pntNode = pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0);
405                                         if ( !(tmplItem = newTmplItems[key]) ) {
406                                                 // The item is for wrapped content, and was copied from the temporary parent wrappedItem.
407                                                 tmplItem = wrappedItems[key];
408                                                 tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode], null, true );
409                                                 tmplItem.key = ++itemKey;
410                                                 newTmplItems[itemKey] = tmplItem;
411                                         }
412                                         if ( cloneIndex ) {
413                                                 cloneTmplItem( key );
414                                         }
415                                 }
416                                 el.removeAttribute( tmplItmAtt );
417                         } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) {
418                                 // This was a rendered element, cloned during append or appendTo etc.
419                                 // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
420                                 cloneTmplItem( tmplItem.key );
421                                 newTmplItems[tmplItem.key] = tmplItem;
422                                 pntNode = jQuery.data( el.parentNode, "tmplItem" );
423                                 pntNode = pntNode ? pntNode.key : 0;
424                         }
425                         if ( tmplItem ) {
426                                 pntItem = tmplItem;
427                                 // Find the template item of the parent element. 
428                                 // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
429                                 while ( pntItem && pntItem.key != pntNode ) { 
430                                         // Add this element as a top-level node for this rendered template item, as well as for any
431                                         // ancestor items between this item and the item of its parent element
432                                         pntItem.nodes.push( el );
433                                         pntItem = pntItem.parent;
434                                 }
435                                 // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
436                                 delete tmplItem._ctnt;
437                                 delete tmplItem._wrap;
438                                 // Store template item as jQuery data on the element
439                                 jQuery.data( el, "tmplItem", tmplItem );
440                         }
441                         function cloneTmplItem( key ) {
442                                 key = key + keySuffix;
443                                 tmplItem = newClonedItems[key] = 
444                                         (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true ));
445                         }
446                 }
447         }
448
449         //---- Helper functions for template item ----
450
451         function tiCalls( content, tmpl, data, options ) {
452                 if ( !content ) {
453                         return stack.pop();
454                 }
455                 stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
456         }
457
458         function tiNest( tmpl, data, options ) {
459                 // nested template, using {{tmpl}} tag
460                 return jQuery.tmpl( jQuery.template( tmpl ), data, options, this );
461         }
462
463         function tiWrap( call, wrapped ) {
464                 // nested template, using {{wrap}} tag
465                 var options = call.options || {};
466                 options.wrapped = wrapped;
467                 // Apply the template, which may incorporate wrapped content, 
468                 return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item );
469         }
470
471         function tiHtml( filter, textOnly ) {
472                 var wrapped = this._wrap;
473                 return jQuery.map(
474                         jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ),
475                         function(e) {
476                                 return textOnly ?
477                                         e.innerText || e.textContent :
478                                         e.outerHTML || outerHtml(e);
479                         });
480         }
481
482         function tiUpdate() {
483                 var coll = this.nodes;
484                 jQuery.tmpl( null, null, null, this).insertBefore( coll[0] );
485                 jQuery( coll ).remove();
486         }
487 })( jQuery );