Debian Codegraph @

dojox/dtl/dom.js

raw symbols SCIP
1 define([
2 "dojo/_base/lang",
3 "./_base",
4 "dojox/string/tokenize",
5 "./Context",
6 "dojo/dom",
7 "dojo/dom-construct",
8 "dojo/_base/html",
9 "dojo/_base/array",
10 "dojo/_base/connect",
11 "dojo/_base/sniff"
12 ], function(lang,dd,Tokenize,context,dom,domconstruct,html,array,connect,has){
13
14 dd.BOOLS = {checked: 1, disabled: 1, readonly: 1};
15 dd.TOKEN_CHANGE = -11;
16 dd.TOKEN_ATTR = -12;
17 dd.TOKEN_CUSTOM = -13;
18 dd.TOKEN_NODE = 1;
19
20 var ddt = dd.text;
21 var ddh = dd.dom = {
22 _attributes: {},
23 _uppers: {},
24 _re4: /^function anonymous\(\)\s*{\s*(.*)\s*}$/,
25 _reTrim: /(?:^[\n\s]*(\{%)?\s*|\s*(%\})?[\n\s]*$)/g,
26 _reSplit: /\s*%\}[\n\s]*\{%\s*/g,
27 getTemplate: function(text){
28 if(typeof this._commentable == "undefined"){
29 // Check to see if the browser can handle comments
30 this._commentable = false;
31 var div = document.createElement("div"), comment = "Test comment handling, and long comments, using comments whenever possible.";
32 div.innerHTML = "<!--" + comment + "-->";
33 if(div.childNodes.length && div.firstChild.nodeType == 8 && div.firstChild.data == comment){
34 this._commentable = true;
35 }
36 }
37
38 if(!this._commentable){
39 // Strip comments
40 text = text.replace(/<!--({({|%).*?(%|})})-->/g, "$1");
41 }
42
43 if(has("ie")){
44 text = text.replace(/\b(checked|disabled|readonly|style)="/g, 't$1="');
45 }
46 text = text.replace(/\bstyle="/g, 'tstyle="');
47
48 var match;
49 var table = has("webkit");
50 var pairs = [ // Format: [enable, parent, allowed children (first for nesting), nestings]
51 [true, "select", "option"],
52 [table, "tr", "td|th"],
53 [table, "thead", "tr", "th"],
54 [table, "tbody", "tr", "td"],
55 [table, "table", "tbody|thead|tr", "tr", "td"]
56 ];
57 var replacements = [];
58 // Some tags can't contain text. So we wrap the text in tags that they can have.
59 for(var i = 0, pair; pair = pairs[i]; i++){
60 if(!pair[0]){
61 continue;
62 }
63 if(text.indexOf("<" + pair[1]) != -1){
64 var selectRe = new RegExp("<" + pair[1] + "(?:.|\n)*?>((?:.|\n)+?)</" + pair[1] + ">", "ig");
65 tagLoop: while(match = selectRe.exec(text)){
66 // Do it like this to make sure we don't double-wrap
67 var inners = pair[2].split("|");
68 var innerRe = [];
69 for(var j = 0, inner; inner = inners[j]; j++){
70 innerRe.push("<" + inner + "(?:.|\n)*?>(?:.|\n)*?</" + inner + ">");
71 }
72 var tags = [];
73 var tokens = Tokenize(match[1], new RegExp("(" + innerRe.join("|") + ")", "ig"), function(data){
74 var tag = /<(\w+)/.exec(data)[1];
75 if(!tags[tag]){
76 tags[tag] = true;
77 tags.push(tag);
78 }
79 return {data: data};
80 });
81 if(tags.length){
82 var tag = (tags.length == 1) ? tags[0] : pair[2].split("|")[0];
83
84 var replace = [];
85 for(var j = 0, jl = tokens.length; j < jl; j++) {
86 var token = tokens[j];
87 if(lang.isObject(token)){
88 replace.push(token.data);
89 }else{
90 var stripped = token.replace(this._reTrim, "");
91 if(!stripped){ continue; }
92 token = stripped.split(this._reSplit);
93 for(var k = 0, kl = token.length; k < kl; k++){
94 var replacement = "";
95 for(var p = 2, pl = pair.length; p < pl; p++){
96 if(p == 2){
97 replacement += "<" + tag + ' dtlinstruction="{% ' + token[k].replace(/"/g, '\\"') + ' %}">';
98 }else if(tag == pair[p]) {
99 continue;
100 }else{
101 replacement += "<" + pair[p] + ">";
102 }
103 }
104 replacement += "DTL";
105 for(var p = pair.length - 1; p > 1; p--){
106 if(p == 2){
107 replacement += "</" + tag + ">";
108 }else if(tag == pair[p]) {
109 continue;
110 }else{
111 replacement += "</" + pair[p] + ">";
112 }
113 }
114 replace.push("\xFF" + replacements.length);
115 replacements.push(replacement);
116 }
117 }
118 }
119 text = text.replace(match[1], replace.join(""));
120 }
121 }
122 }
123 }
124
125 for(var i = replacements.length; i--;){
126 text = text.replace("\xFF" + i, replacements[i]);
127 }
128
129 var re = /\b([a-zA-Z_:][a-zA-Z0-9_\-\.:]*)=['"]/g;
130 while(match = re.exec(text)){
131 var lower = match[1].toLowerCase();
132 if(lower == "dtlinstruction"){ continue; }
133 if(lower != match[1]){
134 this._uppers[lower] = match[1];
135 }
136 this._attributes[lower] = true;
137 }
138 var div = document.createElement("div");
139 div.innerHTML = text;
140 var output = {nodes: []};
141 while(div.childNodes.length){
142 output.nodes.push(div.removeChild(div.childNodes[0]))
143 }
144
145 return output;
146 },
147 tokenize: function(/*Node*/ nodes){
148 var tokens = [];
149
150 for(var i = 0, node; node = nodes[i++];){
151 if(node.nodeType != 1){
152 this.__tokenize(node, tokens);
153 }else{
154 this._tokenize(node, tokens);
155 }
156 }
157
158 return tokens;
159 },
160 _swallowed: [],
161 _tokenize: function(/*Node*/ node, /*Array*/ tokens){
162 var first = false;
163 var swallowed = this._swallowed;
164 var i, j, tag, child;
165
166 if(!tokens.first){
167 // Try to efficiently associate tags that use an attribute to
168 // remove the node from DOM (eg dojoType) so that we can efficiently
169 // locate them later in the tokenizing.
170 first = tokens.first = true;
171 var tags = dd.register.getAttributeTags();
172 for(i = 0; tag = tags[i]; i++){
173 try{
174 (tag[2])({ swallowNode: function(){ throw 1; }}, new dd.Token(dd.TOKEN_ATTR, ""));
175 }catch(e){
176 swallowed.push(tag);
177 }
178 }
179 }
180
181 for(i = 0; tag = swallowed[i]; i++){
182 var text = node.getAttribute(tag[0]);
183 if(text){
184 var swallowed = false;
185 var custom = (tag[2])({ swallowNode: function(){ swallowed = true; return node; }}, new dd.Token(dd.TOKEN_ATTR, tag[0] + " " + text));
186 if(swallowed){
187 if(node.parentNode && node.parentNode.removeChild){
188 node.parentNode.removeChild(node);
189 }
190 tokens.push([dd.TOKEN_CUSTOM, custom]);
191 return;
192 }
193 }
194 }
195
196 var children = [];
197 if(has("ie") && node.tagName == "SCRIPT"){
198 children.push({
199 nodeType: 3,
200 data: node.text
201 });
202 node.text = "";
203 }else{
204 for(i = 0; child = node.childNodes[i]; i++){
205 children.push(child);
206 }
207 }
208
209 tokens.push([dd.TOKEN_NODE, node]);
210
211 var change = false;
212 if(children.length){
213 // Only do a change request if we need to
214 tokens.push([dd.TOKEN_CHANGE, node]);
215 change = true;
216 }
217
218 for(var key in this._attributes){
219 var clear = false;
220
221 var value = "";
222 if(key == "class"){
223 value = node.className || value;
224 }else if(key == "for"){
225 value = node.htmlFor || value;
226 }else if(node.getAttribute){
227 value = node.getAttribute(key, 2) || value;
228 if(key == "href" || key == "src"){
229 if(has("ie")){
230 var hash = location.href.lastIndexOf(location.hash);
231 var href = location.href.substring(0, hash).split("/");
232 href.pop();
233 href = href.join("/") + "/";
234 if(value.indexOf(href) == 0){
235 value = value.replace(href, "");
236 }
237 value = decodeURIComponent(value);
238 }
239 }else if(key == "tstyle"){
240 clear = key; // Placeholder because we can't use style
241 key = "style";
242 }else if(dd.BOOLS[key.slice(1)] && lang.trim(value)){
243 key = key.slice(1);
244 }else if(this._uppers[key] && lang.trim(value)){
245 clear = this._uppers[key]; // Replaced by lowercase
246 }
247 }
248
249 if(clear){
250 // Clear out values that are different than will
251 // be used in plugins
252 node.setAttribute(clear, "");
253 node.removeAttribute(clear);
254 }
255
256 if(typeof value == "function"){
257 value = value.toString().replace(this._re4, "$1");
258 }
259
260 if(!change){
261 // Only do a change request if we need to
262 tokens.push([dd.TOKEN_CHANGE, node]);
263 change = true;
264 }
265
266 // We'll have to resolve attributes during parsing (some ref plugins)
267
268 tokens.push([dd.TOKEN_ATTR, node, key, value]);
269 }
270
271 for(i = 0, child; child = children[i]; i++){
272 if(child.nodeType == 1){
273 var instruction = child.getAttribute("dtlinstruction");
274 if(instruction){
275 child.parentNode.removeChild(child);
276 child = {
277 nodeType: 8,
278 data: instruction
279 };
280 }
281 }
282 this.__tokenize(child, tokens);
283 }
284
285 if(!first && node.parentNode && node.parentNode.tagName){
286 if(change){
287 tokens.push([dd.TOKEN_CHANGE, node, true]);
288 }
289 tokens.push([dd.TOKEN_CHANGE, node.parentNode]);
290 node.parentNode.removeChild(node);
291 }else{
292 // If this node is parentless, it's a base node, so we have to "up" change to itself
293 // and note that it's a top-level to watch for errors
294 tokens.push([dd.TOKEN_CHANGE, node, true, true]);
295 }
296 },
297 __tokenize: function(child, tokens){
298 var data = child.data;
299 switch(child.nodeType){
300 case 1:
301 this._tokenize(child, tokens);
302 return;
303 case 3:
304 if(data.match(/[^\s\n]/) && (data.indexOf("{{") != -1 || data.indexOf("{%") != -1)){
305 var texts = ddt.tokenize(data);
306 for(var j = 0, text; text = texts[j]; j++){
307 if(typeof text == "string"){
308 tokens.push([dd.TOKEN_TEXT, text]);
309 }else{
310 tokens.push(text);
311 }
312 }
313 }else{
314 tokens.push([child.nodeType, child]);
315 }
316 if(child.parentNode) child.parentNode.removeChild(child);
317 return;
318 case 8:
319 if(data.indexOf("{%") == 0){
320 var text = lang.trim(data.slice(2, -2));
321 if(text.substr(0, 5) == "load "){
322 var parts = lang.trim(text).split(/\s+/g);
323 for(var i = 1, part; part = parts[i]; i++){
324 if (/\./.test(part)){
325 part = part.replace(/\./g,"/");
326 }
327 require([part]);
328 }
329 }
330 tokens.push([dd.TOKEN_BLOCK, text]);
331 }
332 if(data.indexOf("{{") == 0){
333 tokens.push([dd.TOKEN_VAR, lang.trim(data.slice(2, -2))]);
334 }
335 if(child.parentNode) child.parentNode.removeChild(child);
336 return;
337 }
338 }
339 };
340
341 dd.DomTemplate = lang.extend(function(/*String|DOMNode|dojo/Url*/ obj){
342 // summary:
343 // The template class for DOM templating.
344 if(!obj.nodes){
345 var node = dom.byId(obj);
346 if(node && node.nodeType == 1){
347 array.forEach(["class", "src", "href", "name", "value"], function(item){
348 ddh._attributes[item] = true;
349 });
350 obj = {
351 nodes: [node]
352 };
353 }else{
354 if(typeof obj == "object"){
355 obj = ddt.getTemplateString(obj);
356 }
357 obj = ddh.getTemplate(obj);
358 }
359 }
360
361 var tokens = ddh.tokenize(obj.nodes);
362 if(dd.tests){
363 this.tokens = tokens.slice(0);
364 }
365
366 var parser = new dd._DomParser(tokens);
367 this.nodelist = parser.parse();
368 },
369 {
370 _count: 0,
371 _re: /\bdojo:([a-zA-Z0-9_]+)\b/g,
372 setClass: function(/*String*/str){
373 // summary:
374 // Sets the specified class name on the root node.
375 this.getRootNode().className = str;
376 },
377 getRootNode: function(){
378 // summary:
379 // Returns the template root node.
380 return this.buffer.rootNode;
381 },
382 getBuffer: function(){
383 // summary:
384 // Returns a new buffer.
385 return new dd.DomBuffer();
386 },
387 render: function(/*dojox/dtl/Context?*/context, /*concatenable?*/buffer){
388 // summary:
389 // Renders this template.
390 buffer = this.buffer = buffer || this.getBuffer();
391 this.rootNode = null;
392 var output = this.nodelist.render(context || new dd.Context({}), buffer);
393 for(var i = 0, node; node = buffer._cache[i]; i++){
394 if(node._cache){
395 node._cache.length = 0;
396 }
397 }
398 return output;
399 },
400 unrender: function(context, buffer){
401 return this.nodelist.unrender(context, buffer);
402 }
403 });
404
405 dd.DomBuffer = lang.extend(function(/*Node*/ parent){
406 // summary:
407 // Allows the manipulation of DOM
408 // description:
409 // Use this to append a child, change the parent, or
410 // change the attribute of the current node.
411 // parent:
412 // The parent node.
413 this._parent = parent;
414 this._cache = [];
415 },
416 {
417 concat: function(/*DOMNode*/ node){
418 var parent = this._parent;
419 if(parent && node.parentNode && node.parentNode === parent && !parent._dirty){
420 return this;
421 }
422
423 if(node.nodeType == 1 && !this.rootNode){
424 this.rootNode = node || true;
425 return this;
426 }
427
428 if(!parent){
429 if(node.nodeType == 3 && lang.trim(node.data)){
430 throw new Error("Text should not exist outside of the root node in template");
431 }
432 return this;
433 }
434 if(this._closed){
435 if(node.nodeType == 3 && !lang.trim(node.data)){
436 return this;
437 }else{
438 throw new Error("Content should not exist outside of the root node in template");
439 }
440 }
441 if(parent._dirty){
442 if(node._drawn && node.parentNode == parent){
443 var caches = parent._cache;
444 if(caches){
445 for(var i = 0, cache; cache = caches[i]; i++){
446 this.onAddNode && this.onAddNode(cache);
447 parent.insertBefore(cache, node);
448 this.onAddNodeComplete && this.onAddNodeComplete(cache);
449 }
450 caches.length = 0;
451 }
452 }
453 parent._dirty = false;
454 }
455 if(!parent._cache){
456 parent._cache = [];
457 this._cache.push(parent);
458 }
459 parent._dirty = true;
460 parent._cache.push(node);
461 return this;
462 },
463 remove: function(/*String|DomNode*/obj){
464 if(typeof obj == "string"){
465 if(this._parent){
466 this._parent.removeAttribute(obj);
467 }
468 }else{
469 if(obj.nodeType == 1 && !this.getRootNode() && !this._removed){
470 this._removed = true;
471 return this;
472 }
473 if(obj.parentNode){
474 this.onRemoveNode && this.onRemoveNode(obj);
475 if(obj.parentNode){
476 obj.parentNode.removeChild(obj);
477 }
478 }
479 }
480 return this;
481 },
482 setAttribute: function(key, value){
483 var old = html.attr(this._parent, key);
484 if(this.onChangeAttribute && old != value){
485 this.onChangeAttribute(this._parent, key, old, value);
486 }
487 if(key == "style"){
488 //console.log(value);
489 this._parent.style.cssText = value;
490 }else{
491 html.attr(this._parent, key, value);
492 //console.log(this._parent, key, value);
493 if(key == "value"){
494 this._parent.setAttribute(key, value);
495 }
496 }
497 return this;
498 },
499 addEvent: function(context, type, fn, /*Array|Function*/ args){
500 if(!context.getThis()){ throw new Error("You must use Context.setObject(instance)"); }
501 this.onAddEvent && this.onAddEvent(this.getParent(), type, fn);
502 var resolved = fn;
503 if(lang.isArray(args)){
504 resolved = function(e){
505 this[fn].apply(this, [e].concat(args));
506 }
507 }
508 return connect.connect(this.getParent(), type, context.getThis(), resolved);
509 },
510 setParent: function(node, /*Boolean?*/ up, /*Boolean?*/ root){
511 if(!this._parent) this._parent = this._first = node;
512
513 if(up && root && node === this._first){
514 this._closed = true;
515 }
516
517 if(up){
518 var parent = this._parent;
519 var script = "";
520 var ie = has("ie") && parent.tagName == "SCRIPT";
521 if(ie){
522 parent.text = "";
523 }
524 if(parent._dirty){
525 var caches = parent._cache;
526 var select = (parent.tagName == "SELECT" && !parent.options.length);
527 for(var i = 0, cache; cache = caches[i]; i++){
528 if(cache !== parent){
529 this.onAddNode && this.onAddNode(cache);
530 if(ie){
531 script += cache.data;
532 }else{
533 parent.appendChild(cache);
534 if(select && cache.defaultSelected && i){
535 select = i;
536 }
537 }
538 this.onAddNodeComplete && this.onAddNodeComplete(cache);
539 }
540 }
541 if(select){
542 parent.options.selectedIndex = (typeof select == "number") ? select : 0;
543 }
544 caches.length = 0;
545 parent._dirty = false;
546 }
547 if(ie){
548 parent.text = script;
549 }
550 }
551
552 this._parent = node;
553 this.onSetParent && this.onSetParent(node, up, root);
554 return this;
555 },
556 getParent: function(){
557 return this._parent;
558 },
559 getRootNode: function(){
560 return this.rootNode;
561 }
562 /*=====
563 ,
564 onSetParent: function(node, up){
565 // summary:
566 // Stub called when setParent is used.
567 },
568 onAddNode: function(node){
569 // summary:
570 // Stub called before new nodes are added
571 },
572 onAddNodeComplete: function(node){
573 // summary:
574 // Stub called after new nodes are added
575 },
576 onRemoveNode: function(node){
577 // summary:
578 // Stub called when nodes are removed
579 },
580 onChangeAttribute: function(node, attribute, old, updated){
581 // summary:
582 // Stub called when an attribute is changed
583 },
584 onChangeData: function(node, old, updated){
585 // summary:
586 // Stub called when a data in a node is changed
587 },
588 onClone: function(from, to){
589 // summary:
590 // Stub called when a node is duplicated
591 // from: DOMNode
592 // to: DOMNode
593 },
594 onAddEvent: function(node, type, description){
595 // summary:
596 // Stub to call when you're adding an event
597 // node: DOMNode
598 // type: String
599 // description: String
600 }
601 =====*/
602 });
603
604 dd._DomNode = lang.extend(function(node){
605 // summary:
606 // Places a node into DOM
607 this.contents = node;
608 },
609 {
610 render: function(context, buffer){
611 this._rendered = true;
612 return buffer.concat(this.contents);
613 },
614 unrender: function(context, buffer){
615 if(!this._rendered){
616 return buffer;
617 }
618 this._rendered = false;
619 return buffer.remove(this.contents);
620 },
621 clone: function(buffer){
622 return new this.constructor(this.contents);
623 }
624 });
625
626 dd._DomNodeList = lang.extend(function(/*Node[]*/ nodes){
627 // summary:
628 // A list of any DOM-specific node objects
629 // description:
630 // Any object that's used in the constructor or added
631 // through the push function much implement the
632 // render, unrender, and clone functions.
633 this.contents = nodes || [];
634 },
635 {
636 push: function(node){
637 this.contents.push(node);
638 },
639 unshift: function(node){
640 this.contents.unshift(node);
641 },
642 render: function(context, buffer, /*Node*/ instance){
643 buffer = buffer || dd.DomTemplate.prototype.getBuffer();
644
645 if(instance){
646 var parent = buffer.getParent();
647 }
648 for(var i = 0; i < this.contents.length; i++){
649 buffer = this.contents[i].render(context, buffer);
650 if(!buffer) throw new Error("Template node render functions must return their buffer");
651 }
652 if(parent){
653 buffer.setParent(parent);
654 }
655 return buffer;
656 },
657 dummyRender: function(context, buffer, asNode){
658 // summary:
659 // A really expensive way of checking to see how a rendering will look.
660 // Used in the ifchanged tag
661 var div = document.createElement("div");
662
663 var parent = buffer.getParent();
664 var old = parent._clone;
665 // Tell the clone system to attach itself to our new div
666 parent._clone = div;
667 var nodelist = this.clone(buffer, div);
668 if(old){
669 // Restore state if there was a previous clone
670 parent._clone = old;
671 }else{
672 // Remove if there was no clone
673 parent._clone = null;
674 }
675
676 buffer = dd.DomTemplate.prototype.getBuffer();
677 nodelist.unshift(new dd.ChangeNode(div));
678 nodelist.unshift(new dd._DomNode(div));
679 nodelist.push(new dd.ChangeNode(div, true));
680 nodelist.render(context, buffer);
681
682 if(asNode){
683 return buffer.getRootNode();
684 }
685
686 var html = div.innerHTML;
687 return (has("ie")) ? domconstruct.replace(/\s*_(dirty|clone)="[^"]*"/g, "") : html;
688 },
689 unrender: function(context, buffer, instance){
690 if(instance){
691 var parent = buffer.getParent();
692 }
693 for(var i = 0; i < this.contents.length; i++){
694 buffer = this.contents[i].unrender(context, buffer);
695 if(!buffer) throw new Error("Template node render functions must return their buffer");
696 }
697 if(parent){
698 buffer.setParent(parent);
699 }
700 return buffer;
701 },
702 clone: function(buffer){
703 // summary:
704 // Used to create an identical copy of a NodeList, useful for things like the for tag.
705 var parent = buffer.getParent();
706 var contents = this.contents;
707 var nodelist = new dd._DomNodeList();
708 var cloned = [];
709 for(var i = 0; i < contents.length; i++){
710 var clone = contents[i].clone(buffer);
711 if(clone instanceof dd.ChangeNode || clone instanceof dd._DomNode){
712 var item = clone.contents._clone;
713 if(item){
714 clone.contents = item;
715 }else if(parent != clone.contents && clone instanceof dd._DomNode){
716 var node = clone.contents;
717 clone.contents = clone.contents.cloneNode(false);
718 buffer.onClone && buffer.onClone(node, clone.contents);
719 cloned.push(node);
720 node._clone = clone.contents;
721 }
722 }
723 nodelist.push(clone);
724 }
725
726 for(var i = 0, clone; clone = cloned[i]; i++){
727 clone._clone = null;
728 }
729
730 return nodelist;
731 },
732 rtrim: function(){
733 while(1){
734 var i = this.contents.length - 1;
735 if(this.contents[i] instanceof dd._DomTextNode && this.contents[i].isEmpty()){
736 this.contents.pop();
737 }else{
738 break;
739 }
740 }
741
742 return this;
743 }
744 });
745
746 dd._DomVarNode = lang.extend(function(str){
747 // summary:
748 // A node to be processed as a variable
749 // description:
750 // Will render an object that supports the render function
751 // and the getRootNode function
752 this.contents = new dd._Filter(str);
753 },
754 {
755 render: function(context, buffer){
756 var str = this.contents.resolve(context);
757
758 // What type of rendering?
759 var type = "text";
760 if(str){
761 if(str.render && str.getRootNode){
762 type = "injection";
763 }else if(str.safe){
764 if(str.nodeType){
765 type = "node";
766 }else if(str.toString){
767 str = str.toString();
768 type = "html";
769 }
770 }
771 }
772
773 // Has the typed changed?
774 if(this._type && type != this._type){
775 this.unrender(context, buffer);
776 }
777 this._type = type;
778
779 // Now render
780 switch(type){
781 case "text":
782 this._rendered = true;
783 this._txt = this._txt || document.createTextNode(str);
784 if(this._txt.data != str){
785 var old = this._txt.data;
786 this._txt.data = str;
787 buffer.onChangeData && buffer.onChangeData(this._txt, old, this._txt.data);
788 }
789 return buffer.concat(this._txt);
790 case "injection":
791 var root = str.getRootNode();
792
793 if(this._rendered && root != this._root){
794 buffer = this.unrender(context, buffer);
795 }
796 this._root = root;
797
798 var injected = this._injected = new dd._DomNodeList();
799 injected.push(new dd.ChangeNode(buffer.getParent()));
800 injected.push(new dd._DomNode(root));
801 injected.push(str);
802 injected.push(new dd.ChangeNode(buffer.getParent()));
803 this._rendered = true;
804
805 return injected.render(context, buffer);
806 case "node":
807 this._rendered = true;
808 if(this._node && this._node != str && this._node.parentNode && this._node.parentNode === buffer.getParent()){
809 this._node.parentNode.removeChild(this._node);
810 }
811 this._node = str;
812 return buffer.concat(str);
813 case "html":
814 if(this._rendered && this._src != str){
815 buffer = this.unrender(context, buffer);
816 }
817 this._src = str;
818
819 // This can get reset in the above tag
820 if(!this._rendered){
821 this._rendered = true;
822 this._html = this._html || [];
823 var div = (this._div = this._div || document.createElement("div"));
824 div.innerHTML = str;
825 var children = div.childNodes;
826 while(children.length){
827 var removed = div.removeChild(children[0]);
828 this._html.push(removed);
829 buffer = buffer.concat(removed);
830 }
831 }
832
833 return buffer;
834 default:
835 return buffer;
836 }
837 },
838 unrender: function(context, buffer){
839 if(!this._rendered){
840 return buffer;
841 }
842 this._rendered = false;
843
844 // Unrender injected nodes
845 switch(this._type){
846 case "text":
847 return buffer.remove(this._txt);
848 case "injection":
849 return this._injection.unrender(context, buffer);
850 case "node":
851 if(this._node.parentNode === buffer.getParent()){
852 return buffer.remove(this._node);
853 }
854 return buffer;
855 case "html":
856 for(var i = 0, l = this._html.length; i < l; i++){
857 buffer = buffer.remove(this._html[i]);
858 }
859 return buffer;
860 default:
861 return buffer;
862 }
863 },
864 clone: function(){
865 return new this.constructor(this.contents.getExpression());
866 }
867 });
868
869 dd.ChangeNode = lang.extend(function(node, /*Boolean?*/ up, /*Bookean*/ root){
870 // summary:
871 // Changes the parent during render/unrender
872 this.contents = node;
873 this.up = up;
874 this.root = root;
875 },
876 {
877 render: function(context, buffer){
878 return buffer.setParent(this.contents, this.up, this.root);
879 },
880 unrender: function(context, buffer){
881 if(!buffer.getParent()){
882 return buffer;
883 }
884 return buffer.setParent(this.contents);
885 },
886 clone: function(){
887 return new this.constructor(this.contents, this.up, this.root);
888 }
889 });
890
891 dd.AttributeNode = lang.extend(function(key, value){
892 // summary
893 // Works on attributes
894 this.key = key;
895 this.value = value;
896 this.contents = value;
897 if(this._pool[value]){
898 this.nodelist = this._pool[value];
899 }else{
900 if(!(this.nodelist = dd.quickFilter(value))){
901 this.nodelist = (new dd.Template(value, true)).nodelist;
902 }
903 this._pool[value] = this.nodelist;
904 }
905
906 this.contents = "";
907 },
908 {
909 _pool: {},
910 render: function(context, buffer){
911 var key = this.key;
912 var value = this.nodelist.dummyRender(context);
913 if(dd.BOOLS[key]){
914 value = !(value == "false" || value == "undefined" || !value);
915 }
916 if(value !== this.contents || value === ""){
917 this.contents = value;
918 return buffer.setAttribute(key, value);
919 }
920 return buffer;
921 },
922 unrender: function(context, buffer){
923 this.contents = "";
924 return buffer.remove(this.key);
925 },
926 clone: function(buffer){
927 return new this.constructor(this.key, this.value);
928 }
929 });
930
931 dd._DomTextNode = lang.extend(function(str){
932 // summary
933 // Adds a straight text node without any processing
934 this.contents = document.createTextNode(str);
935 this.upcoming = str;
936 },
937 {
938 set: function(data){
939 this.upcoming = data;
940 return this;
941 },
942 render: function(context, buffer){
943 if(this.contents.data != this.upcoming){
944 var old = this.contents.data;
945 this.contents.data = this.upcoming;
946 buffer.onChangeData && buffer.onChangeData(this.contents, old, this.upcoming);
947 }
948 return buffer.concat(this.contents);
949 },
950 unrender: function(context, buffer){
951 return buffer.remove(this.contents);
952 },
953 isEmpty: function(){
954 return !lang.trim(this.contents.data);
955 },
956 clone: function(){
957 return new this.constructor(this.contents.data);
958 }
959 });
960
961 dd._DomParser = lang.extend(function(tokens){
962 // summary:
963 // Turn a simple array into a set of objects
964 // description:
965 // This is also used by all tags to move through
966 // the list of nodes.
967 this.contents = tokens;
968 },
969 {
970 i: 0,
971 parse: function(/*Array?*/ stop_at){
972 var terminators = {};
973 var tokens = this.contents;
974 if(!stop_at){
975 stop_at = [];
976 }
977 for(var i = 0; i < stop_at.length; i++){
978 terminators[stop_at[i]] = true;
979 }
980 var nodelist = new dd._DomNodeList();
981 while(this.i < tokens.length){
982 var token = tokens[this.i++];
983 var type = token[0];
984 var value = token[1];
985 if(type == dd.TOKEN_CUSTOM){
986 nodelist.push(value);
987 }else if(type == dd.TOKEN_CHANGE){
988 var changeNode = new dd.ChangeNode(value, token[2], token[3]);
989 value[changeNode.attr] = changeNode;
990 nodelist.push(changeNode);
991 }else if(type == dd.TOKEN_ATTR){
992 var fn = ddt.getTag("attr:" + token[2], true);
993 if(fn && token[3]){
994 if (token[3].indexOf("{%") != -1 || token[3].indexOf("{{") != -1) {
995 value.setAttribute(token[2], "");
996 }
997 nodelist.push(fn(null, new dd.Token(type, token[2] + " " + token[3])));
998 }else if(lang.isString(token[3])){
999 if(token[2] == "style" || token[3].indexOf("{%") != -1 || token[3].indexOf("{{") != -1){
1000 nodelist.push(new dd.AttributeNode(token[2], token[3]));
1001 }else if(lang.trim(token[3])){
1002 try{
1003 html.attr(value, token[2], token[3]);
1004 }catch(e){}
1005 }
1006 }
1007 }else if(type == dd.TOKEN_NODE){
1008 var fn = ddt.getTag("node:" + value.tagName.toLowerCase(), true);
1009 if(fn){
1010 // TODO: We need to move this to tokenization so that it's before the
1011 // node and the parser can be passed here instead of null
1012 nodelist.push(fn(null, new dd.Token(type, value), value.tagName.toLowerCase()));
1013 }
1014 nodelist.push(new dd._DomNode(value));
1015 }else if(type == dd.TOKEN_VAR){
1016 nodelist.push(new dd._DomVarNode(value));
1017 }else if(type == dd.TOKEN_TEXT){
1018 nodelist.push(new dd._DomTextNode(value.data || value));
1019 }else if(type == dd.TOKEN_BLOCK){
1020 if(terminators[value]){
1021 --this.i;
1022 return nodelist;
1023 }
1024 var cmd = value.split(/\s+/g);
1025 if(cmd.length){
1026 cmd = cmd[0];
1027 var fn = ddt.getTag(cmd);
1028 if(typeof fn != "function"){
1029 throw new Error("Function not found for " + cmd);
1030 }
1031 var tpl = fn(this, new dd.Token(type, value));
1032 if(tpl){
1033 nodelist.push(tpl);
1034 }
1035 }
1036 }
1037 }
1038
1039 if(stop_at.length){
1040 throw new Error("Could not find closing tag(s): " + stop_at.toString());
1041 }
1042
1043 return nodelist;
1044 },
1045 next_token: function(){
1046 // summary:
1047 // Returns the next token in the list.
1048 var token = this.contents[this.i++];
1049 return new dd.Token(token[0], token[1]);
1050 },
1051 delete_first_token: function(){
1052 this.i++;
1053 },
1054 skip_past: function(endtag){
1055 return dd._Parser.prototype.skip_past.call(this, endtag);
1056 },
1057 create_variable_node: function(expr){
1058 return new dd._DomVarNode(expr);
1059 },
1060 create_text_node: function(expr){
1061 return new dd._DomTextNode(expr || "");
1062 },
1063 getTemplate: function(/*String*/ loc){
1064 return new dd.DomTemplate(ddh.getTemplate(loc));
1065 }
1066 });
1067
1068 return ddh;
1069 });