dom.js 29 KB

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