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