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 var itemType = item.type || ""; 126 if(tagName && _Lang.equalsIgnoreCase(tagName, "script") && 127 (itemType === "" || _Lang.equalsIgnoreCase(itemType,"text/javascript") || 128 _Lang.equalsIgnoreCase(itemType,"javascript") || 129 _Lang.equalsIgnoreCase(itemType,"text/ecmascript") || 130 _Lang.equalsIgnoreCase(itemType,"ecmascript"))) { 131 var src = item.getAttribute('src'); 132 if ('undefined' != typeof src 133 && null != src 134 && src.length > 0 135 ) { 136 //we have to move this into an inner if because chrome otherwise chokes 137 //due to changing the and order instead of relying on left to right 138 //if jsf.js is already registered we do not replace it anymore 139 if ((src.indexOf("ln=scripts") == -1 && src.indexOf("ln=javax.faces") == -1) || (src.indexOf("/jsf.js") == -1 140 && src.indexOf("/jsf-uncompressed.js") == -1)) { 141 if (finalScripts.length) { 142 //script source means we have to eval the existing 143 //scripts before running the include 144 _RT.globalEval(finalScripts.join("\n")); 145 146 finalScripts = []; 147 } 148 _RT.loadScriptEval(src, item.getAttribute('type'), false, "UTF-8", false); 149 } 150 151 } else { 152 // embedded script auto eval 153 var test = (!xmlData) ? item.text : _Lang.serializeChilds(item); 154 var go = true; 155 while (go) { 156 go = false; 157 if (test.substring(0, 1) == " ") { 158 test = test.substring(1); 159 go = true; 160 } 161 if (test.substring(0, 4) == "<!--") { 162 test = test.substring(4); 163 go = true; 164 } 165 if (test.substring(0, 11) == "//<![CDATA[") { 166 test = test.substring(11); 167 go = true; 168 } 169 } 170 // we have to run the script under a global context 171 //we store the script for less calls to eval 172 finalScripts.push(test); 173 174 } 175 } 176 }; 177 try { 178 var scriptElements = this.findByTagName(item, "script", true); 179 if (scriptElements == null) return; 180 for (var cnt = 0; cnt < scriptElements.length; cnt++) { 181 execScrpt(scriptElements[cnt]); 182 } 183 if (finalScripts.length) { 184 _RT.globalEval(finalScripts.join("\n")); 185 } 186 } catch (e) { 187 if(window.console && window.console.error) { 188 //not sure if we 189 //should use our standard 190 //error mechanisms here 191 //because in the head appendix 192 //method only a console 193 //error would be raised as well 194 console.error(e.message||e.description); 195 } else { 196 if(jsf.ajax.getProjectStage() === "Development") { 197 alert("Error in evaluated javascript:"+ (e.message||e.description)); 198 } 199 } 200 } finally { 201 //the usual ie6 fix code 202 //the IE6 garbage collector is broken 203 //nulling closures helps somewhat to reduce 204 //mem leaks, which are impossible to avoid 205 //at this browser 206 execScrpt = null; 207 } 208 }, 209 210 211 /** 212 * determines to fetch a node 213 * from its id or name, the name case 214 * only works if the element is unique in its name 215 * @param {String} elem 216 */ 217 byIdOrName: function(elem) { 218 if (!elem) return null; 219 if (!this._Lang.isString(elem)) return elem; 220 221 var ret = this.byId(elem); 222 if (ret) return ret; 223 //we try the unique name fallback 224 var items = document.getElementsByName(elem); 225 return ((items.length == 1) ? items[0] : null); 226 }, 227 228 /** 229 * node id or name, determines the valid form identifier of a node 230 * depending on its uniqueness 231 * 232 * Usually the id is chosen for an elem, but if the id does not 233 * exist we try a name fallback. If the passed element has a unique 234 * name we can use that one as subsequent identifier. 235 * 236 * 237 * @param {String} elem 238 */ 239 nodeIdOrName: function(elem) { 240 if (elem) { 241 //just to make sure that the pas 242 243 elem = this.byId(elem); 244 if (!elem) return null; 245 //detached element handling, we also store the element name 246 //to get a fallback option in case the identifier is not determinable 247 // anymore, in case of a framework induced detachment the element.name should 248 // be shared if the identifier is not determinable anymore 249 //the downside of this method is the element name must be unique 250 //which in case of jsf it is 251 var elementId = elem.id || elem.name; 252 if ((elem.id == null || elem.id == '') && elem.name) { 253 elementId = elem.name; 254 255 //last check for uniqueness 256 if (this.getElementsByName(elementId).length > 1) { 257 //no unique element name so we need to perform 258 //a return null to let the caller deal with this issue 259 return null; 260 } 261 } 262 return elementId; 263 } 264 return null; 265 }, 266 267 deleteItems: function(items) { 268 if (! items || ! items.length) return; 269 for (var cnt = 0; cnt < items.length; cnt++) { 270 this.deleteItem(items[cnt]); 271 } 272 }, 273 274 /** 275 * Simple delete on an existing item 276 */ 277 deleteItem: function(itemIdToReplace) { 278 var item = this.byId(itemIdToReplace); 279 if (!item) { 280 throw this._Lang.makeException(new Error(),null, null, this._nameSpace, "deleteItem", "_Dom.deleteItem Unknown Html-Component-ID: " + itemIdToReplace); 281 } 282 283 this._removeNode(item, false); 284 }, 285 286 /** 287 * creates a node upon a given node name 288 * @param nodeName {String} the node name to be created 289 * @param attrs {Array} a set of attributes to be set 290 */ 291 createElement: function(nodeName, attrs) { 292 var ret = document.createElement(nodeName); 293 if (attrs) { 294 for (var key in attrs) { 295 if(!attrs.hasOwnProperty(key)) continue; 296 this.setAttribute(ret, key, attrs[key]); 297 } 298 } 299 return ret; 300 }, 301 302 /** 303 * Checks whether the browser is dom compliant. 304 * Dom compliant means that it performs the basic dom operations safely 305 * without leaking and also is able to perform a native setAttribute 306 * operation without freaking out 307 * 308 * 309 * Not dom compliant browsers are all microsoft browsers in quirks mode 310 * and ie6 and ie7 to some degree in standards mode 311 * and pretty much every browser who cannot create ranges 312 * (older mobile browsers etc...) 313 * 314 * We dont do a full browser detection here because it probably is safer 315 * to test for existing features to make an assumption about the 316 * browsers capabilities 317 */ 318 isDomCompliant: function() { 319 return true; 320 }, 321 322 /** 323 * proper insert before which takes tables into consideration as well as 324 * browser deficiencies 325 * @param item the node to insert before 326 * @param markup the markup to be inserted 327 */ 328 insertBefore: function(item, markup) { 329 this._assertStdParams(item, markup, "insertBefore"); 330 331 markup = this._Lang.trim(markup); 332 if (markup === "") return null; 333 334 var evalNodes = this._buildEvalNodes(item, markup), 335 currentRef = item, 336 parentNode = item.parentNode, 337 ret = []; 338 for (var cnt = evalNodes.length - 1; cnt >= 0; cnt--) { 339 currentRef = parentNode.insertBefore(evalNodes[cnt], currentRef); 340 ret.push(currentRef); 341 } 342 ret = ret.reverse(); 343 this._eval(ret); 344 return ret; 345 }, 346 347 /** 348 * proper insert before which takes tables into consideration as well as 349 * browser deficiencies 350 * @param item the node to insert before 351 * @param markup the markup to be inserted 352 */ 353 insertAfter: function(item, markup) { 354 this._assertStdParams(item, markup, "insertAfter"); 355 markup = this._Lang.trim(markup); 356 if (markup === "") return null; 357 358 var evalNodes = this._buildEvalNodes(item, markup), 359 currentRef = item, 360 parentNode = item.parentNode, 361 ret = []; 362 363 for (var cnt = 0; cnt < evalNodes.length; cnt++) { 364 if (currentRef.nextSibling) { 365 //Winmobile 6 has problems with this strategy, but it is not really fixable 366 currentRef = parentNode.insertBefore(evalNodes[cnt], currentRef.nextSibling); 367 } else { 368 currentRef = parentNode.appendChild(evalNodes[cnt]); 369 } 370 ret.push(currentRef); 371 } 372 this._eval(ret); 373 return ret; 374 }, 375 376 propertyToAttribute: function(name) { 377 if (name === 'className') { 378 return 'class'; 379 } else if (name === 'xmllang') { 380 return 'xml:lang'; 381 } else { 382 return name.toLowerCase(); 383 } 384 }, 385 386 isFunctionNative: function(func) { 387 return /^\s*function[^{]+{\s*\[native code\]\s*}\s*$/.test(String(func)); 388 }, 389 390 detectAttributes: function(element) { 391 //test if 'hasAttribute' method is present and its native code is intact 392 //for example, Prototype can add its own implementation if missing 393 if (element.hasAttribute && this.isFunctionNative(element.hasAttribute)) { 394 return function(name) { 395 return element.hasAttribute(name); 396 } 397 } else { 398 try { 399 //when accessing .getAttribute method without arguments does not throw an error then the method is not available 400 element.getAttribute; 401 402 var html = element.outerHTML; 403 var startTag = html.match(/^<[^>]*>/)[0]; 404 return function(name) { 405 return startTag.indexOf(name + '=') > -1; 406 } 407 } catch (ex) { 408 return function(name) { 409 return element.getAttribute(name); 410 } 411 } 412 } 413 }, 414 415 /** 416 * copy all attributes from one element to another - except id 417 * @param target element to copy attributes to 418 * @param source element to copy attributes from 419 * @ignore 420 */ 421 cloneAttributes: function(target, source) { 422 423 // enumerate core element attributes - without 'dir' as special case 424 var coreElementProperties = ['className', 'title', 'lang', 'xmllang']; 425 // enumerate additional input element attributes 426 var inputElementProperties = [ 427 'name', 'value', 'size', 'maxLength', 'src', 'alt', 'useMap', 'tabIndex', 'accessKey', 'accept', 'type' 428 ]; 429 // enumerate additional boolean input attributes 430 var inputElementBooleanProperties = [ 431 'checked', 'disabled', 'readOnly' 432 ]; 433 434 // Enumerate all the names of the event listeners 435 var listenerNames = 436 [ 'onclick', 'ondblclick', 'onmousedown', 'onmousemove', 'onmouseout', 437 'onmouseover', 'onmouseup', 'onkeydown', 'onkeypress', 'onkeyup', 438 'onhelp', 'onblur', 'onfocus', 'onchange', 'onload', 'onunload', 'onabort', 439 'onreset', 'onselect', 'onsubmit' 440 ]; 441 442 var sourceAttributeDetector = this.detectAttributes(source); 443 var targetAttributeDetector = this.detectAttributes(target); 444 445 var isInputElement = target.nodeName.toLowerCase() === 'input'; 446 var propertyNames = isInputElement ? coreElementProperties.concat(inputElementProperties) : coreElementProperties; 447 var isXML = !source.ownerDocument.contentType || source.ownerDocument.contentType == 'text/xml'; 448 for (var iIndex = 0, iLength = propertyNames.length; iIndex < iLength; iIndex++) { 449 var propertyName = propertyNames[iIndex]; 450 var attributeName = this.propertyToAttribute(propertyName); 451 if (sourceAttributeDetector(attributeName)) { 452 453 //With IE 7 (quirks or standard mode) and IE 8/9 (quirks mode only), 454 //you cannot get the attribute using 'class'. You must use 'className' 455 //which is the same value you use to get the indexed property. The only 456 //reliable way to detect this (without trying to evaluate the browser 457 //mode and version) is to compare the two return values using 'className' 458 //to see if they exactly the same. If they are, then use the property 459 //name when using getAttribute. 460 if( attributeName == 'class'){ 461 if( this._RT.browser.isIE && (source.getAttribute(propertyName) === source[propertyName]) ){ 462 attributeName = propertyName; 463 } 464 } 465 466 var newValue = isXML ? source.getAttribute(attributeName) : source[propertyName]; 467 var oldValue = target[propertyName]; 468 if (oldValue != newValue) { 469 target[propertyName] = newValue; 470 } 471 } else { 472 target.removeAttribute(attributeName); 473 if (attributeName == "value") { 474 target[propertyName] = ''; 475 } 476 } 477 } 478 479 var booleanPropertyNames = isInputElement ? inputElementBooleanProperties : []; 480 for (var jIndex = 0, jLength = booleanPropertyNames.length; jIndex < jLength; jIndex++) { 481 var booleanPropertyName = booleanPropertyNames[jIndex]; 482 var newBooleanValue = source[booleanPropertyName]; 483 var oldBooleanValue = target[booleanPropertyName]; 484 if (oldBooleanValue != newBooleanValue) { 485 target[booleanPropertyName] = newBooleanValue; 486 } 487 } 488 489 //'style' attribute special case 490 if (sourceAttributeDetector('style')) { 491 var newStyle; 492 var oldStyle; 493 if (this._RT.browser.isIE) { 494 newStyle = source.style.cssText; 495 oldStyle = target.style.cssText; 496 if (newStyle != oldStyle) { 497 target.style.cssText = newStyle; 498 } 499 } else { 500 newStyle = source.getAttribute('style'); 501 oldStyle = target.getAttribute('style'); 502 if (newStyle != oldStyle) { 503 target.setAttribute('style', newStyle); 504 } 505 } 506 } else if (targetAttributeDetector('style')){ 507 target.removeAttribute('style'); 508 } 509 510 // Special case for 'dir' attribute 511 if (!this._RT.browser.isIE && source.dir != target.dir) { 512 if (sourceAttributeDetector('dir')) { 513 target.dir = source.dir; 514 } else if (targetAttributeDetector('dir')) { 515 target.dir = ''; 516 } 517 } 518 519 for (var lIndex = 0, lLength = listenerNames.length; lIndex < lLength; lIndex++) { 520 var name = listenerNames[lIndex]; 521 target[name] = source[name] ? source[name] : null; 522 if (source[name]) { 523 source[name] = null; 524 } 525 } 526 527 //clone HTML5 data-* attributes 528 try{ 529 var targetDataset = target.dataset; 530 var sourceDataset = source.dataset; 531 if (targetDataset || sourceDataset) { 532 //cleanup the dataset 533 for (var tp in targetDataset) { 534 delete targetDataset[tp]; 535 } 536 //copy dataset's properties 537 for (var sp in sourceDataset) { 538 targetDataset[sp] = sourceDataset[sp]; 539 } 540 } 541 } catch (ex) { 542 //most probably dataset properties are not supported 543 } 544 }, 545 //from 546 // http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/ 547 getCaretPosition:function (ctrl) { 548 var caretPos = 0; 549 550 try { 551 552 // other browsers make it simpler by simply having a selection start element 553 if (ctrl.selectionStart || ctrl.selectionStart == '0') 554 caretPos = ctrl.selectionStart; 555 // ie 5 quirks mode as second option because 556 // this option is flakey in conjunction with text areas 557 // TODO move this into the quirks class 558 else if (document.selection) { 559 ctrl.focus(); 560 var selection = document.selection.createRange(); 561 //the selection now is start zero 562 selection.moveStart('character', -ctrl.value.length); 563 //the caretposition is the selection start 564 caretPos = selection.text.length; 565 } 566 } catch (e) { 567 //now this is ugly, but not supported input types throw errors for selectionStart 568 //this way we are future proof by having not to define every selection enabled 569 //input in an if (which will be a lot in the near future with html5) 570 } 571 return caretPos; 572 }, 573 574 setCaretPosition:function (ctrl, pos) { 575 576 if (ctrl.createTextRange) { 577 var range = ctrl.createTextRange(); 578 range.collapse(true); 579 range.moveEnd('character', pos); 580 range.moveStart('character', pos); 581 range.select(); 582 } 583 //IE quirks mode again, TODO move this into the quirks class 584 else if (ctrl.setSelectionRange) { 585 ctrl.focus(); 586 //the selection range is our caret position 587 ctrl.setSelectionRange(pos, pos); 588 } 589 }, 590 591 /** 592 * outerHTML replacement which works cross browserlike 593 * but still is speed optimized 594 * 595 * @param item the item to be replaced 596 * @param markup the markup for the replacement 597 * @param preserveFocus, tries to preserve the focus within the outerhtml operation 598 * if set to true a focus preservation algorithm based on document.activeElement is 599 * used to preserve the focus at the exactly same location as it was 600 * 601 */ 602 outerHTML : function(item, markup, preserveFocus) { 603 this._assertStdParams(item, markup, "outerHTML"); 604 // we can work on a single element in a cross browser fashion 605 // regarding the focus thanks to the 606 // icefaces team for providing the code 607 if (item.nodeName.toLowerCase() === 'input') { 608 var replacingInput = this._buildEvalNodes(item, markup)[0]; 609 this.cloneAttributes(item, replacingInput); 610 return item; 611 } else { 612 markup = this._Lang.trim(markup); 613 if (markup !== "") { 614 var ret = null; 615 616 var focusElementId = null; 617 var caretPosition = 0; 618 if (preserveFocus && 'undefined' != typeof document.activeElement) { 619 focusElementId = (document.activeElement) ? document.activeElement.id : null; 620 caretPosition = this.getCaretPosition(document.activeElement); 621 } 622 // we try to determine the browsers compatibility 623 // level to standards dom level 2 via various methods 624 if (this.isDomCompliant()) { 625 ret = this._outerHTMLCompliant(item, markup); 626 } else { 627 //call into abstract method 628 ret = this._outerHTMLNonCompliant(item, markup); 629 } 630 if (focusElementId) { 631 var newFocusElement = this.byId(focusElementId); 632 if (newFocusElement && newFocusElement.nodeName.toLowerCase() === 'input') { 633 //just in case the replacement element is not focusable anymore 634 if ("undefined" != typeof newFocusElement.focus) { 635 newFocusElement.focus(); 636 } 637 } 638 if (caretPosition) { 639 //zero caret position is set automatically on focus 640 this.setCaretPosition(newFocusElement, caretPosition); 641 } 642 } 643 644 // and remove the old item 645 //first we have to save the node newly insert for easier access in our eval part 646 this._eval(ret); 647 return ret; 648 } 649 // and remove the old item, in case of an empty newtag and do nothing else 650 this._removeNode(item, false); 651 return null; 652 } 653 }, 654 655 /** 656 * detaches a set of nodes from their parent elements 657 * in a browser independend manner 658 * @param {Object} items the items which need to be detached 659 * @return {Array} an array of nodes with the detached dom nodes 660 */ 661 detach: function(items) { 662 var ret = []; 663 if ('undefined' != typeof items.nodeType) { 664 if (items.parentNode) { 665 ret.push(items.parentNode.removeChild(items)); 666 } else { 667 ret.push(items); 668 } 669 return ret; 670 } 671 //all ies treat node lists not as arrays so we have to take 672 //an intermediate step 673 var nodeArr = this._Lang.objToArray(items); 674 for (var cnt = 0; cnt < nodeArr.length; cnt++) { 675 ret.push(nodeArr[cnt].parentNode.removeChild(nodeArr[cnt])); 676 } 677 return ret; 678 }, 679 680 _outerHTMLCompliant: function(item, markup) { 681 //table element replacements like thead, tbody etc... have to be treated differently 682 var evalNodes = this._buildEvalNodes(item, markup); 683 684 if (evalNodes.length == 1) { 685 var ret = evalNodes[0]; 686 item.parentNode.replaceChild(ret, item); 687 return ret; 688 } else { 689 return this.replaceElements(item, evalNodes); 690 } 691 }, 692 693 694 695 /** 696 * checks if the provided element is a subelement of a table element 697 * @param item 698 */ 699 _isTableElement: function(item) { 700 return !!this.TABLE_ELEMS[(item.nodeName || item.tagName).toLowerCase()]; 701 }, 702 703 /** 704 * non ie browsers do not have problems with embedded scripts or any other construct 705 * we simply can use an innerHTML in a placeholder 706 * 707 * @param markup the markup to be used 708 */ 709 _buildNodesCompliant: function(markup) { 710 var dummyPlaceHolder = this.getDummyPlaceHolder(); //document.createElement("div"); 711 dummyPlaceHolder.innerHTML = markup; 712 return this._Lang.objToArray(dummyPlaceHolder.childNodes); 713 }, 714 715 716 717 718 /** 719 * builds up a correct dom subtree 720 * if the markup is part of table nodes 721 * The usecase for this is to allow subtable rendering 722 * like single rows thead or tbody 723 * 724 * @param item 725 * @param markup 726 */ 727 _buildTableNodes: function(item, markup) { 728 var itemNodeName = (item.nodeName || item.tagName).toLowerCase(); 729 730 var tmpNodeName = itemNodeName; 731 var depth = 0; 732 while (tmpNodeName != "table") { 733 item = item.parentNode; 734 tmpNodeName = (item.nodeName || item.tagName).toLowerCase(); 735 depth++; 736 } 737 738 var dummyPlaceHolder = this.getDummyPlaceHolder(); 739 if (itemNodeName == "td") { 740 dummyPlaceHolder.innerHTML = "<table><tbody><tr>" + markup + "</tr></tbody></table>"; 741 } else { 742 dummyPlaceHolder.innerHTML = "<table>" + markup + "</table>"; 743 } 744 745 for (var cnt = 0; cnt < depth; cnt++) { 746 dummyPlaceHolder = dummyPlaceHolder.childNodes[0]; 747 } 748 749 return this.detach(dummyPlaceHolder.childNodes); 750 }, 751 752 _removeChildNodes: function(node /*, breakEventsOpen */) { 753 if (!node) return; 754 node.innerHTML = ""; 755 }, 756 757 758 759 _removeNode: function(node /*, breakEventsOpen*/) { 760 if (!node) return; 761 var parentNode = node.parentNode; 762 if (parentNode) //if the node has a parent 763 parentNode.removeChild(node); 764 }, 765 766 767 /** 768 * build up the nodes from html markup in a browser independend way 769 * so that it also works with table nodes 770 * 771 * @param item the parent item upon the nodes need to be processed upon after building 772 * @param markup the markup to be built up 773 */ 774 _buildEvalNodes: function(item, markup) { 775 var evalNodes = null; 776 if (this._isTableElement(item)) { 777 evalNodes = this._buildTableNodes(item, markup); 778 } else { 779 var nonIEQuirks = (!this._RT.browser.isIE || this._RT.browser.isIE > 8); 780 //ie8 has a special problem it still has the swallow scripts and other 781 //elements bug, but it is mostly dom compliant so we have to give it a special 782 //treatment, IE9 finally fixes that issue finally after 10 years 783 evalNodes = (this.isDomCompliant() && nonIEQuirks) ? 784 this._buildNodesCompliant(markup) : 785 //ie8 or quirks mode browsers 786 this._buildNodesNonCompliant(markup); 787 } 788 return evalNodes; 789 }, 790 791 /** 792 * we have lots of methods with just an item and a markup as params 793 * this method builds an assertion for those methods to reduce code 794 * 795 * @param item the item to be tested 796 * @param markup the mark 797 * @param caller 798 */ 799 _assertStdParams: function(item, markup, caller, params) { 800 //internal error 801 if (!caller) { 802 throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "_assertStdParams", "Caller must be set for assertion"); 803 } 804 var _Lang = this._Lang, 805 ERR_PROV = "ERR_MUST_BE_PROVIDED1", 806 DOM = "myfaces._impl._util._Dom.", 807 finalParams = params || ["item", "markup"]; 808 809 if (!item || !markup) { 810 _Lang.makeException(new Error(), null, null,DOM, ""+caller, _Lang.getMessage(ERR_PROV, null, DOM +"."+ caller, (!item) ? finalParams[0] : finalParams[1])); 811 //throw Error(_Lang.getMessage(ERR_PROV, null, DOM + caller, (!item) ? params[0] : params[1])); 812 } 813 }, 814 815 /** 816 * internal eval handler used by various functions 817 * @param _nodeArr 818 */ 819 _eval: function(_nodeArr) { 820 if (this.isManualScriptEval()) { 821 var isArr = _nodeArr instanceof Array; 822 if (isArr && _nodeArr.length) { 823 for (var cnt = 0; cnt < _nodeArr.length; cnt++) { 824 this.runScripts(_nodeArr[cnt]); 825 } 826 } else if (!isArr) { 827 this.runScripts(_nodeArr); 828 } 829 } 830 }, 831 832 /** 833 * for performance reasons we work with replaceElement and replaceElements here 834 * after measuring performance it has shown that passing down an array instead 835 * of a single node makes replaceElement twice as slow, however 836 * a single node case is the 95% case 837 * 838 * @param item 839 * @param evalNode 840 */ 841 replaceElement: function(item, evalNode) { 842 //browsers with defect garbage collection 843 item.parentNode.insertBefore(evalNode, item); 844 this._removeNode(item, false); 845 }, 846 847 848 /** 849 * replaces an element with another element or a set of elements 850 * 851 * @param item the item to be replaced 852 * 853 * @param evalNodes the elements 854 */ 855 replaceElements: function (item, evalNodes) { 856 var evalNodesDefined = evalNodes && 'undefined' != typeof evalNodes.length; 857 if (!evalNodesDefined) { 858 throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "replaceElements", this._Lang.getMessage("ERR_REPLACE_EL")); 859 } 860 861 var parentNode = item.parentNode, 862 863 sibling = item.nextSibling, 864 resultArr = this._Lang.objToArray(evalNodes); 865 866 for (var cnt = 0; cnt < resultArr.length; cnt++) { 867 if (cnt == 0) { 868 this.replaceElement(item, resultArr[cnt]); 869 } else { 870 if (sibling) { 871 parentNode.insertBefore(resultArr[cnt], sibling); 872 } else { 873 parentNode.appendChild(resultArr[cnt]); 874 } 875 } 876 } 877 return resultArr; 878 }, 879 880 /** 881 * optimized search for an array of tag names 882 * deep scan will always be performed. 883 * @param fragment the fragment which should be searched for 884 * @param tagNames an map indx of tag names which have to be found 885 * 886 */ 887 findByTagNames: function(fragment, tagNames) { 888 this._assertStdParams(fragment, tagNames, "findByTagNames", ["fragment", "tagNames"]); 889 890 var nodeType = fragment.nodeType; 891 if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null; 892 893 //we can use the shortcut 894 if (fragment.querySelectorAll) { 895 var query = []; 896 for (var key in tagNames) { 897 if(!tagNames.hasOwnProperty(key)) continue; 898 query.push(key); 899 } 900 var res = []; 901 if (fragment.tagName && tagNames[fragment.tagName.toLowerCase()]) { 902 res.push(fragment); 903 } 904 return res.concat(this._Lang.objToArray(fragment.querySelectorAll(query.join(", ")))); 905 } 906 907 //now the filter function checks case insensitively for the tag names needed 908 var filter = function(node) { 909 return node.tagName && tagNames[node.tagName.toLowerCase()]; 910 }; 911 912 //now we run an optimized find all on it 913 try { 914 return this.findAll(fragment, filter, true); 915 } finally { 916 //the usual IE6 is broken, fix code 917 filter = null; 918 } 919 }, 920 921 /** 922 * determines the number of nodes according to their tagType 923 * 924 * @param {Node} fragment (Node or fragment) the fragment to be investigated 925 * @param {String} tagName the tag name (lowercase) 926 * (the normal usecase is false, which means if the element is found only its 927 * adjacent elements will be scanned, due to the recursive descension 928 * this should work out with elements with different nesting depths but not being 929 * parent and child to each other 930 * 931 * @return the child elements as array or null if nothing is found 932 * 933 */ 934 findByTagName : function(fragment, tagName) { 935 this._assertStdParams(fragment, tagName, "findByTagName", ["fragment", "tagName"]); 936 var _Lang = this._Lang, 937 nodeType = fragment.nodeType; 938 if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null; 939 940 //remapping to save a few bytes 941 942 var ret = _Lang.objToArray(fragment.getElementsByTagName(tagName)); 943 if (fragment.tagName && _Lang.equalsIgnoreCase(fragment.tagName, tagName)) ret.unshift(fragment); 944 return ret; 945 }, 946 947 findByName : function(fragment, name) { 948 this._assertStdParams(fragment, name, "findByName", ["fragment", "name"]); 949 950 var nodeType = fragment.nodeType; 951 if (nodeType != 1 && nodeType != 9 && nodeType != 11) return null; 952 953 var ret = this._Lang.objToArray(fragment.getElementsByName(name)); 954 if (fragment.name == name) ret.unshift(fragment); 955 return ret; 956 }, 957 958 /** 959 * a filtered findAll for subdom treewalking 960 * (which uses browser optimizations wherever possible) 961 * 962 * @param {|Node|} rootNode the rootNode so start the scan 963 * @param filter filter closure with the syntax {boolean} filter({Node} node) 964 * @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) 965 */ 966 findAll : function(rootNode, filter, deepScan) { 967 this._Lang.assertType(filter, "function"); 968 deepScan = !!deepScan; 969 970 if (document.createTreeWalker && NodeFilter) { 971 return this._iteratorSearchAll(rootNode, filter, deepScan); 972 } else { 973 //will not be called in dom level3 compliant browsers 974 return this._recursionSearchAll(rootNode, filter, deepScan); 975 } 976 }, 977 978 /** 979 * the faster dom iterator based search, works on all newer browsers 980 * except ie8 which already have implemented the dom iterator functions 981 * of html 5 (which is pretty all standard compliant browsers) 982 * 983 * The advantage of this method is a faster tree iteration compared 984 * to the normal recursive tree walking. 985 * 986 * @param rootNode the root node to be iterated over 987 * @param filter the iteration filter 988 * @param deepScan if set to true a deep scan is performed 989 */ 990 _iteratorSearchAll: function(rootNode, filter, deepScan) { 991 var retVal = []; 992 //Works on firefox and webkit, opera and ie have to use the slower fallback mechanis 993 //we have a tree walker in place this allows for an optimized deep scan 994 if (filter(rootNode)) { 995 996 retVal.push(rootNode); 997 if (!deepScan) { 998 return retVal; 999 } 1000 } 1001 //we use the reject mechanism to prevent a deep scan reject means any 1002 //child elements will be omitted from the scan 1003 var FILTER_ACCEPT = NodeFilter.FILTER_ACCEPT, 1004 FILTER_SKIP = NodeFilter.FILTER_SKIP, 1005 FILTER_REJECT = NodeFilter.FILTER_REJECT; 1006 1007 var walkerFilter = function (node) { 1008 var retCode = (filter(node)) ? FILTER_ACCEPT : FILTER_SKIP; 1009 retCode = (!deepScan && retCode == FILTER_ACCEPT) ? FILTER_REJECT : retCode; 1010 if (retCode == FILTER_ACCEPT || retCode == FILTER_REJECT) { 1011 retVal.push(node); 1012 } 1013 return retCode; 1014 }; 1015 1016 var treeWalker = document.createTreeWalker(rootNode, NodeFilter.SHOW_ELEMENT, walkerFilter, false); 1017 //noinspection StatementWithEmptyBodyJS 1018 while (treeWalker.nextNode()); 1019 return retVal; 1020 }, 1021 1022 /** 1023 * bugfixing for ie6 which does not cope properly with setAttribute 1024 */ 1025 setAttribute : function(node, attr, val) { 1026 this._assertStdParams(node, attr, "setAttribute", ["fragment", "name"]); 1027 if (!node.setAttribute) { 1028 return; 1029 } 1030 node.setAttribute(attr, val); 1031 }, 1032 1033 /** 1034 * fuzzy form detection which tries to determine the form 1035 * an item has been detached. 1036 * 1037 * The problem is some Javascript libraries simply try to 1038 * detach controls by reusing the names 1039 * of the detached input controls. Most of the times, 1040 * the name is unique in a jsf scenario, due to the inherent form mapping. 1041 * One way or the other, we will try to fix that by 1042 * identifying the proper form over the name 1043 * 1044 * We do it in several ways, in case of no form null is returned 1045 * in case of multiple forms we check all elements with a given name (which we determine 1046 * out of a name or id of the detached element) and then iterate over them 1047 * to find whether they are in a form or not. 1048 * 1049 * If only one element within a form and a given identifier found then we can pull out 1050 * and move on 1051 * 1052 * We cannot do much further because in case of two identical named elements 1053 * all checks must fail and the first elements form is served. 1054 * 1055 * Note, this method is only triggered in case of the issuer or an ajax request 1056 * is a detached element, otherwise already existing code has served the correct form. 1057 * 1058 * This method was added because of 1059 * https://issues.apache.org/jira/browse/MYFACES-2599 1060 * to support the integration of existing ajax libraries which do heavy dom manipulation on the 1061 * controls side (Dojos Dijit library for instance). 1062 * 1063 * @param {Node} elem - element as source, can be detached, undefined or null 1064 * 1065 * @return either null or a form node if it could be determined 1066 * 1067 * TODO move this into extended and replace it with a simpler algorithm 1068 */ 1069 fuzzyFormDetection : function(elem) { 1070 var forms = document.forms, _Lang = this._Lang; 1071 1072 if (!forms || !forms.length) { 1073 return null; 1074 } 1075 1076 // This will not work well on portlet case, because we cannot be sure 1077 // the returned form is right one. 1078 //we can cover that case by simply adding one of our config params 1079 //the default is the weaker, but more correct portlet code 1080 //you can override it with myfaces_config.no_portlet_env = true globally 1081 else if (1 == forms.length && this._RT.getGlobalConfig("no_portlet_env", false)) { 1082 return forms[0]; 1083 } 1084 1085 //before going into the more complicated stuff we try the simple approach 1086 var finalElem = this.byId(elem); 1087 var fetchForm = _Lang.hitch(this, function(elem) { 1088 //element of type form then we are already 1089 //at form level for the issuing element 1090 //https://issues.apache.org/jira/browse/MYFACES-2793 1091 1092 return (_Lang.equalsIgnoreCase(elem.tagName, "form")) ? elem : 1093 ( this.html5FormDetection(elem) || this.getParent(elem, "form")); 1094 }); 1095 1096 if (finalElem) { 1097 var elemForm = fetchForm(finalElem); 1098 if (elemForm) return elemForm; 1099 } 1100 1101 /** 1102 * name check 1103 */ 1104 var foundElements = []; 1105 var name = (_Lang.isString(elem)) ? elem : elem.name; 1106 //id detection did not work 1107 if (!name) return null; 1108 /** 1109 * the lesser chance is the elements which have the same name 1110 * (which is the more likely case in case of a brute dom replacement) 1111 */ 1112 var nameElems = document.getElementsByName(name); 1113 if (nameElems) { 1114 for (var cnt = 0; cnt < nameElems.length && foundElements.length < 2; cnt++) { 1115 // we already have covered the identifier case hence we only can deal with names, 1116 var foundForm = fetchForm(nameElems[cnt]); 1117 if (foundForm) { 1118 foundElements.push(foundForm); 1119 } 1120 } 1121 } 1122 1123 return (1 == foundElements.length ) ? foundElements[0] : null; 1124 }, 1125 1126 html5FormDetection: function(/*item*/) { 1127 return null; 1128 }, 1129 1130 1131 /** 1132 * gets a parent of an item with a given tagname 1133 * @param {Node} item - child element 1134 * @param {String} tagName - TagName of parent element 1135 */ 1136 getParent : function(item, tagName) { 1137 1138 if (!item) { 1139 throw this._Lang.makeException(new Error(), null, null, this._nameSpace, "getParent", 1140 this._Lang.getMessage("ERR_MUST_BE_PROVIDED1", null, "_Dom.getParent", "item {DomNode}")); 1141 } 1142 1143 var _Lang = this._Lang; 1144 var searchClosure = function(parentItem) { 1145 return parentItem && parentItem.tagName 1146 && _Lang.equalsIgnoreCase(parentItem.tagName, tagName); 1147 }; 1148 try { 1149 return this.getFilteredParent(item, searchClosure); 1150 } finally { 1151 searchClosure = null; 1152 _Lang = null; 1153 } 1154 }, 1155 1156 /** 1157 * A parent walker which uses 1158 * a filter closure for filtering 1159 * 1160 * @param {Node} item the root item to ascend from 1161 * @param {function} filter the filter closure 1162 */ 1163 getFilteredParent : function(item, filter) { 1164 this._assertStdParams(item, filter, "getFilteredParent", ["item", "filter"]); 1165 1166 //search parent tag parentName 1167 var parentItem = (item.parentNode) ? item.parentNode : null; 1168 1169 while (parentItem && !filter(parentItem)) { 1170 parentItem = parentItem.parentNode; 1171 } 1172 return (parentItem) ? parentItem : null; 1173 }, 1174 1175 /** 1176 * cross ported from dojo 1177 * fetches an attribute from a node 1178 * 1179 * @param {String} node the node 1180 * @param {String} attr the attribute 1181 * @return the attributes value or null 1182 */ 1183 getAttribute : function(/* HTMLElement */node, /* string */attr) { 1184 return node.getAttribute(attr); 1185 }, 1186 1187 /** 1188 * checks whether the given node has an attribute attached 1189 * 1190 * @param {String|Object} node the node to search for 1191 * @param {String} attr the attribute to search for 1192 * @true if the attribute was found 1193 */ 1194 hasAttribute : function(/* HTMLElement */node, /* string */attr) { 1195 // summary 1196 // Determines whether or not the specified node carries a value for the attribute in question. 1197 return this.getAttribute(node, attr) ? true : false; // boolean 1198 }, 1199 1200 /** 1201 * concatenation routine which concats all childnodes of a node which 1202 * contains a set of CDATA blocks to one big string 1203 * @param {Node} node the node to concat its blocks for 1204 */ 1205 concatCDATABlocks : function(/*Node*/ node) { 1206 var cDataBlock = []; 1207 // response may contain several blocks 1208 for (var i = 0; i < node.childNodes.length; i++) { 1209 cDataBlock.push(node.childNodes[i].data); 1210 } 1211 return cDataBlock.join(''); 1212 }, 1213 1214 //all modern browsers evaluate the scripts 1215 //manually this is a w3d recommendation 1216 isManualScriptEval: function() { 1217 return true; 1218 }, 1219 1220 isMultipartCandidate: function(/*executes*/) { 1221 //implementation in the experimental part 1222 return false; 1223 }, 1224 1225 insertFirst: function(newNode) { 1226 var body = document.body; 1227 if (body.childNodes.length > 0) { 1228 body.insertBefore(newNode, body.firstChild); 1229 } else { 1230 body.appendChild(newNode); 1231 } 1232 }, 1233 1234 byId: function(id) { 1235 return this._Lang.byId(id); 1236 }, 1237 1238 getDummyPlaceHolder: function() { 1239 this._dummyPlaceHolder = this._dummyPlaceHolder ||this.createElement("div"); 1240 return this._dummyPlaceHolder; 1241 }, 1242 1243 /** 1244 * fetches the window id for the current request 1245 * note, this is a preparation method for jsf 2.2 1246 * 1247 */ 1248 getWindowId: function() { 1249 //implementation in the experimental part 1250 return null; 1251 } 1252 }); 1253 1254 1255