1 /* Licensed to the Apache Software Foundation (ASF) under one or more 2 * contributor license agreements. See the NOTICE file distributed with 3 * this work for additional information regarding copyright ownership. 4 * The ASF licenses this file to you under the Apache License, Version 2.0 5 * (the "License"); you may not use this file except in compliance with 6 * the License. You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 /** 18 * @class 19 * @name _Dom 20 * @memberOf myfaces._impl._util 21 * @extends myfaces._impl.core._Runtime 22 * @description Object singleton collection of dom helper routines 23 * (which in later incarnations will 24 * get browser specific speed optimizations) 25 * 26 * Since we have to be as tight as possible 27 * we will focus with our dom routines to only 28 * the parts which our impl uses. 29 * A jquery like query API would be nice 30 * but this would increase up our codebase significantly 31 * 32 * <p>This class provides the proper fallbacks for ie8- and Firefox 3.6-</p> 33 */ 34 _MF_SINGLTN(_PFX_UTIL + "_Dom", Object, /** @lends myfaces._impl._util._Dom.prototype */ { 35 36 /*table elements which are used in various parts */ 37 TABLE_ELEMS: { 38 "thead": 1, 39 "tbody": 1, 40 "tr": 1, 41 "th": 1, 42 "td": 1, 43 "tfoot" : 1 44 }, 45 46 _Lang: myfaces._impl._util._Lang, 47 _RT: myfaces._impl.core._Runtime, 48 _dummyPlaceHolder:null, 49 50 /** 51 * standard constructor 52 */ 53 constructor_: function() { 54 }, 55 56 runCss: function(item/*, xmlData*/) { 57 58 var UDEF = "undefined", 59 _RT = this._RT, 60 _Lang = this._Lang, 61 applyStyle = function(item, style) { 62 var newSS = document.createElement("style"); 63 64 newSS.setAttribute("rel", item.getAttribute("rel") || "stylesheet"); 65 newSS.setAttribute("type", item.getAttribute("type") || "text/css"); 66 document.getElementsByTagName("head")[0].appendChild(newSS); 67 //ie merrily again goes its own way 68 if (window.attachEvent && !_RT.isOpera && UDEF != typeof newSS.styleSheet && UDEF != newSS.styleSheet.cssText) newSS.styleSheet.cssText = style; 69 else newSS.appendChild(document.createTextNode(style)); 70 }, 71 72 execCss = function(item) { 73 var equalsIgnoreCase = _Lang.equalsIgnoreCase; 74 var tagName = item.tagName; 75 if (tagName && equalsIgnoreCase(tagName, "link") && equalsIgnoreCase(item.getAttribute("type"), "text/css")) { 76 applyStyle(item, "@import url('" + item.getAttribute("href") + "');"); 77 } else if (tagName && equalsIgnoreCase(tagName, "style") && equalsIgnoreCase(item.getAttribute("type"), "text/css")) { 78 var innerText = []; 79 //compliant browsers know child nodes 80 var childNodes = item.childNodes; 81 if (childNodes) { 82 var len = childNodes.length; 83 for (var cnt = 0; cnt < len; cnt++) { 84 innerText.push(childNodes[cnt].innerHTML || childNodes[cnt].data); 85 } 86 //non compliant ones innerHTML 87 } else if (item.innerHTML) { 88 innerText.push(item.innerHTML); 89 } 90 91 applyStyle(item, innerText.join("")); 92 } 93 }; 94 95 try { 96 var scriptElements = this.findByTagNames(item, {"link":1,"style":1}, true); 97 if (scriptElements == null) return; 98 for (var cnt = 0; cnt < scriptElements.length; cnt++) { 99 execCss(scriptElements[cnt]); 100 } 101 102 } finally { 103 //the usual ie6 fix code 104 //the IE6 garbage collector is broken 105 //nulling closures helps somewhat to reduce 106 //mem leaks, which are impossible to avoid 107 //at this browser 108 execCss = null; 109 applyStyle = null; 110 } 111 }, 112 113 114 /** 115 * Run through the given Html item and execute the inline scripts 116 * (IE doesn't do this by itself) 117 * @param {Node} item 118 */ 119 runScripts: function(item, xmlData) { 120 var _Lang = this._Lang, 121 _RT = this._RT, 122 finalScripts = [], 123 execScrpt = function(item) { 124 var tagName = item.tagName; 125 if (tagName && _Lang.equalsIgnoreCase(tagName, "script")) { 126 var src = item.getAttribute('src'); 127 if ('undefined' != typeof src 128 && null != src 129 && src.length > 0 130 ) { 131 //we have to move this into an inner if because chrome otherwise chokes 132 //due to changing the and order instead of relying on left to right 133 //if jsf.js is already registered we do not replace it anymore 134 if ((src.indexOf("ln=scripts") == -1 && src.indexOf("ln=javax.faces") == -1) || (src.indexOf("/jsf.js") == -1 135 && src.indexOf("/jsf-uncompressed.js") == -1)) { 136 if (finalScripts.length) { 137 //script source means we have to eval the existing 138 //scripts before running the include 139 _RT.globalEval(finalScripts.join("\n")); 140 141 finalScripts = []; 142 } 143 _RT.loadScriptEval(src, item.getAttribute('type'), false, "UTF-8", false); 144 } 145 146 } else { 147 // embedded script auto eval 148 var test = (!xmlData) ? item.text : _Lang.serializeChilds(item); 149 var go = true; 150 while (go) { 151 go = false; 152 if (test.substring(0, 1) == " ") { 153 test = test.substring(1); 154 go = true; 155 } 156 if (test.substring(0, 4) == "<!--") { 157 test = test.substring(4); 158 go = true; 159 } 160 if (test.substring(0, 11) == "//<![CDATA[") { 161 test = test.substring(11); 162 go = true; 163 } 164 } 165 // we have to run the script under a global context 166 //we store the script for less calls to eval 167 finalScripts.push(test); 168 169 } 170 } 171 }; 172 try { 173 var scriptElements = this.findByTagName(item, "script", true); 174 if (scriptElements == null) return; 175 for (var cnt = 0; cnt < scriptElements.length; cnt++) { 176 execScrpt(scriptElements[cnt]); 177 } 178 if (finalScripts.length) { 179 _RT.globalEval(finalScripts.join("\n")); 180 } 181 } catch (e) { 182 if(window.console && window.console.error) { 183 //not sure if we 184 //should use our standard 185 //error mechanisms here 186 //because in the head appendix 187 //method only a console 188 //error would be raised as well 189 console.error(e.message||e.description); 190 } else { 191 if(jsf.ajax.getProjectStage() === "Development") { 192 alert("Error in evaluated javascript:"+ (e.message||e.description)); 193 } 194 } 195 } finally { 196 //the usual ie6 fix code 197 //the IE6 garbage collector is broken 198 //nulling closures helps somewhat to reduce 199 //mem leaks, which are impossible to avoid 200 //at this browser 201 execScrpt = null; 202 } 203 }, 204 205 206 /** 207 * determines to fetch a node 208 * from its id or name, the name case 209 * only works if the element is unique in its name 210 * @param {String} elem 211 */ 212 byIdOrName: function(elem) { 213 if (!elem) return null; 214 if (!this._Lang.isString(elem)) return elem; 215 216 var ret = this.byId(elem); 217 if (ret) return ret; 218 //we try the unique name fallback 219 var items = document.getElementsByName(elem); 220 return ((items.length == 1) ? items[0] : null); 221 }, 222 223 /** 224 * node id or name, determines the valid form identifier of a node 225 * depending on its uniqueness 226 * 227 * Usually the id is chosen for an elem, but if the id does not 228 * exist we try a name fallback. If the passed element has a unique 229 * name we can use that one as subsequent identifier. 230 * 231 * 232 * @param {String} elem 233 */ 234 nodeIdOrName: function(elem) { 235 if (elem) { 236 //just to make sure that the pas 237 238 elem = this.byId(elem); 239 if (!elem) return null; 240 //detached element handling, we also store the element name 241 //to get a fallback option in case the identifier is not determinable 242 // anymore, in case of a framework induced detachment the element.name should 243 // be shared if the identifier is not determinable anymore 244 //the downside of this method is the element name must be unique 245 //which in case of jsf it is 246 var elementId = elem.id || elem.name; 247 if ((elem.id == null || elem.id == '') && elem.name) { 248 elementId = elem.name; 249 250 //last check for uniqueness 251 if (this.getElementsByName(elementId).length > 1) { 252 //no unique element name so we need to perform 253 //a return null to let the caller deal with this issue 254 return null; 255 } 256 } 257 return elementId; 258 } 259 return null; 260 }, 261 262 deleteItems: function(items) { 263 if (! items || ! items.length) return; 264 for (var cnt = 0; cnt < items.length; cnt++) { 265 this.deleteItem(items[cnt]); 266 } 267 }, 268 269 /** 270 * Simple delete on an existing item 271 */ 272 deleteItem: function(itemIdToReplace) { 273 var item = this.byId(itemIdToReplace); 274 if (!item) { 275 throw this._Lang.makeException(new Error(),null, null, this._nameSpace, "deleteItem", "_Dom.deleteItem Unknown Html-Component-ID: " + itemIdToReplace); 276 } 277 278 this._removeNode(item, false); 279 }, 280 281 /** 282 * creates a node upon a given node name 283 * @param nodeName {String} the node name to be created 284 * @param attrs {Array} a set of attributes to be set 285 */ 286 createElement: function(nodeName, attrs) { 287 var ret = document.createElement(nodeName); 288 if (attrs) { 289 for (var key in attrs) { 290 if(!attrs.hasOwnProperty(key)) continue; 291 this.setAttribute(ret, key, attrs[key]); 292 } 293 } 294 return ret; 295 }, 296 297 /** 298 * Checks whether the browser is dom compliant. 299 * Dom compliant means that it performs the basic dom operations safely 300 * without leaking and also is able to perform a native setAttribute 301 * operation without freaking out 302 * 303 * 304 * Not dom compliant browsers are all microsoft browsers in quirks mode 305 * and ie6 and ie7 to some degree in standards mode 306 * and pretty much every browser who cannot create ranges 307 * (older mobile browsers etc...) 308 * 309 * We dont do a full browser detection here because it probably is safer 310 * to test for existing features to make an assumption about the 311 * browsers capabilities 312 */ 313 isDomCompliant: function() { 314 return true; 315 }, 316 317 /** 318 * proper insert before which takes tables into consideration as well as 319 * browser deficiencies 320 * @param item the node to insert before 321 * @param markup the markup to be inserted 322 */ 323 insertBefore: function(item, markup) { 324 this._assertStdParams(item, markup, "insertBefore"); 325 326 markup = this._Lang.trim(markup); 327 if (markup === "") return null; 328 329 var evalNodes = this._buildEvalNodes(item, markup), 330 currentRef = item, 331 parentNode = item.parentNode, 332 ret = []; 333 for (var cnt = evalNodes.length - 1; cnt >= 0; cnt--) { 334 currentRef = parentNode.insertBefore(evalNodes[cnt], currentRef); 335 ret.push(currentRef); 336 } 337 ret = ret.reverse(); 338 this._eval(ret); 339 return ret; 340 }, 341 342 /** 343 * proper insert before which takes tables into consideration as well as 344 * browser deficiencies 345 * @param item the node to insert before 346 * @param markup the markup to be inserted 347 */ 348 insertAfter: function(item, markup) { 349 this._assertStdParams(item, markup, "insertAfter"); 350 markup = this._Lang.trim(markup); 351 if (markup === "") return null; 352 353 var evalNodes = this._buildEvalNodes(item, markup), 354 currentRef = item, 355 parentNode = item.parentNode, 356 ret = []; 357 358 for (var cnt = 0; cnt < evalNodes.length; cnt++) { 359 if (currentRef.nextSibling) { 360 //Winmobile 6 has problems with this strategy, but it is not really fixable 361 currentRef = parentNode.insertBefore(evalNodes[cnt], currentRef.nextSibling); 362 } else { 363 currentRef = parentNode.appendChild(evalNodes[cnt]); 364 } 365 ret.push(currentRef); 366 } 367 this._eval(ret); 368 return ret; 369 }, 370 371 372 /** 373 * outerHTML replacement which works cross browserlike 374 * but still is speed optimized 375 * 376 * @param item the item to be replaced 377 * @param markup the markup for the replacement 378 */ 379 outerHTML : function(item, markup) { 380 this._assertStdParams(item, markup, "outerHTML"); 381 382 markup = this._Lang.trim(markup); 383 if (markup !== "") { 384 var ret = null; 385 386 // we try to determine the browsers compatibility 387 // level to standards dom level 2 via various methods 388 if (this.isDomCompliant()) { 389 ret = this._outerHTMLCompliant(item, markup); 390 } else { 391 //call into abstract method 392 ret = this._outerHTMLNonCompliant(item, markup); 393 } 394 395 // and remove the old item 396 //first we have to save the node newly insert for easier access in our eval part 397 this._eval(ret); 398 return ret; 399 } 400 // and remove the old item, in case of an empty newtag and do nothing else 401 this._removeNode(item, false); 402 return null; 403 }, 404 405 /** 406 * detaches a set of nodes from their parent elements 407 * in a browser independend manner 408 * @param {Object} items the items which need to be detached 409 * @return {Array} an array of nodes with the detached dom nodes 410 */ 411 detach: function(items) { 412 var ret = []; 413 if ('undefined' != typeof items.nodeType) { 414 if (items.parentNode) { 415 ret.push(items.parentNode.removeChild(items)); 416 } else { 417 ret.push(items); 418 } 419 return ret; 420 } 421 //all ies treat node lists not as arrays so we have to take 422 //an intermediate step 423 var nodeArr = this._Lang.objToArray(items); 424 for (var cnt = 0; cnt < nodeArr.length; cnt++) { 425 ret.push(nodeArr[cnt].parentNode.removeChild(nodeArr[cnt])); 426 } 427 return ret; 428 }, 429 430 _outerHTMLCompliant: function(item, markup) { 431 //table element replacements like thead, tbody etc... have to be treated differently 432 var evalNodes = this._buildEvalNodes(item, markup); 433 434 if (evalNodes.length == 1) { 435 var ret = evalNodes[0]; 436 item.parentNode.replaceChild(ret, item); 437 return ret; 438 } else { 439 return this.replaceElements(item, evalNodes); 440 } 441 }, 442 443 444 445 /** 446 * checks if the provided element is a subelement of a table element 447 * @param item 448 */ 449 _isTableElement: function(item) { 450 return !!this.TABLE_ELEMS[(item.nodeName || item.tagName).toLowerCase()]; 451 }, 452 453 /** 454 * non ie browsers do not have problems with embedded scripts or any other construct 455 * we simply can use an innerHTML in a placeholder 456 * 457 * @param markup the markup to be used 458 */ 459 _buildNodesCompliant: function(markup) { 460 var dummyPlaceHolder = this.getDummyPlaceHolder(); //document.createElement("div"); 461 dummyPlaceHolder.innerHTML = markup; 462 return this._Lang.objToArray(dummyPlaceHolder.childNodes); 463 }, 464 465 466 467 468 /** 469 * builds up a correct dom subtree 470 * if the markup is part of table nodes 471 * The usecase for this is to allow subtable rendering 472 * like single rows thead or tbody 473 * 474 * @param item 475 * @param markup 476 */ 477 _buildTableNodes: function(item, markup) { 478 var itemNodeName = (item.nodeName || item.tagName).toLowerCase(); 479 480 var tmpNodeName = itemNodeName; 481 var depth = 0; 482 while (tmpNodeName != "table") { 483 item = item.parentNode; 484 tmpNodeName = (item.nodeName || item.tagName).toLowerCase(); 485 depth++; 486 } 487 488 var dummyPlaceHolder = this.getDummyPlaceHolder(); 489 if (itemNodeName == "td") { 490 dummyPlaceHolder.innerHTML = "<table><tbody><tr>" + markup + "</tr></tbody></table>"; 491 } else { 492 dummyPlaceHolder.innerHTML = "<table>" + markup + "</table>"; 493 } 494 495 for (var cnt = 0; cnt < depth; cnt++) { 496 dummyPlaceHolder = dummyPlaceHolder.childNodes[0]; 497 } 498 499 return this.detach(dummyPlaceHolder.childNodes); 500 }, 501 502 _removeChildNodes: function(node /*, breakEventsOpen */) { 503 if (!node) return; 504 node.innerHTML = ""; 505 }, 506 507 508 509 _removeNode: function(node /*, breakEventsOpen*/) { 510 if (!node) return; 511 var parentNode = node.parentNode; 512 if (parentNode) //if the node has a parent 513 parentNode.removeChild(node); 514 }, 515 516 517 /** 518 * build up the nodes from html markup in a browser independend way 519 * so that it also works with table nodes 520 * 521 * @param item the parent item upon the nodes need to be processed upon after building 522 * @param markup the markup to be built up 523 */ 524 _buildEvalNodes: function(item, markup) { 525 var evalNodes = null; 526 if (this._isTableElement(item)) { 527 evalNodes = this._buildTableNodes(item, markup); 528 } else { 529 var nonIEQuirks = (!this._RT.browser.isIE || this._RT.browser.isIE > 8); 530 //ie8 has a special problem it still has the swallow scripts and other 531 //elements bug, but it is mostly dom compliant so we have to give it a special 532 //treatment, IE9 finally fixes that issue finally after 10 years 533 evalNodes = (this.isDomCompliant() && nonIEQuirks) ? 534 this._buildNodesCompliant(markup) : 535 //ie8 or quirks mode browsers 536 this._buildNodesNonCompliant(markup); 537 } 538 return evalNodes; 539 }, 540 541 /** 542 * we have lots of methods with just an item and a markup as params 543 * this method builds an assertion for those methods to reduce code 544 * 545 * @param item the item to be tested 546 * @param markup the mark 547 * @param caller 548 */ 549 _assertStdParams: function(item, markup, caller, params) { 550 //internal error 551 if (!caller) { 552 throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "_assertStdParams", "Caller must be set for assertion"); 553 } 554 var _Lang = this._Lang, 555 ERR_PROV = "ERR_MUST_BE_PROVIDED1", 556 DOM = "myfaces._impl._util._Dom.", 557 finalParams = params || ["item", "markup"]; 558 559 if (!item || !markup) { 560 _Lang.makeException(new Error(), null, null,DOM, ""+caller, _Lang.getMessage(ERR_PROV, null, DOM +"."+ caller, (!item) ? finalParams[0] : finalParams[1])); 561 //throw Error(_Lang.getMessage(ERR_PROV, null, DOM + caller, (!item) ? params[0] : params[1])); 562 } 563 }, 564 565 /** 566 * internal eval handler used by various functions 567 * @param _nodeArr 568 */ 569 _eval: function(_nodeArr) { 570 if (this.isManualScriptEval()) { 571 var isArr = _nodeArr instanceof Array; 572 if (isArr && _nodeArr.length) { 573 for (var cnt = 0; cnt < _nodeArr.length; cnt++) { 574 this.runScripts(_nodeArr[cnt]); 575 } 576 } else if (!isArr) { 577 this.runScripts(_nodeArr); 578 } 579 } 580 }, 581 582 /** 583 * for performance reasons we work with replaceElement and replaceElements here 584 * after measuring performance it has shown that passing down an array instead 585 * of a single node makes replaceElement twice as slow, however 586 * a single node case is the 95% case 587 * 588 * @param item 589 * @param evalNode 590 */ 591 replaceElement: function(item, evalNode) { 592 //browsers with defect garbage collection 593 item.parentNode.insertBefore(evalNode, item); 594 this._removeNode(item, false); 595 }, 596 597 598 /** 599 * replaces an element with another element or a set of elements 600 * 601 * @param item the item to be replaced 602 * 603 * @param evalNodes the elements 604 */ 605 replaceElements: function (item, evalNodes) { 606 var evalNodesDefined = evalNodes && 'undefined' != typeof evalNodes.length; 607 if (!evalNodesDefined) { 608 throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "replaceElements", this._Lang.getMessage("ERR_REPLACE_EL")); 609 } 610 611 var parentNode = item.parentNode, 612 613 sibling = item.nextSibling, 614 resultArr = this._Lang.objToArray(evalNodes); 615 616 for (var cnt = 0; cnt < resultArr.length; cnt++) { 617 if (cnt == 0) { 618 this.replaceElement(item, resultArr[cnt]); 619 } else { 620 if (sibling) { 621 parentNode.insertBefore(resultArr[cnt], sibling); 622 } else { 623 parentNode.appendChild(resultArr[cnt]); 624 } 625 } 626 } 627 return resultArr; 628 }, 629 630 /** 631 * optimized search for an array of tag names 632 * deep scan will always be performed. 633 * @param fragment the fragment which should be searched for 634 * @param tagNames an map indx of tag names which have to be found 635 * 636 */ 637 findByTagNames: function(fragment, tagNames) { 638 this._assertStdParams(fragment, tagNames, "findByTagNames", ["fragment", "tagNames"]); 639 640 var nodeType = fragment.nodeType; 641 if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null; 642 643 //we can use the shortcut 644 if (fragment.querySelectorAll) { 645 var query = []; 646 for (var key in tagNames) { 647 if(!tagNames.hasOwnProperty(key)) continue; 648 query.push(key); 649 } 650 var res = []; 651 if (fragment.tagName && tagNames[fragment.tagName.toLowerCase()]) { 652 res.push(fragment); 653 } 654 return res.concat(this._Lang.objToArray(fragment.querySelectorAll(query.join(", ")))); 655 } 656 657 //now the filter function checks case insensitively for the tag names needed 658 var filter = function(node) { 659 return node.tagName && tagNames[node.tagName.toLowerCase()]; 660 }; 661 662 //now we run an optimized find all on it 663 try { 664 return this.findAll(fragment, filter, true); 665 } finally { 666 //the usual IE6 is broken, fix code 667 filter = null; 668 } 669 }, 670 671 /** 672 * determines the number of nodes according to their tagType 673 * 674 * @param {Node} fragment (Node or fragment) the fragment to be investigated 675 * @param {String} tagName the tag name (lowercase) 676 * (the normal usecase is false, which means if the element is found only its 677 * adjacent elements will be scanned, due to the recursive descension 678 * this should work out with elements with different nesting depths but not being 679 * parent and child to each other 680 * 681 * @return the child elements as array or null if nothing is found 682 * 683 */ 684 findByTagName : function(fragment, tagName) { 685 this._assertStdParams(fragment, tagName, "findByTagName", ["fragment", "tagName"]); 686 var _Lang = this._Lang, 687 nodeType = fragment.nodeType; 688 if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null; 689 690 //remapping to save a few bytes 691 692 var ret = _Lang.objToArray(fragment.getElementsByTagName(tagName)); 693 if (fragment.tagName && _Lang.equalsIgnoreCase(fragment.tagName, tagName)) ret.unshift(fragment); 694 return ret; 695 }, 696 697 findByName : function(fragment, name) { 698 this._assertStdParams(fragment, name, "findByName", ["fragment", "name"]); 699 700 var nodeType = fragment.nodeType; 701 if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null; 702 703 var ret = this._Lang.objToArray(fragment.getElementsByName(name)); 704 if (fragment.name == name) ret.unshift(fragment); 705 return ret; 706 }, 707 708 /** 709 * a filtered findAll for subdom treewalking 710 * (which uses browser optimizations wherever possible) 711 * 712 * @param {|Node|} rootNode the rootNode so start the scan 713 * @param filter filter closure with the syntax {boolean} filter({Node} node) 714 * @param deepScan if set to true or not set at all a deep scan is performed (for form scans it does not make much sense to deeply scan) 715 */ 716 findAll : function(rootNode, filter, deepScan) { 717 this._Lang.assertType(filter, "function"); 718 deepScan = !!deepScan; 719 720 if (document.createTreeWalker && NodeFilter) { 721 return this._iteratorSearchAll(rootNode, filter, deepScan); 722 } else { 723 //will not be called in dom level3 compliant browsers 724 return this._recursionSearchAll(rootNode, filter, deepScan); 725 } 726 }, 727 728 /** 729 * the faster dom iterator based search, works on all newer browsers 730 * except ie8 which already have implemented the dom iterator functions 731 * of html 5 (which is pretty all standard compliant browsers) 732 * 733 * The advantage of this method is a faster tree iteration compared 734 * to the normal recursive tree walking. 735 * 736 * @param rootNode the root node to be iterated over 737 * @param filter the iteration filter 738 * @param deepScan if set to true a deep scan is performed 739 */ 740 _iteratorSearchAll: function(rootNode, filter, deepScan) { 741 var retVal = []; 742 //Works on firefox and webkit, opera and ie have to use the slower fallback mechanis 743 //we have a tree walker in place this allows for an optimized deep scan 744 if (filter(rootNode)) { 745 746 retVal.push(rootNode); 747 if (!deepScan) { 748 return retVal; 749 } 750 } 751 //we use the reject mechanism to prevent a deep scan reject means any 752 //child elements will be omitted from the scan 753 var FILTER_ACCEPT = NodeFilter.FILTER_ACCEPT, 754 FILTER_SKIP = NodeFilter.FILTER_SKIP, 755 FILTER_REJECT = NodeFilter.FILTER_REJECT; 756 757 var walkerFilter = function (node) { 758 var retCode = (filter(node)) ? FILTER_ACCEPT : FILTER_SKIP; 759 retCode = (!deepScan && retCode == FILTER_ACCEPT) ? FILTER_REJECT : retCode; 760 if (retCode == FILTER_ACCEPT || retCode == FILTER_REJECT) { 761 retVal.push(node); 762 } 763 return retCode; 764 }; 765 766 var treeWalker = document.createTreeWalker(rootNode, NodeFilter.SHOW_ELEMENT, walkerFilter, false); 767 //noinspection StatementWithEmptyBodyJS 768 while (treeWalker.nextNode()); 769 return retVal; 770 }, 771 772 /** 773 * bugfixing for ie6 which does not cope properly with setAttribute 774 */ 775 setAttribute : function(node, attr, val) { 776 this._assertStdParams(node, attr, "setAttribute", ["fragment", "name"]); 777 if (!node.setAttribute) { 778 return; 779 } 780 node.setAttribute(attr, val); 781 }, 782 783 /** 784 * fuzzy form detection which tries to determine the form 785 * an item has been detached. 786 * 787 * The problem is some Javascript libraries simply try to 788 * detach controls by reusing the names 789 * of the detached input controls. Most of the times, 790 * the name is unique in a jsf scenario, due to the inherent form mapping. 791 * One way or the other, we will try to fix that by 792 * identifying the proper form over the name 793 * 794 * We do it in several ways, in case of no form null is returned 795 * in case of multiple forms we check all elements with a given name (which we determine 796 * out of a name or id of the detached element) and then iterate over them 797 * to find whether they are in a form or not. 798 * 799 * If only one element within a form and a given identifier found then we can pull out 800 * and move on 801 * 802 * We cannot do much further because in case of two identical named elements 803 * all checks must fail and the first elements form is served. 804 * 805 * Note, this method is only triggered in case of the issuer or an ajax request 806 * is a detached element, otherwise already existing code has served the correct form. 807 * 808 * This method was added because of 809 * https://issues.apache.org/jira/browse/MYFACES-2599 810 * to support the integration of existing ajax libraries which do heavy dom manipulation on the 811 * controls side (Dojos Dijit library for instance). 812 * 813 * @param {Node} elem - element as source, can be detached, undefined or null 814 * 815 * @return either null or a form node if it could be determined 816 * 817 * TODO move this into extended and replace it with a simpler algorithm 818 */ 819 fuzzyFormDetection : function(elem) { 820 var forms = document.forms, _Lang = this._Lang; 821 822 if (!forms || !forms.length) { 823 return null; 824 } 825 826 // This will not work well on portlet case, because we cannot be sure 827 // the returned form is right one. 828 //we can cover that case by simply adding one of our config params 829 //the default is the weaker, but more correct portlet code 830 //you can override it with myfaces_config.no_portlet_env = true globally 831 else if (1 == forms.length && this._RT.getGlobalConfig("no_portlet_env", false)) { 832 return forms[0]; 833 } 834 835 //before going into the more complicated stuff we try the simple approach 836 var finalElem = this.byId(elem); 837 var fetchForm = _Lang.hitch(this, function(elem) { 838 //element of type form then we are already 839 //at form level for the issuing element 840 //https://issues.apache.org/jira/browse/MYFACES-2793 841 842 return (_Lang.equalsIgnoreCase(elem.tagName, "form")) ? elem : 843 ( this.html5FormDetection(elem) || this.getParent(elem, "form")); 844 }); 845 846 if (finalElem) { 847 var elemForm = fetchForm(finalElem); 848 if (elemForm) return elemForm; 849 } 850 851 /** 852 * name check 853 */ 854 var foundElements = []; 855 var name = (_Lang.isString(elem)) ? elem : elem.name; 856 //id detection did not work 857 if (!name) return null; 858 /** 859 * the lesser chance is the elements which have the same name 860 * (which is the more likely case in case of a brute dom replacement) 861 */ 862 var nameElems = document.getElementsByName(name); 863 if (nameElems) { 864 for (var cnt = 0; cnt < nameElems.length && foundElements.length < 2; cnt++) { 865 // we already have covered the identifier case hence we only can deal with names, 866 var foundForm = fetchForm(nameElems[cnt]); 867 if (foundForm) { 868 foundElements.push(foundForm); 869 } 870 } 871 } 872 873 return (1 == foundElements.length ) ? foundElements[0] : null; 874 }, 875 876 html5FormDetection: function(/*item*/) { 877 return null; 878 }, 879 880 881 /** 882 * gets a parent of an item with a given tagname 883 * @param {Node} item - child element 884 * @param {String} tagName - TagName of parent element 885 */ 886 getParent : function(item, tagName) { 887 888 if (!item) { 889 throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "getParent", 890 this._Lang.getMessage("ERR_MUST_BE_PROVIDED1", null, "_Dom.getParent", "item {DomNode}")); 891 } 892 893 var _Lang = this._Lang; 894 var searchClosure = function(parentItem) { 895 return parentItem && parentItem.tagName 896 && _Lang.equalsIgnoreCase(parentItem.tagName, tagName); 897 }; 898 try { 899 return this.getFilteredParent(item, searchClosure); 900 } finally { 901 searchClosure = null; 902 _Lang = null; 903 } 904 }, 905 906 /** 907 * A parent walker which uses 908 * a filter closure for filtering 909 * 910 * @param {Node} item the root item to ascend from 911 * @param {function} filter the filter closure 912 */ 913 getFilteredParent : function(item, filter) { 914 this._assertStdParams(item, filter, "getFilteredParent", ["item", "filter"]); 915 916 //search parent tag parentName 917 var parentItem = (item.parentNode) ? item.parentNode : null; 918 919 while (parentItem && !filter(parentItem)) { 920 parentItem = parentItem.parentNode; 921 } 922 return (parentItem) ? parentItem : null; 923 }, 924 925 /** 926 * cross ported from dojo 927 * fetches an attribute from a node 928 * 929 * @param {String} node the node 930 * @param {String} attr the attribute 931 * @return the attributes value or null 932 */ 933 getAttribute : function(/* HTMLElement */node, /* string */attr) { 934 return node.getAttribute(attr); 935 }, 936 937 /** 938 * checks whether the given node has an attribute attached 939 * 940 * @param {String|Object} node the node to search for 941 * @param {String} attr the attribute to search for 942 * @true if the attribute was found 943 */ 944 hasAttribute : function(/* HTMLElement */node, /* string */attr) { 945 // summary 946 // Determines whether or not the specified node carries a value for the attribute in question. 947 return this.getAttribute(node, attr) ? true : false; // boolean 948 }, 949 950 /** 951 * concatenation routine which concats all childnodes of a node which 952 * contains a set of CDATA blocks to one big string 953 * @param {Node} node the node to concat its blocks for 954 */ 955 concatCDATABlocks : function(/*Node*/ node) { 956 var cDataBlock = []; 957 // response may contain several blocks 958 for (var i = 0; i < node.childNodes.length; i++) { 959 cDataBlock.push(node.childNodes[i].data); 960 } 961 return cDataBlock.join(''); 962 }, 963 964 //all modern browsers evaluate the scripts 965 //manually this is a w3d recommendation 966 isManualScriptEval: function() { 967 return true; 968 }, 969 970 isMultipartCandidate: function(/*executes*/) { 971 //implementation in the experimental part 972 return false; 973 }, 974 975 insertFirst: function(newNode) { 976 var body = document.body; 977 if (body.childNodes.length > 0) { 978 body.insertBefore(newNode, body.firstChild); 979 } else { 980 body.appendChild(newNode); 981 } 982 }, 983 984 byId: function(id) { 985 return this._Lang.byId(id); 986 }, 987 988 getDummyPlaceHolder: function() { 989 this._dummyPlaceHolder = this._dummyPlaceHolder ||this.createElement("div"); 990 return this._dummyPlaceHolder; 991 }, 992 993 /** 994 * fetches the window id for the current request 995 * note, this is a preparation method for jsf 2.2 996 * 997 */ 998 getWindowId: function() { 999 //implementation in the experimental part 1000 return null; 1001 } 1002 }); 1003 1004 1005