2 * Copyright (C) 2007 Apple Inc. All rights reserved.
3 * Copyright (C) 2012 Google Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15 * its contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * Contains diff method based on Javascript Diff Algorithm By John Resig
30 * http://ejohn.org/files/jsdiff.js (released under the MIT license).
34 * @param {number} offset
35 * @param {string} stopCharacters
36 * @param {!Node} stayWithinNode
37 * @param {string=} direction
40 Node.prototype.rangeOfWord = function(offset, stopCharacters, stayWithinNode, direction)
48 stayWithinNode = this;
50 if (!direction || direction === "backward" || direction === "both") {
53 if (node === stayWithinNode) {
55 startNode = stayWithinNode;
59 if (node.nodeType === Node.TEXT_NODE) {
60 var start = (node === this ? (offset - 1) : (node.nodeValue.length - 1));
61 for (var i = start; i >= 0; --i) {
62 if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
73 node = node.traversePreviousNode(stayWithinNode);
77 startNode = stayWithinNode;
85 if (!direction || direction === "forward" || direction === "both") {
88 if (node === stayWithinNode) {
90 endNode = stayWithinNode;
94 if (node.nodeType === Node.TEXT_NODE) {
95 var start = (node === this ? offset : 0);
96 for (var i = start; i < node.nodeValue.length; ++i) {
97 if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
108 node = node.traverseNextNode(stayWithinNode);
112 endNode = stayWithinNode;
113 endOffset = stayWithinNode.nodeType === Node.TEXT_NODE ? stayWithinNode.nodeValue.length : stayWithinNode.childNodes.length;
120 var result = this.ownerDocument.createRange();
121 result.setStart(startNode, startOffset);
122 result.setEnd(endNode, endOffset);
128 * @param {!Node=} stayWithin
131 Node.prototype.traverseNextTextNode = function(stayWithin)
133 var node = this.traverseNextNode(stayWithin);
136 var nonTextTags = { "STYLE": 1, "SCRIPT": 1 };
137 while (node && (node.nodeType !== Node.TEXT_NODE || nonTextTags[node.parentElement.nodeName]))
138 node = node.traverseNextNode(stayWithin);
144 * @param {number|undefined} x
145 * @param {number|undefined} y
146 * @param {!Element=} relativeTo
148 Element.prototype.positionAt = function(x, y, relativeTo)
150 var shift = {x: 0, y: 0};
152 shift = relativeTo.boxInWindow(this.ownerDocument.defaultView);
154 if (typeof x === "number")
155 this.style.setProperty("left", (shift.x + x) + "px");
157 this.style.removeProperty("left");
159 if (typeof y === "number")
160 this.style.setProperty("top", (shift.y + y) + "px");
162 this.style.removeProperty("top");
164 if (typeof x === "number" || typeof y === "number")
165 this.style.setProperty("position", "absolute");
167 this.style.removeProperty("position");
173 Element.prototype.isScrolledToBottom = function()
175 // This code works only for 0-width border.
176 // The scrollTop, clientHeight and scrollHeight are computed in double values internally.
177 // However, they are exposed to javascript differently, each being either rounded (via
178 // round, ceil or floor functions) or left intouch.
179 // This adds up a total error up to 2.
180 return Math.abs(this.scrollTop + this.clientHeight - this.scrollHeight) <= 2;
184 * @param {!Node} fromNode
185 * @param {!Node} toNode
187 function removeSubsequentNodes(fromNode, toNode)
189 for (var node = fromNode; node && node !== toNode; ) {
190 var nodeToRemove = node;
191 node = node.nextSibling;
192 nodeToRemove.remove();
197 * @param {!Event} event
200 Element.prototype.containsEventPoint = function(event)
202 var box = this.getBoundingClientRect();
203 return box.left < event.x && event.x < box.right &&
204 box.top < event.y && event.y < box.bottom;
208 * @param {!Array.<string>} nameArray
211 Node.prototype.enclosingNodeOrSelfWithNodeNameInArray = function(nameArray)
213 for (var node = this; node && node !== this.ownerDocument; node = node.parentNodeOrShadowHost()) {
214 for (var i = 0; i < nameArray.length; ++i) {
215 if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase())
223 * @param {string} nodeName
226 Node.prototype.enclosingNodeOrSelfWithNodeName = function(nodeName)
228 return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);
232 * @param {string} className
233 * @param {!Element=} stayWithin
236 Node.prototype.enclosingNodeOrSelfWithClass = function(className, stayWithin)
238 return this.enclosingNodeOrSelfWithClassList([className], stayWithin);
242 * @param {!Array.<string>} classNames
243 * @param {!Element=} stayWithin
246 Node.prototype.enclosingNodeOrSelfWithClassList = function(classNames, stayWithin)
248 for (var node = this; node && node !== stayWithin && node !== this.ownerDocument; node = node.parentNodeOrShadowHost()) {
249 if (node.nodeType === Node.ELEMENT_NODE) {
250 var containsAll = true;
251 for (var i = 0; i < classNames.length && containsAll; ++i) {
252 if (!node.classList.contains(classNames[i]))
256 return /** @type {!Element} */ (node);
265 Node.prototype.parentElementOrShadowHost = function()
267 var node = this.parentNode;
270 if (node.nodeType === Node.ELEMENT_NODE)
271 return /** @type {!Element} */ (node);
272 if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE)
273 return /** @type {!Element} */ (node.host);
280 Node.prototype.parentNodeOrShadowHost = function()
282 return this.parentNode || this.host || null;
286 * @return {?Selection}
288 Node.prototype.getComponentSelection = function()
290 var parent = this.parentNode;
291 while (parent && parent.nodeType !== Node.DOCUMENT_FRAGMENT_NODE)
292 parent = parent.parentNode;
293 return parent instanceof ShadowRoot ? parent.getSelection() : this.window().getSelection();
300 Node.prototype.isComponentSelectionCollapsed = function()
302 // FIXME: crbug.com/447523, use selection.isCollapsed when it is fixed for shadow dom.
303 var selection = this.getComponentSelection();
304 return selection && selection.rangeCount ? selection.getRangeAt(0).collapsed : true;
308 * @return {!Selection}
310 Node.prototype.getDeepSelection = function()
312 var activeElement = this.ownerDocument.activeElement;
313 var shadowRoot = null;
314 while (activeElement && activeElement.shadowRoot) {
315 shadowRoot = activeElement.shadowRoot;
316 activeElement = shadowRoot.activeElement;
319 return shadowRoot ? shadowRoot.getSelection() : this.window().getSelection();
325 Node.prototype.window = function()
327 return this.ownerDocument.defaultView;
331 * @param {string} query
334 Element.prototype.query = function(query)
336 return this.ownerDocument.evaluate(query, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
339 Element.prototype.removeChildren = function()
342 this.textContent = "";
348 Element.prototype.isInsertionCaretInside = function()
350 var selection = this.getComponentSelection();
351 if (!selection.rangeCount || !selection.isCollapsed)
353 var selectionRange = selection.getRangeAt(0);
354 return selectionRange.startContainer.isSelfOrDescendant(this);
358 * @param {string} tagName
359 * @param {string=} customElementType
361 * @suppressGlobalPropertiesCheck
363 function createElement(tagName, customElementType)
365 return document.createElement(tagName, customElementType || "");
369 * @param {string} type
370 * @param {boolean} bubbles
371 * @param {boolean} cancelable
373 * @suppressGlobalPropertiesCheck
375 function createEvent(type, bubbles, cancelable)
377 var event = document.createEvent("Event");
378 event.initEvent(type, bubbles, cancelable);
383 * @param {number|string} data
385 * @suppressGlobalPropertiesCheck
387 function createTextNode(data)
389 return document.createTextNode(data);
393 * @param {string} elementName
394 * @param {string=} className
395 * @param {string=} customElementType
398 Document.prototype.createElementWithClass = function(elementName, className, customElementType)
400 var element = this.createElement(elementName, customElementType || "");
402 element.className = className;
407 * @param {string} elementName
408 * @param {string=} className
409 * @param {string=} customElementType
411 * @suppressGlobalPropertiesCheck
413 function createElementWithClass(elementName, className, customElementType)
415 return document.createElementWithClass(elementName, className, customElementType);
419 * @param {string} childType
420 * @param {string=} className
423 Document.prototype.createSVGElement = function(childType, className)
425 var element = this.createElementNS("http://www.w3.org/2000/svg", childType);
427 element.setAttribute("class", className);
432 * @param {string} childType
433 * @param {string=} className
435 * @suppressGlobalPropertiesCheck
437 function createSVGElement(childType, className)
439 return document.createSVGElement(childType, className);
443 * @return {!DocumentFragment}
444 * @suppressGlobalPropertiesCheck
446 function createDocumentFragment()
448 return document.createDocumentFragment();
452 * @param {string} elementName
453 * @param {string=} className
454 * @param {string=} customElementType
457 Element.prototype.createChild = function(elementName, className, customElementType)
459 var element = this.ownerDocument.createElementWithClass(elementName, className, customElementType);
460 this.appendChild(element);
464 DocumentFragment.prototype.createChild = Element.prototype.createChild;
467 * @param {string} text
470 Element.prototype.createTextChild = function(text)
472 var element = this.ownerDocument.createTextNode(text);
473 this.appendChild(element);
477 DocumentFragment.prototype.createTextChild = Element.prototype.createTextChild;
480 * @param {...string} var_args
482 Element.prototype.createTextChildren = function(var_args)
484 for (var i = 0, n = arguments.length; i < n; ++i)
485 this.createTextChild(arguments[i]);
488 DocumentFragment.prototype.createTextChildren = Element.prototype.createTextChildren;
493 Element.prototype.totalOffsetLeft = function()
495 return this.totalOffset().left;
501 Element.prototype.totalOffsetTop = function()
503 return this.totalOffset().top;
507 * @return {!{left: number, top: number}}
509 Element.prototype.totalOffset = function()
511 var rect = this.getBoundingClientRect();
512 return { left: rect.left, top: rect.top };
516 * @return {!{left: number, top: number}}
518 Element.prototype.scrollOffset = function()
522 for (var element = this; element; element = element.scrollParent) {
523 curLeft += element.scrollLeft;
524 curTop += element.scrollTop;
526 return { left: curLeft, top: curTop };
530 * @param {string} childType
531 * @param {string=} className
534 Element.prototype.createSVGChild = function(childType, className)
536 var child = this.ownerDocument.createSVGElement(childType, className);
537 this.appendChild(child);
545 * @param {number=} width
546 * @param {number=} height
548 function AnchorBox(x, y, width, height)
552 this.width = width || 0;
553 this.height = height || 0;
557 * @param {!AnchorBox} box
558 * @return {!AnchorBox}
560 AnchorBox.prototype.relativeTo = function(box)
562 return new AnchorBox(
563 this.x - box.x, this.y - box.y, this.width, this.height);
567 * @param {!Element} element
568 * @return {!AnchorBox}
570 AnchorBox.prototype.relativeToElement = function(element)
572 return this.relativeTo(element.boxInWindow(element.ownerDocument.defaultView));
576 * @param {?AnchorBox} anchorBox
579 AnchorBox.prototype.equals = function(anchorBox)
581 return !!anchorBox && this.x === anchorBox.x && this.y === anchorBox.y && this.width === anchorBox.width && this.height === anchorBox.height;
585 * @param {!Window} targetWindow
586 * @return {!AnchorBox}
588 Element.prototype.offsetRelativeToWindow = function(targetWindow)
590 var elementOffset = new AnchorBox();
591 var curElement = this;
592 var curWindow = this.ownerDocument.defaultView;
593 while (curWindow && curElement) {
594 elementOffset.x += curElement.totalOffsetLeft();
595 elementOffset.y += curElement.totalOffsetTop();
596 if (curWindow === targetWindow)
599 curElement = curWindow.frameElement;
600 curWindow = curWindow.parent;
603 return elementOffset;
607 * @param {!Window=} targetWindow
608 * @return {!AnchorBox}
610 Element.prototype.boxInWindow = function(targetWindow)
612 targetWindow = targetWindow || this.ownerDocument.defaultView;
614 var anchorBox = this.offsetRelativeToWindow(window);
615 anchorBox.width = Math.min(this.offsetWidth, window.innerWidth - anchorBox.x);
616 anchorBox.height = Math.min(this.offsetHeight, window.innerHeight - anchorBox.y);
622 * @param {string} text
624 Element.prototype.setTextAndTitle = function(text)
626 this.textContent = text;
630 KeyboardEvent.prototype.__defineGetter__("data", function()
632 // Emulate "data" attribute from DOM 3 TextInput event.
633 // See http://www.w3.org/TR/DOM-Level-3-Events/#events-Events-TextEvent-data
636 if (!this.ctrlKey && !this.metaKey)
637 return String.fromCharCode(this.charCode);
642 if (!this.ctrlKey && !this.metaKey && !this.altKey)
643 return String.fromCharCode(this.which);
650 * @param {boolean=} preventDefault
652 Event.prototype.consume = function(preventDefault)
654 this.stopImmediatePropagation();
656 this.preventDefault();
661 * @param {number=} start
662 * @param {number=} end
665 Text.prototype.select = function(start, end)
668 end = end || this.textContent.length;
673 var selection = this.getComponentSelection();
674 selection.removeAllRanges();
675 var range = this.ownerDocument.createRange();
676 range.setStart(this, start);
677 range.setEnd(this, end);
678 selection.addRange(range);
685 Element.prototype.selectionLeftOffset = function()
687 // Calculate selection offset relative to the current element.
689 var selection = this.getComponentSelection();
690 if (!selection.containsNode(this, true))
693 var leftOffset = selection.anchorOffset;
694 var node = selection.anchorNode;
696 while (node !== this) {
697 while (node.previousSibling) {
698 node = node.previousSibling;
699 leftOffset += node.textContent.length;
701 node = node.parentNodeOrShadowHost();
708 * @param {...!Node} var_args
710 Node.prototype.appendChildren = function(var_args)
712 for (var i = 0, n = arguments.length; i < n; ++i)
713 this.appendChild(arguments[i]);
719 Node.prototype.deepTextContent = function()
721 return this.childTextNodes().map(function (node) { return node.textContent; }).join("");
725 * @return {!Array.<!Node>}
727 Node.prototype.childTextNodes = function()
729 var node = this.traverseNextTextNode(this);
731 var nonTextTags = { "STYLE": 1, "SCRIPT": 1 };
733 if (!nonTextTags[node.parentElement.nodeName])
735 node = node.traverseNextTextNode(this);
741 * @param {?Node} node
744 Node.prototype.isAncestor = function(node)
749 var currentNode = node.parentNodeOrShadowHost();
750 while (currentNode) {
751 if (this === currentNode)
753 currentNode = currentNode.parentNodeOrShadowHost();
759 * @param {?Node} descendant
762 Node.prototype.isDescendant = function(descendant)
764 return !!descendant && descendant.isAncestor(this);
768 * @param {?Node} node
771 Node.prototype.isSelfOrAncestor = function(node)
773 return !!node && (node === this || this.isAncestor(node));
777 * @param {?Node} node
780 Node.prototype.isSelfOrDescendant = function(node)
782 return !!node && (node === this || this.isDescendant(node));
786 * @param {!Node=} stayWithin
789 Node.prototype.traverseNextNode = function(stayWithin)
792 return this.shadowRoot;
794 var distributedNodes = this.getDistributedNodes ? this.getDistributedNodes() : [];
796 if (distributedNodes.length)
797 return distributedNodes[0];
800 return this.firstChild;
804 if (stayWithin && node === stayWithin)
807 var sibling = nextSibling(node);
811 node = insertionPoint(node) || node.parentNodeOrShadowHost();
815 * @param {!Node} node
818 function nextSibling(node)
820 var parent = insertionPoint(node);
822 return node.nextSibling;
823 var distributedNodes = parent.getDistributedNodes ? parent.getDistributedNodes() : [];
825 var position = Array.prototype.indexOf.call(distributedNodes, node);
826 if (position + 1 < distributedNodes.length)
827 return distributedNodes[position + 1];
832 * @param {!Node} node
835 function insertionPoint(node)
837 var insertionPoints = node.getDestinationInsertionPoints ? node.getDestinationInsertionPoints() : [];
838 return insertionPoints.length > 0 ? insertionPoints[insertionPoints.length - 1] : null;
845 * @param {!Node=} stayWithin
848 Node.prototype.traversePreviousNode = function(stayWithin)
850 if (stayWithin && this === stayWithin)
852 var node = this.previousSibling;
853 while (node && node.lastChild)
854 node = node.lastChild;
857 return this.parentNodeOrShadowHost();
862 * @param {string=} placeholder
863 * @return {boolean} true if was truncated
865 Node.prototype.setTextContentTruncatedIfNeeded = function(text, placeholder)
867 // Huge texts in the UI reduce rendering performance drastically.
868 // Moreover, Blink/WebKit uses <unsigned short> internally for storing text content
869 // length, so texts longer than 65535 are inherently displayed incorrectly.
870 const maxTextContentLength = 10000;
872 if (typeof text === "string" && text.length > maxTextContentLength) {
873 this.textContent = typeof placeholder === "string" ? placeholder : text.trimMiddle(maxTextContentLength);
877 this.textContent = text;
884 Event.prototype.deepElementFromPoint = function()
886 // 1. climb to the component root.
887 var node = this.target;
888 while (node && node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE && node.nodeType !== Node.DOCUMENT_NODE)
889 node = node.parentNode;
894 // 2. Find deepest node by coordinates.
895 node = node.elementFromPoint(this.pageX, this.pageY);
896 while (node && node.shadowRoot)
897 node = node.shadowRoot.elementFromPoint(this.pageX, this.pageY);
904 Event.prototype.deepActiveElement = function()
906 var activeElement = this.target && this.target.ownerDocument ? this.target.ownerDocument.activeElement : null;
907 while (activeElement && activeElement.shadowRoot)
908 activeElement = activeElement.shadowRoot.activeElement;
909 return activeElement;
917 Document.prototype.deepElementFromPoint = function(x, y)
919 var node = this.elementFromPoint(x, y);
920 while (node && node.shadowRoot)
921 node = node.shadowRoot.elementFromPoint(x, y);
926 * @param {!Event} event
929 function isEnterKey(event)
932 return event.keyCode !== 229 && event.keyIdentifier === "Enter";
936 * @param {!Event} event
939 function isEscKey(event)
941 return event.keyCode === 27;
944 function consumeEvent(e)
950 * @param {function()} callback
951 * @suppressGlobalPropertiesCheck
953 function runOnWindowLoad(callback)
956 * @suppressGlobalPropertiesCheck
958 function windowLoaded()
960 window.removeEventListener("DOMContentLoaded", windowLoaded, false);
964 if (document.readyState === "complete" || document.readyState === "interactive")
967 window.addEventListener("DOMContentLoaded", windowLoaded, false);