Home | History | Annotate | Download | only in jst
      1 // Copyright 2006 Google Inc.
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 // http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
     12 // implied. See the License for the specific language governing
     13 // permissions and limitations under the License.
     14 /**
     15  * Author: Steffen Meschkat <mesch (a] google.com>
     16  *
     17  * @fileoverview A simple formatter to project JavaScript data into
     18  * HTML templates. The template is edited in place. I.e. in order to
     19  * instantiate a template, clone it from the DOM first, and then
     20  * process the cloned template. This allows for updating of templates:
     21  * If the templates is processed again, changed values are merely
     22  * updated.
     23  *
     24  * NOTE(mesch): IE DOM doesn't have importNode().
     25  *
     26  * NOTE(mesch): The property name "length" must not be used in input
     27  * data, see comment in jstSelect_().
     28  */
     29 
     30 
     31 /**
     32  * Names of jstemplate attributes. These attributes are attached to
     33  * normal HTML elements and bind expression context data to the HTML
     34  * fragment that is used as template.
     35  */
     36 var ATT_select = 'jsselect';
     37 var ATT_instance = 'jsinstance';
     38 var ATT_display = 'jsdisplay';
     39 var ATT_values = 'jsvalues';
     40 var ATT_vars = 'jsvars';
     41 var ATT_eval = 'jseval';
     42 var ATT_transclude = 'transclude';
     43 var ATT_content = 'jscontent';
     44 var ATT_skip = 'jsskip';
     45 
     46 
     47 /**
     48  * Name of the attribute that caches a reference to the parsed
     49  * template processing attribute values on a template node.
     50  */
     51 var ATT_jstcache = 'jstcache';
     52 
     53 
     54 /**
     55  * Name of the property that caches the parsed template processing
     56  * attribute values on a template node.
     57  */
     58 var PROP_jstcache = '__jstcache';
     59 
     60 
     61 /**
     62  * ID of the element that contains dynamically loaded jstemplates.
     63  */
     64 var STRING_jsts = 'jsts';
     65 
     66 
     67 /**
     68  * Un-inlined string literals, to avoid object creation in
     69  * IE6.
     70  */
     71 var CHAR_asterisk = '*';
     72 var CHAR_dollar = '$';
     73 var CHAR_period = '.';
     74 var CHAR_ampersand = '&';
     75 var STRING_div = 'div';
     76 var STRING_id = 'id';
     77 var STRING_asteriskzero = '*0';
     78 var STRING_zero = '0';
     79 
     80 
     81 /**
     82  * HTML template processor. Data values are bound to HTML templates
     83  * using the attributes transclude, jsselect, jsdisplay, jscontent,
     84  * jsvalues. The template is modifed in place. The values of those
     85  * attributes are JavaScript expressions that are evaluated in the
     86  * context of the data object fragment.
     87  *
     88  * @param {JsEvalContext} context Context created from the input data
     89  * object.
     90  *
     91  * @param {Element} template DOM node of the template. This will be
     92  * processed in place. After processing, it will still be a valid
     93  * template that, if processed again with the same data, will remain
     94  * unchanged.
     95  *
     96  * @param {boolean} opt_debugging Optional flag to collect debugging
     97  *     information while processing the template.  Only takes effect
     98  *     in MAPS_DEBUG.
     99  */
    100 function jstProcess(context, template, opt_debugging) {
    101   var processor = new JstProcessor;
    102   if (MAPS_DEBUG && opt_debugging) {
    103     processor.setDebugging(opt_debugging);
    104   }
    105   JstProcessor.prepareTemplate_(template);
    106 
    107   /**
    108    * Caches the document of the template node, so we don't have to
    109    * access it through ownerDocument.
    110    * @type Document
    111    */
    112   processor.document_ = ownerDocument(template);
    113 
    114   processor.run_(bindFully(processor, processor.jstProcessOuter_,
    115                            context, template));
    116   if (MAPS_DEBUG && opt_debugging) {
    117     log('jstProcess:' + '\n' + processor.getLogs().join('\n'));
    118   }
    119 }
    120 
    121 
    122 /**
    123  * Internal class used by jstemplates to maintain context.  This is
    124  * necessary to process deep templates in Safari which has a
    125  * relatively shallow maximum recursion depth of 100.
    126  * @class
    127  * @constructor
    128  */
    129 function JstProcessor() {
    130   if (MAPS_DEBUG) {
    131     /**
    132      * An array of logging messages.  These are collected during processing
    133      * and dumped to the console at the end.
    134      * @type Array.<string>
    135      */
    136     this.logs_ = [];
    137   }
    138 }
    139 
    140 
    141 /**
    142  * Counter to generate node ids. These ids will be stored in
    143  * ATT_jstcache and be used to lookup the preprocessed js attributes
    144  * from the jstcache_. The id is stored in an attribute so it
    145  * suvives cloneNode() and thus cloned template nodes can share the
    146  * same cache entry.
    147  * @type number
    148  */
    149 JstProcessor.jstid_ = 0;
    150 
    151 
    152 /**
    153  * Map from jstid to processed js attributes.
    154  * @type Object
    155  */
    156 JstProcessor.jstcache_ = {};
    157 
    158 /**
    159  * The neutral cache entry. Used for all nodes that don't have any
    160  * jst attributes. We still set the jsid attribute on those nodes so
    161  * we can avoid to look again for all the other jst attributes that
    162  * aren't there. Remember: not only the processing of the js
    163  * attribute values is expensive and we thus want to cache it. The
    164  * access to the attributes on the Node in the first place is
    165  * expensive too.
    166  */
    167 JstProcessor.jstcache_[0] = {};
    168 
    169 
    170 /**
    171  * Map from concatenated attribute string to jstid.
    172  * The key is the concatenation of all jst atributes found on a node
    173  * formatted as "name1=value1&name2=value2&...", in the order defined by
    174  * JST_ATTRIBUTES. The value is the id of the jstcache_ entry that can
    175  * be used for this node. This allows the reuse of cache entries in cases
    176  * when a cached entry already exists for a given combination of attribute
    177  * values. (For example when two different nodes in a template share the same
    178  * JST attributes.)
    179  * @type Object
    180  */
    181 JstProcessor.jstcacheattributes_ = {};
    182 
    183 
    184 /**
    185  * Map for storing temporary attribute values in prepareNode_() so they don't
    186  * have to be retrieved twice. (IE6 perf)
    187  * @type Object
    188  */
    189 JstProcessor.attributeValues_ = {};
    190 
    191 
    192 /**
    193  * A list for storing non-empty attributes found on a node in prepareNode_().
    194  * The array is global since it can be reused - this way there is no need to
    195  * construct a new array object for each invocation. (IE6 perf)
    196  * @type Array
    197  */
    198 JstProcessor.attributeList_ = [];
    199 
    200 
    201 /**
    202  * Prepares the template: preprocesses all jstemplate attributes.
    203  *
    204  * @param {Element} template
    205  */
    206 JstProcessor.prepareTemplate_ = function(template) {
    207   if (!template[PROP_jstcache]) {
    208     domTraverseElements(template, function(node) {
    209       JstProcessor.prepareNode_(node);
    210     });
    211   }
    212 };
    213 
    214 
    215 /**
    216  * A list of attributes we use to specify jst processing instructions,
    217  * and the functions used to parse their values.
    218  *
    219  * @type Array.<Array>
    220  */
    221 var JST_ATTRIBUTES = [
    222     [ ATT_select, jsEvalToFunction ],
    223     [ ATT_display, jsEvalToFunction ],
    224     [ ATT_values, jsEvalToValues ],
    225     [ ATT_vars, jsEvalToValues ],
    226     [ ATT_eval, jsEvalToExpressions ],
    227     [ ATT_transclude, jsEvalToSelf ],
    228     [ ATT_content, jsEvalToFunction ],
    229     [ ATT_skip, jsEvalToFunction ]
    230 ];
    231 
    232 
    233 /**
    234  * Prepares a single node: preprocesses all template attributes of the
    235  * node, and if there are any, assigns a jsid attribute and stores the
    236  * preprocessed attributes under the jsid in the jstcache.
    237  *
    238  * @param {Element} node
    239  *
    240  * @return {Object} The jstcache entry. The processed jst attributes
    241  * are properties of this object. If the node has no jst attributes,
    242  * returns an object with no properties (the jscache_[0] entry).
    243  */
    244 JstProcessor.prepareNode_ = function(node) {
    245   // If the node already has a cache property, return it.
    246   if (node[PROP_jstcache]) {
    247     return node[PROP_jstcache];
    248   }
    249 
    250   // If it is not found, we always set the PROP_jstcache property on the node.
    251   // Accessing the property is faster than executing getAttribute(). If we
    252   // don't find the property on a node that was cloned in jstSelect_(), we
    253   // will fall back to check for the attribute and set the property
    254   // from cache.
    255 
    256   // If the node has an attribute indexing a cache object, set it as a property
    257   // and return it.
    258   var jstid = domGetAttribute(node, ATT_jstcache);
    259   if (jstid != null) {
    260     return node[PROP_jstcache] = JstProcessor.jstcache_[jstid];
    261   }
    262 
    263   var attributeValues = JstProcessor.attributeValues_;
    264   var attributeList = JstProcessor.attributeList_;
    265   attributeList.length = 0;
    266 
    267   // Look for interesting attributes.
    268   for (var i = 0, I = jsLength(JST_ATTRIBUTES); i < I; ++i) {
    269     var name = JST_ATTRIBUTES[i][0];
    270     var value = domGetAttribute(node, name);
    271     attributeValues[name] = value;
    272     if (value != null) {
    273       attributeList.push(name + "=" + value);
    274     }
    275   }
    276 
    277   // If none found, mark this node to prevent further inspection, and return
    278   // an empty cache object.
    279   if (attributeList.length == 0) {
    280     domSetAttribute(node, ATT_jstcache, STRING_zero);
    281     return node[PROP_jstcache] = JstProcessor.jstcache_[0];
    282   }
    283 
    284   // If we already have a cache object corresponding to these attributes,
    285   // annotate the node with it, and return it.
    286   var attstring = attributeList.join(CHAR_ampersand);
    287   if (jstid = JstProcessor.jstcacheattributes_[attstring]) {
    288     domSetAttribute(node, ATT_jstcache, jstid);
    289     return node[PROP_jstcache] = JstProcessor.jstcache_[jstid];
    290   }
    291 
    292   // Otherwise, build a new cache object.
    293   var jstcache = {};
    294   for (var i = 0, I = jsLength(JST_ATTRIBUTES); i < I; ++i) {
    295     var att = JST_ATTRIBUTES[i];
    296     var name = att[0];
    297     var parse = att[1];
    298     var value = attributeValues[name];
    299     if (value != null) {
    300       jstcache[name] = parse(value);
    301       if (MAPS_DEBUG) {
    302         jstcache.jstAttributeValues = jstcache.jstAttributeValues || {};
    303         jstcache.jstAttributeValues[name] = value;
    304       }
    305     }
    306   }
    307 
    308   jstid = STRING_empty + ++JstProcessor.jstid_;
    309   domSetAttribute(node, ATT_jstcache, jstid);
    310   JstProcessor.jstcache_[jstid] = jstcache;
    311   JstProcessor.jstcacheattributes_[attstring] = jstid;
    312 
    313   return node[PROP_jstcache] = jstcache;
    314 };
    315 
    316 
    317 /**
    318  * Runs the given function in our state machine.
    319  *
    320  * It's informative to view the set of all function calls as a tree:
    321  * - nodes are states
    322  * - edges are state transitions, implemented as calls to the pending
    323  *   functions in the stack.
    324  *   - pre-order function calls are downward edges (recursion into call).
    325  *   - post-order function calls are upward edges (return from call).
    326  * - leaves are nodes which do not recurse.
    327  * We represent the call tree as an array of array of calls, indexed as
    328  * stack[depth][index].  Here [depth] indexes into the call stack, and
    329  * [index] indexes into the call queue at that depth.  We require a call
    330  * queue so that a node may branch to more than one child
    331  * (which will be called serially), typically due to a loop structure.
    332  *
    333  * @param {Function} f The first function to run.
    334  */
    335 JstProcessor.prototype.run_ = function(f) {
    336   var me = this;
    337 
    338   /**
    339    * A stack of queues of pre-order calls.
    340    * The inner arrays (constituent queues) are structured as
    341    * [ arg2, arg1, method, arg2, arg1, method, ...]
    342    * ie. a flattened array of methods with 2 arguments, in reverse order
    343    * for efficient push/pop.
    344    *
    345    * The outer array is a stack of such queues.
    346    *
    347    * @type Array.<Array>
    348    */
    349   var calls = me.calls_ = [];
    350 
    351   /**
    352    * The index into the queue for each depth. NOTE: Alternative would
    353    * be to maintain the queues in reverse order (popping off of the
    354    * end) but the repeated calls to .pop() consumed 90% of this
    355    * function's execution time.
    356    * @type Array.<number>
    357    */
    358   var queueIndices = me.queueIndices_ = [];
    359 
    360   /**
    361    * A pool of empty arrays.  Minimizes object allocation for IE6's benefit.
    362    * @type Array.<Array>
    363    */
    364   var arrayPool = me.arrayPool_ = [];
    365 
    366   f();
    367   var queue, queueIndex;
    368   var method, arg1, arg2;
    369   var temp;
    370   while (calls.length) {
    371     queue = calls[calls.length - 1];
    372     queueIndex = queueIndices[queueIndices.length - 1];
    373     if (queueIndex >= queue.length) {
    374       me.recycleArray_(calls.pop());
    375       queueIndices.pop();
    376       continue;
    377     }
    378 
    379     // Run the first function in the queue.
    380     method = queue[queueIndex++];
    381     arg1 = queue[queueIndex++];
    382     arg2 = queue[queueIndex++];
    383     queueIndices[queueIndices.length - 1] = queueIndex;
    384     method.call(me, arg1, arg2);
    385   }
    386 };
    387 
    388 
    389 /**
    390  * Pushes one or more functions onto the stack.  These will be run in sequence,
    391  * interspersed with any recursive calls that they make.
    392  *
    393  * This method takes ownership of the given array!
    394  *
    395  * @param {Array} args Array of method calls structured as
    396  *     [ method, arg1, arg2, method, arg1, arg2, ... ]
    397  */
    398 JstProcessor.prototype.push_ = function(args) {
    399   this.calls_.push(args);
    400   this.queueIndices_.push(0);
    401 };
    402 
    403 
    404 /**
    405  * Enable/disable debugging.
    406  * @param {boolean} debugging New state
    407  */
    408 JstProcessor.prototype.setDebugging = function(debugging) {
    409   if (MAPS_DEBUG) {
    410     this.debugging_ = debugging;
    411   }
    412 };
    413 
    414 
    415 JstProcessor.prototype.createArray_ = function() {
    416   if (this.arrayPool_.length) {
    417     return this.arrayPool_.pop();
    418   } else {
    419     return [];
    420   }
    421 };
    422 
    423 
    424 JstProcessor.prototype.recycleArray_ = function(array) {
    425   arrayClear(array);
    426   this.arrayPool_.push(array);
    427 };
    428 
    429 /**
    430  * Implements internals of jstProcess. This processes the two
    431  * attributes transclude and jsselect, which replace or multiply
    432  * elements, hence the name "outer". The remainder of the attributes
    433  * is processed in jstProcessInner_(), below. That function
    434  * jsProcessInner_() only processes attributes that affect an existing
    435  * node, but doesn't create or destroy nodes, hence the name
    436  * "inner". jstProcessInner_() is called through jstSelect_() if there
    437  * is a jsselect attribute (possibly for newly created clones of the
    438  * current template node), or directly from here if there is none.
    439  *
    440  * @param {JsEvalContext} context
    441  *
    442  * @param {Element} template
    443  */
    444 JstProcessor.prototype.jstProcessOuter_ = function(context, template) {
    445   var me = this;
    446 
    447   var jstAttributes = me.jstAttributes_(template);
    448   if (MAPS_DEBUG && me.debugging_) {
    449     me.logState_('Outer', template, jstAttributes.jstAttributeValues);
    450   }
    451 
    452   var transclude = jstAttributes[ATT_transclude];
    453   if (transclude) {
    454     var tr = jstGetTemplate(transclude);
    455     if (tr) {
    456       domReplaceChild(tr, template);
    457       var call = me.createArray_();
    458       call.push(me.jstProcessOuter_, context, tr);
    459       me.push_(call);
    460     } else {
    461       domRemoveNode(template);
    462     }
    463     return;
    464   }
    465 
    466   var select = jstAttributes[ATT_select];
    467   if (select) {
    468     me.jstSelect_(context, template, select);
    469   } else {
    470     me.jstProcessInner_(context, template);
    471   }
    472 };
    473 
    474 
    475 /**
    476  * Implements internals of jstProcess. This processes all attributes
    477  * except transclude and jsselect. It is called either from
    478  * jstSelect_() for nodes that have a jsselect attribute so that the
    479  * jsselect attribute will not be processed again, or else directly
    480  * from jstProcessOuter_(). See the comment on jstProcessOuter_() for
    481  * an explanation of the name.
    482  *
    483  * @param {JsEvalContext} context
    484  *
    485  * @param {Element} template
    486  */
    487 JstProcessor.prototype.jstProcessInner_ = function(context, template) {
    488   var me = this;
    489 
    490   var jstAttributes = me.jstAttributes_(template);
    491   if (MAPS_DEBUG && me.debugging_) {
    492     me.logState_('Inner', template, jstAttributes.jstAttributeValues);
    493   }
    494 
    495   // NOTE(mesch): See NOTE on ATT_content why this is a separate
    496   // attribute, and not a special value in ATT_values.
    497   var display = jstAttributes[ATT_display];
    498   if (display) {
    499     var shouldDisplay = context.jsexec(display, template);
    500     if (MAPS_DEBUG && me.debugging_) {
    501       me.logs_.push(ATT_display + ': ' + shouldDisplay + '<br/>');
    502     }
    503     if (!shouldDisplay) {
    504       displayNone(template);
    505       return;
    506     }
    507     displayDefault(template);
    508   }
    509 
    510   // NOTE(mesch): jsvars is evaluated before jsvalues, because it's
    511   // more useful to be able to use var values in attribute value
    512   // expressions than vice versa.
    513   var values = jstAttributes[ATT_vars];
    514   if (values) {
    515     me.jstVars_(context, template, values);
    516   }
    517 
    518   values = jstAttributes[ATT_values];
    519   if (values) {
    520     me.jstValues_(context, template, values);
    521   }
    522 
    523   // Evaluate expressions immediately. Useful for hooking callbacks
    524   // into jstemplates.
    525   //
    526   // NOTE(mesch): Evaluation order is sometimes significant, e.g. when
    527   // the expression evaluated in jseval relies on the values set in
    528   // jsvalues, so it needs to be evaluated *after*
    529   // jsvalues. TODO(mesch): This is quite arbitrary, it would be
    530   // better if this would have more necessity to it.
    531   var expressions = jstAttributes[ATT_eval];
    532   if (expressions) {
    533     for (var i = 0, I = jsLength(expressions); i < I; ++i) {
    534       context.jsexec(expressions[i], template);
    535     }
    536   }
    537 
    538   var skip = jstAttributes[ATT_skip];
    539   if (skip) {
    540     var shouldSkip = context.jsexec(skip, template);
    541     if (MAPS_DEBUG && me.debugging_) {
    542       me.logs_.push(ATT_skip + ': ' + shouldSkip + '<br/>');
    543     }
    544     if (shouldSkip) return;
    545   }
    546 
    547   // NOTE(mesch): content is a separate attribute, instead of just a
    548   // special value mentioned in values, for two reasons: (1) it is
    549   // fairly common to have only mapped content, and writing
    550   // content="expr" is shorter than writing values="content:expr", and
    551   // (2) the presence of content actually terminates traversal, and we
    552   // need to check for that. Display is a separate attribute for a
    553   // reason similar to the second, in that its presence *may*
    554   // terminate traversal.
    555   var content = jstAttributes[ATT_content];
    556   if (content) {
    557     me.jstContent_(context, template, content);
    558 
    559   } else {
    560     // Newly generated children should be ignored, so we explicitly
    561     // store the children to be processed.
    562     var queue = me.createArray_();
    563     for (var c = template.firstChild; c; c = c.nextSibling) {
    564       if (c.nodeType == DOM_ELEMENT_NODE) {
    565         queue.push(me.jstProcessOuter_, context, c);
    566       }
    567     }
    568     if (queue.length) me.push_(queue);
    569   }
    570 };
    571 
    572 
    573 /**
    574  * Implements the jsselect attribute: evalutes the value of the
    575  * jsselect attribute in the current context, with the current
    576  * variable bindings (see JsEvalContext.jseval()). If the value is an
    577  * array, the current template node is multiplied once for every
    578  * element in the array, with the array element being the context
    579  * object. If the array is empty, or the value is undefined, then the
    580  * current template node is dropped. If the value is not an array,
    581  * then it is just made the context object.
    582  *
    583  * @param {JsEvalContext} context The current evaluation context.
    584  *
    585  * @param {Element} template The currently processed node of the template.
    586  *
    587  * @param {Function} select The javascript expression to evaluate.
    588  *
    589  * @notypecheck FIXME(hmitchell): See OCL6434950. instance and value need
    590  * type checks.
    591  */
    592 JstProcessor.prototype.jstSelect_ = function(context, template, select) {
    593   var me = this;
    594 
    595   var value = context.jsexec(select, template);
    596 
    597   // Enable reprocessing: if this template is reprocessed, then only
    598   // fill the section instance here. Otherwise do the cardinal
    599   // processing of a new template.
    600   var instance = domGetAttribute(template, ATT_instance);
    601 
    602   var instanceLast = false;
    603   if (instance) {
    604     if (instance.charAt(0) == CHAR_asterisk) {
    605       instance = parseInt10(instance.substr(1));
    606       instanceLast = true;
    607     } else {
    608       instance = parseInt10(/** @type string */(instance));
    609     }
    610   }
    611 
    612   // The expression value instanceof Array is occasionally false for
    613   // arrays, seen in Firefox. Thus we recognize an array as an object
    614   // which is not null that has a length property. Notice that this
    615   // also matches input data with a length property, so this property
    616   // name should be avoided in input data.
    617   var multiple = isArray(value);
    618   var count = multiple ? jsLength(value) : 1;
    619   var multipleEmpty = (multiple && count == 0);
    620 
    621   if (multiple) {
    622     if (multipleEmpty) {
    623       // For an empty array, keep the first template instance and mark
    624       // it last. Remove all other template instances.
    625       if (!instance) {
    626         domSetAttribute(template, ATT_instance, STRING_asteriskzero);
    627         displayNone(template);
    628       } else {
    629         domRemoveNode(template);
    630       }
    631 
    632     } else {
    633       displayDefault(template);
    634       // For a non empty array, create as many template instances as
    635       // are needed. If the template is first processed, as many
    636       // template instances are needed as there are values in the
    637       // array. If the template is reprocessed, new template instances
    638       // are only needed if there are more array values than template
    639       // instances. Those additional instances are created by
    640       // replicating the last template instance.
    641       //
    642       // When the template is first processed, there is no jsinstance
    643       // attribute. This is indicated by instance === null, except in
    644       // opera it is instance === "". Notice also that the === is
    645       // essential, because 0 == "", presumably via type coercion to
    646       // boolean.
    647       if (instance === null || instance === STRING_empty ||
    648           (instanceLast && instance < count - 1)) {
    649         // A queue of calls to push.
    650         var queue = me.createArray_();
    651 
    652         var instancesStart = instance || 0;
    653         var i, I, clone;
    654         for (i = instancesStart, I = count - 1; i < I; ++i) {
    655           var node = domCloneNode(template);
    656           domInsertBefore(node, template);
    657 
    658           jstSetInstance(/** @type Element */(node), value, i);
    659           clone = context.clone(value[i], i, count);
    660 
    661           queue.push(me.jstProcessInner_, clone, node,
    662                      JsEvalContext.recycle, clone, null);
    663                      
    664         }
    665         // Push the originally present template instance last to keep
    666         // the order aligned with the DOM order, because the newly
    667         // created template instances are inserted *before* the
    668         // original instance.
    669         jstSetInstance(template, value, i);
    670         clone = context.clone(value[i], i, count);
    671         queue.push(me.jstProcessInner_, clone, template,
    672                    JsEvalContext.recycle, clone, null);
    673         me.push_(queue);
    674       } else if (instance < count) {
    675         var v = value[instance];
    676 
    677         jstSetInstance(template, value, instance);
    678         var clone = context.clone(v, instance, count);
    679         var queue = me.createArray_();
    680         queue.push(me.jstProcessInner_, clone, template,
    681                    JsEvalContext.recycle, clone, null);
    682         me.push_(queue);
    683       } else {
    684         domRemoveNode(template);
    685       }
    686     }
    687   } else {
    688     if (value == null) {
    689       displayNone(template);
    690     } else {
    691       displayDefault(template);
    692       var clone = context.clone(value, 0, 1);
    693       var queue = me.createArray_();
    694       queue.push(me.jstProcessInner_, clone, template,
    695                  JsEvalContext.recycle, clone, null);
    696       me.push_(queue);
    697     }
    698   }
    699 };
    700 
    701 
    702 /**
    703  * Implements the jsvars attribute: evaluates each of the values and
    704  * assigns them to variables in the current context. Similar to
    705  * jsvalues, except that all values are treated as vars, independent
    706  * of their names.
    707  *
    708  * @param {JsEvalContext} context Current evaluation context.
    709  *
    710  * @param {Element} template Currently processed template node.
    711  *
    712  * @param {Array} values Processed value of the jsvalues attribute: a
    713  * flattened array of pairs. The second element in the pair is a
    714  * function that can be passed to jsexec() for evaluation in the
    715  * current jscontext, and the first element is the variable name that
    716  * the value returned by jsexec is assigned to.
    717  */
    718 JstProcessor.prototype.jstVars_ = function(context, template, values) {
    719   for (var i = 0, I = jsLength(values); i < I; i += 2) {
    720     var label = values[i];
    721     var value = context.jsexec(values[i+1], template);
    722     context.setVariable(label, value);
    723   }
    724 };
    725 
    726 
    727 /**
    728  * Implements the jsvalues attribute: evaluates each of the values and
    729  * assigns them to variables in the current context (if the name
    730  * starts with '$', javascript properties of the current template node
    731  * (if the name starts with '.'), or DOM attributes of the current
    732  * template node (otherwise). Since DOM attribute values are always
    733  * strings, the value is coerced to string in the latter case,
    734  * otherwise it's the uncoerced javascript value.
    735  *
    736  * @param {JsEvalContext} context Current evaluation context.
    737  *
    738  * @param {Element} template Currently processed template node.
    739  *
    740  * @param {Array} values Processed value of the jsvalues attribute: a
    741  * flattened array of pairs. The second element in the pair is a
    742  * function that can be passed to jsexec() for evaluation in the
    743  * current jscontext, and the first element is the label that
    744  * determines where the value returned by jsexec is assigned to.
    745  */
    746 JstProcessor.prototype.jstValues_ = function(context, template, values) {
    747   for (var i = 0, I = jsLength(values); i < I; i += 2) {
    748     var label = values[i];
    749     var value = context.jsexec(values[i+1], template);
    750 
    751     if (label.charAt(0) == CHAR_dollar) {
    752       // A jsvalues entry whose name starts with $ sets a local
    753       // variable.
    754       context.setVariable(label, value);
    755 
    756     } else if (label.charAt(0) == CHAR_period) {
    757       // A jsvalues entry whose name starts with . sets a property of
    758       // the current template node. The name may have further dot
    759       // separated components, which are translated into namespace
    760       // objects. This specifically allows to set properties on .style
    761       // using jsvalues. NOTE(mesch): Setting the style attribute has
    762       // no effect in IE and hence should not be done anyway.
    763       var nameSpaceLabel = label.substr(1).split(CHAR_period);
    764       var nameSpaceObject = template;
    765       var nameSpaceDepth = jsLength(nameSpaceLabel);
    766       for (var j = 0, J = nameSpaceDepth - 1; j < J; ++j) {
    767         var jLabel = nameSpaceLabel[j];
    768         if (!nameSpaceObject[jLabel]) {
    769           nameSpaceObject[jLabel] = {};
    770         }
    771         nameSpaceObject = nameSpaceObject[jLabel];
    772       }
    773       nameSpaceObject[nameSpaceLabel[nameSpaceDepth - 1]] = value;
    774 
    775     } else if (label) {
    776       // Any other jsvalues entry sets an attribute of the current
    777       // template node.
    778       if (typeof value == TYPE_boolean) {
    779         // Handle boolean values that are set as attributes specially,
    780         // according to the XML/HTML convention.
    781         if (value) {
    782           domSetAttribute(template, label, label);
    783         } else {
    784           domRemoveAttribute(template, label);
    785         }
    786       } else {
    787         domSetAttribute(template, label, STRING_empty + value);
    788       }
    789     }
    790   }
    791 };
    792 
    793 
    794 /**
    795  * Implements the jscontent attribute. Evalutes the expression in
    796  * jscontent in the current context and with the current variables,
    797  * and assigns its string value to the content of the current template
    798  * node.
    799  *
    800  * @param {JsEvalContext} context Current evaluation context.
    801  *
    802  * @param {Element} template Currently processed template node.
    803  *
    804  * @param {Function} content Processed value of the jscontent
    805  * attribute.
    806  */
    807 JstProcessor.prototype.jstContent_ = function(context, template, content) {
    808   // NOTE(mesch): Profiling shows that this method costs significant
    809   // time. In jstemplate_perf.html, it's about 50%. I tried to replace
    810   // by HTML escaping and assignment to innerHTML, but that was even
    811   // slower.
    812   var value = STRING_empty + context.jsexec(content, template);
    813   // Prevent flicker when refreshing a template and the value doesn't
    814   // change.
    815   if (template.innerHTML == value) {
    816     return;
    817   }
    818   while (template.firstChild) {
    819     domRemoveNode(template.firstChild);
    820   }
    821   var t = domCreateTextNode(this.document_, value);
    822   domAppendChild(template, t);
    823 };
    824 
    825 
    826 /**
    827  * Caches access to and parsing of template processing attributes. If
    828  * domGetAttribute() is called every time a template attribute value
    829  * is used, it takes more than 10% of the time.
    830  *
    831  * @param {Element} template A DOM element node of the template.
    832  *
    833  * @return {Object} A javascript object that has all js template
    834  * processing attribute values of the node as properties.
    835  */
    836 JstProcessor.prototype.jstAttributes_ = function(template) {
    837   if (template[PROP_jstcache]) {
    838     return template[PROP_jstcache];
    839   }
    840 
    841   var jstid = domGetAttribute(template, ATT_jstcache);
    842   if (jstid) {
    843     return template[PROP_jstcache] = JstProcessor.jstcache_[jstid];
    844   }
    845 
    846   return JstProcessor.prepareNode_(template);
    847 };
    848 
    849 
    850 /**
    851  * Helps to implement the transclude attribute, and is the initial
    852  * call to get hold of a template from its ID.
    853  *
    854  * If the ID is not present in the DOM, and opt_loadHtmlFn is specified, this
    855  * function will call that function and add the result to the DOM, before
    856  * returning the template.
    857  *
    858  * @param {string} name The ID of the HTML element used as template.
    859  * @param {Function} opt_loadHtmlFn A function which, when called, will return
    860  *   HTML that contains an element whose ID is 'name'.
    861  *
    862  * @return {Element|null} The DOM node of the template. (Only element nodes
    863  * can be found by ID, hence it's a Element.)
    864  */
    865 function jstGetTemplate(name, opt_loadHtmlFn) {
    866   var doc = document;
    867   var section;
    868   if (opt_loadHtmlFn) {
    869     section = jstLoadTemplateIfNotPresent(doc, name, opt_loadHtmlFn);
    870   } else {
    871     section = domGetElementById(doc, name);
    872   }
    873   if (section) {
    874     JstProcessor.prepareTemplate_(section);
    875     var ret = domCloneElement(section);
    876     domRemoveAttribute(ret, STRING_id);
    877     return ret;
    878   } else {
    879     return null;
    880   }
    881 }
    882 
    883 /**
    884  * This function is the same as 'jstGetTemplate' but, if the template
    885  * does not exist, throw an exception.
    886  *
    887  * @param {string} name The ID of the HTML element used as template.
    888  * @param {Function} opt_loadHtmlFn A function which, when called, will return
    889  *   HTML that contains an element whose ID is 'name'.
    890  *
    891  * @return {Element} The DOM node of the template. (Only element nodes
    892  * can be found by ID, hence it's a Element.)
    893  */
    894 function jstGetTemplateOrDie(name, opt_loadHtmlFn) {
    895   var x = jstGetTemplate(name, opt_loadHtmlFn);
    896   check(x !== null);
    897   return /** @type Element */(x);
    898 }
    899 
    900 
    901 /**
    902  * If an element with id 'name' is not present in the document, call loadHtmlFn
    903  * and insert the result into the DOM.
    904  *
    905  * @param {Document} doc
    906  * @param {string} name
    907  * @param {Function} loadHtmlFn A function that returns HTML to be inserted
    908  * into the DOM.
    909  * @param {string} opt_target The id of a DOM object under which to attach the
    910  *   HTML once it's inserted.  An object with this id is created if it does not
    911  *   exist.
    912  * @return {Element} The node whose id is 'name'
    913  */
    914 function jstLoadTemplateIfNotPresent(doc, name, loadHtmlFn, opt_target) {
    915   var section = domGetElementById(doc, name);
    916   if (section) {
    917     return section;
    918   }
    919   // Load any necessary HTML and try again.
    920   jstLoadTemplate_(doc, loadHtmlFn(), opt_target || STRING_jsts);
    921   var section = domGetElementById(doc, name);
    922   if (!section) {
    923     log("Error: jstGetTemplate was provided with opt_loadHtmlFn, " +
    924 	"but that function did not provide the id '" + name + "'.");
    925   }
    926   return /** @type Element */(section);
    927 }
    928 
    929 
    930 /**
    931  * Loads the given HTML text into the given document, so that
    932  * jstGetTemplate can find it.
    933  *
    934  * We append it to the element identified by targetId, which is hidden.
    935  * If it doesn't exist, it is created.
    936  *
    937  * @param {Document} doc The document to create the template in.
    938  *
    939  * @param {string} html HTML text to be inserted into the document.
    940  *
    941  * @param {string} targetId The id of a DOM object under which to attach the
    942  *   HTML once it's inserted.  An object with this id is created if it does not
    943  *   exist.
    944  */
    945 function jstLoadTemplate_(doc, html, targetId) {
    946   var existing_target = domGetElementById(doc, targetId);
    947   var target;
    948   if (!existing_target) {
    949     target = domCreateElement(doc, STRING_div);
    950     target.id = targetId;
    951     displayNone(target);
    952     positionAbsolute(target);
    953     domAppendChild(doc.body, target);
    954   } else {
    955     target = existing_target;
    956   }
    957   var div = domCreateElement(doc, STRING_div);
    958   target.appendChild(div);
    959   div.innerHTML = html;
    960 }
    961 
    962 
    963 /**
    964  * Sets the jsinstance attribute on a node according to its context.
    965  *
    966  * @param {Element} template The template DOM node to set the instance
    967  * attribute on.
    968  *
    969  * @param {Array} values The current input context, the array of
    970  * values of which the template node will render one instance.
    971  *
    972  * @param {number} index The index of this template node in values.
    973  */
    974 function jstSetInstance(template, values, index) {
    975   if (index == jsLength(values) - 1) {
    976     domSetAttribute(template, ATT_instance, CHAR_asterisk + index);
    977   } else {
    978     domSetAttribute(template, ATT_instance, STRING_empty + index);
    979   }
    980 }
    981 
    982 
    983 /**
    984  * Log the current state.
    985  * @param {string} caller An identifier for the caller of .log_.
    986  * @param {Element} template The template node being processed.
    987  * @param {Object} jstAttributeValues The jst attributes of the template node.
    988  */
    989 JstProcessor.prototype.logState_ = function(
    990     caller, template, jstAttributeValues) {
    991   if (MAPS_DEBUG) {
    992     var msg = '<table>';
    993     msg += '<caption>' + caller + '</caption>';
    994     msg += '<tbody>';
    995     if (template.id) {
    996       msg += '<tr><td>' + 'id:' + '</td><td>' + template.id + '</td></tr>';
    997     }
    998     if (template.name) {
    999       msg += '<tr><td>' + 'name:' + '</td><td>' + template.name + '</td></tr>';
   1000     }
   1001     if (jstAttributeValues) {
   1002       msg += '<tr><td>' + 'attr:' +
   1003       '</td><td>' + jsToSource(jstAttributeValues) + '</td></tr>';
   1004     }
   1005     msg += '</tbody></table><br/>';
   1006     this.logs_.push(msg);
   1007   }
   1008 };
   1009 
   1010 
   1011 /**
   1012  * Retrieve the processing logs.
   1013  * @return {Array.<string>} The processing logs.
   1014  */
   1015 JstProcessor.prototype.getLogs = function() {
   1016   return this.logs_;
   1017 };
   1018 
   1019