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);
137 while (node && node.nodeType !== Node.TEXT_NODE)
138 node = node.traverseNextNode(stayWithin);
144 * @param {number} offset
145 * @return {!{container: !Node, offset: number}}
147 Node.prototype.rangeBoundaryForOffset = function(offset)
149 var node = this.traverseNextTextNode(this);
150 while (node && offset > node.nodeValue.length) {
151 offset -= node.nodeValue.length;
152 node = node.traverseNextTextNode(this);
155 return { container: this, offset: 0 };
156 return { container: node, offset: offset };
159 Element.prototype.removeMatchingStyleClasses = function(classNameRegex)
161 var regex = new RegExp("(^|\\s+)" + classNameRegex + "($|\\s+)");
162 if (regex.test(this.className))
163 this.className = this.className.replace(regex, " ");
167 * @param {number|undefined} x
168 * @param {number|undefined} y
169 * @param {!Element=} relativeTo
171 Element.prototype.positionAt = function(x, y, relativeTo)
173 var shift = {x: 0, y: 0};
175 shift = relativeTo.boxInWindow(this.ownerDocument.defaultView);
177 if (typeof x === "number")
178 this.style.setProperty("left", (shift.x + x) + "px");
180 this.style.removeProperty("left");
182 if (typeof y === "number")
183 this.style.setProperty("top", (shift.y + y) + "px");
185 this.style.removeProperty("top");
191 Element.prototype.isScrolledToBottom = function()
193 // This code works only for 0-width border.
194 // Both clientHeight and scrollHeight are rounded to integer values, so we tolerate
196 return Math.abs(this.scrollTop + this.clientHeight - this.scrollHeight) <= 1;
200 * @param {!Node} fromNode
201 * @param {!Node} toNode
203 function removeSubsequentNodes(fromNode, toNode)
205 for (var node = fromNode; node && node !== toNode; ) {
206 var nodeToRemove = node;
207 node = node.nextSibling;
208 nodeToRemove.remove();
214 * @param {!Size} minimum
215 * @param {?Size=} preferred
217 function Constraints(minimum, preferred)
222 this.minimum = minimum;
227 this.preferred = preferred || minimum;
229 if (this.minimum.width > this.preferred.width || this.minimum.height > this.preferred.height)
230 throw new Error("Minimum size is greater than preferred.");
234 * @param {?Constraints} constraints
237 Constraints.prototype.isEqual = function(constraints)
239 return !!constraints && this.minimum.isEqual(constraints.minimum) && this.preferred.isEqual(constraints.preferred);
243 * @param {!Constraints|number} value
244 * @return {!Constraints}
246 Constraints.prototype.widthToMax = function(value)
248 if (typeof value === "number")
249 return new Constraints(this.minimum.widthToMax(value), this.preferred.widthToMax(value));
250 return new Constraints(this.minimum.widthToMax(value.minimum), this.preferred.widthToMax(value.preferred));
254 * @param {!Constraints|number} value
255 * @return {!Constraints}
257 Constraints.prototype.addWidth = function(value)
259 if (typeof value === "number")
260 return new Constraints(this.minimum.addWidth(value), this.preferred.addWidth(value));
261 return new Constraints(this.minimum.addWidth(value.minimum), this.preferred.addWidth(value.preferred));
265 * @param {!Constraints|number} value
266 * @return {!Constraints}
268 Constraints.prototype.heightToMax = function(value)
270 if (typeof value === "number")
271 return new Constraints(this.minimum.heightToMax(value), this.preferred.heightToMax(value));
272 return new Constraints(this.minimum.heightToMax(value.minimum), this.preferred.heightToMax(value.preferred));
276 * @param {!Constraints|number} value
277 * @return {!Constraints}
279 Constraints.prototype.addHeight = function(value)
281 if (typeof value === "number")
282 return new Constraints(this.minimum.addHeight(value), this.preferred.addHeight(value));
283 return new Constraints(this.minimum.addHeight(value.minimum), this.preferred.addHeight(value.preferred));
287 * @param {?Element=} containerElement
290 Element.prototype.measurePreferredSize = function(containerElement)
292 containerElement = containerElement || document.body;
293 containerElement.appendChild(this);
294 this.positionAt(0, 0);
295 var result = new Size(this.offsetWidth, this.offsetHeight);
296 this.positionAt(undefined, undefined);
302 * @param {!Event} event
305 Element.prototype.containsEventPoint = function(event)
307 var box = this.getBoundingClientRect();
308 return box.left < event.x && event.x < box.right &&
309 box.top < event.y && event.y < box.bottom;
313 * @param {!Array.<string>} nameArray
316 Node.prototype.enclosingNodeOrSelfWithNodeNameInArray = function(nameArray)
318 for (var node = this; node && node !== this.ownerDocument; node = node.parentNode) {
319 for (var i = 0; i < nameArray.length; ++i) {
320 if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase())
328 * @param {string} nodeName
331 Node.prototype.enclosingNodeOrSelfWithNodeName = function(nodeName)
333 return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);
337 * @param {string} className
338 * @param {!Element=} stayWithin
341 Node.prototype.enclosingNodeOrSelfWithClass = function(className, stayWithin)
343 for (var node = this; node && node !== stayWithin && node !== this.ownerDocument; node = node.parentNode) {
344 if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains(className))
345 return /** @type {!Element} */ (node);
351 * @param {string} query
354 Element.prototype.query = function(query)
356 return this.ownerDocument.evaluate(query, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
359 Element.prototype.removeChildren = function()
362 this.textContent = "";
365 Element.prototype.appendChildren = function(children)
367 for (var i = 0; i < children.length; ++i)
368 this.appendChild(children[i]);
371 Element.prototype.setChildren = function(children)
373 this.removeChildren();
374 this.appendChildren(children);
380 Element.prototype.isInsertionCaretInside = function()
382 var selection = window.getSelection();
383 if (!selection.rangeCount || !selection.isCollapsed)
385 var selectionRange = selection.getRangeAt(0);
386 return selectionRange.startContainer.isSelfOrDescendant(this);
390 * @param {string} elementName
391 * @param {string=} className
394 Document.prototype.createElementWithClass = function(elementName, className)
396 var element = this.createElement(elementName);
398 element.className = className;
403 * @param {string} elementName
404 * @param {string=} className
407 Element.prototype.createChild = function(elementName, className)
409 var element = this.ownerDocument.createElementWithClass(elementName, className);
410 this.appendChild(element);
414 DocumentFragment.prototype.createChild = Element.prototype.createChild;
417 * @param {string} text
420 Element.prototype.createTextChild = function(text)
422 var element = this.ownerDocument.createTextNode(text);
423 this.appendChild(element);
427 DocumentFragment.prototype.createTextChild = Element.prototype.createTextChild;
432 Element.prototype.totalOffsetLeft = function()
434 return this.totalOffset().left;
440 Element.prototype.totalOffsetTop = function()
442 return this.totalOffset().top;
447 * @return {!{left: number, top: number}}
449 Element.prototype.totalOffset = function()
451 var rect = this.getBoundingClientRect();
452 return { left: rect.left, top: rect.top };
456 * @return {!{left: number, top: number}}
458 Element.prototype.scrollOffset = function()
462 for (var element = this; element; element = element.scrollParent) {
463 curLeft += element.scrollLeft;
464 curTop += element.scrollTop;
466 return { left: curLeft, top: curTop };
473 * @param {number=} width
474 * @param {number=} height
476 function AnchorBox(x, y, width, height)
480 this.width = width || 0;
481 this.height = height || 0;
485 * @param {!AnchorBox} box
486 * @return {!AnchorBox}
488 AnchorBox.prototype.relativeTo = function(box)
490 return new AnchorBox(
491 this.x - box.x, this.y - box.y, this.width, this.height);
495 * @param {!Element} element
496 * @return {!AnchorBox}
498 AnchorBox.prototype.relativeToElement = function(element)
500 return this.relativeTo(element.boxInWindow(element.ownerDocument.defaultView));
504 * @param {?AnchorBox} anchorBox
507 AnchorBox.prototype.equals = function(anchorBox)
509 return !!anchorBox && this.x === anchorBox.x && this.y === anchorBox.y && this.width === anchorBox.width && this.height === anchorBox.height;
513 * @param {!Window} targetWindow
514 * @return {!AnchorBox}
516 Element.prototype.offsetRelativeToWindow = function(targetWindow)
518 var elementOffset = new AnchorBox();
519 var curElement = this;
520 var curWindow = this.ownerDocument.defaultView;
521 while (curWindow && curElement) {
522 elementOffset.x += curElement.totalOffsetLeft();
523 elementOffset.y += curElement.totalOffsetTop();
524 if (curWindow === targetWindow)
527 curElement = curWindow.frameElement;
528 curWindow = curWindow.parent;
531 return elementOffset;
535 * @param {!Window=} targetWindow
536 * @return {!AnchorBox}
538 Element.prototype.boxInWindow = function(targetWindow)
540 targetWindow = targetWindow || this.ownerDocument.defaultView;
542 var anchorBox = this.offsetRelativeToWindow(window);
543 anchorBox.width = Math.min(this.offsetWidth, window.innerWidth - anchorBox.x);
544 anchorBox.height = Math.min(this.offsetHeight, window.innerHeight - anchorBox.y);
550 * @param {string} text
552 Element.prototype.setTextAndTitle = function(text)
554 this.textContent = text;
558 KeyboardEvent.prototype.__defineGetter__("data", function()
560 // Emulate "data" attribute from DOM 3 TextInput event.
561 // See http://www.w3.org/TR/DOM-Level-3-Events/#events-Events-TextEvent-data
564 if (!this.ctrlKey && !this.metaKey)
565 return String.fromCharCode(this.charCode);
570 if (!this.ctrlKey && !this.metaKey && !this.altKey)
571 return String.fromCharCode(this.which);
578 * @param {boolean=} preventDefault
580 Event.prototype.consume = function(preventDefault)
582 this.stopImmediatePropagation();
584 this.preventDefault();
589 * @param {number=} start
590 * @param {number=} end
593 Text.prototype.select = function(start, end)
596 end = end || this.textContent.length;
601 var selection = this.ownerDocument.defaultView.getSelection();
602 selection.removeAllRanges();
603 var range = this.ownerDocument.createRange();
604 range.setStart(this, start);
605 range.setEnd(this, end);
606 selection.addRange(range);
613 Element.prototype.selectionLeftOffset = function()
615 // Calculate selection offset relative to the current element.
617 var selection = window.getSelection();
618 if (!selection.containsNode(this, true))
621 var leftOffset = selection.anchorOffset;
622 var node = selection.anchorNode;
624 while (node !== this) {
625 while (node.previousSibling) {
626 node = node.previousSibling;
627 leftOffset += node.textContent.length;
629 node = node.parentNode;
636 * @param {?Node} node
639 Node.prototype.isAncestor = function(node)
644 var currentNode = node.parentNode;
645 while (currentNode) {
646 if (this === currentNode)
648 currentNode = currentNode.parentNode;
654 * @param {?Node} descendant
657 Node.prototype.isDescendant = function(descendant)
659 return !!descendant && descendant.isAncestor(this);
663 * @param {?Node} node
666 Node.prototype.isSelfOrAncestor = function(node)
668 return !!node && (node === this || this.isAncestor(node));
672 * @param {?Node} node
675 Node.prototype.isSelfOrDescendant = function(node)
677 return !!node && (node === this || this.isDescendant(node));
681 * @param {!Node=} stayWithin
684 Node.prototype.traverseNextNode = function(stayWithin)
686 var node = this.firstChild;
690 if (stayWithin && this === stayWithin)
693 node = this.nextSibling;
698 while (node && !node.nextSibling && (!stayWithin || !node.parentNode || node.parentNode !== stayWithin))
699 node = node.parentNode;
703 return node.nextSibling;
707 * @param {!Node=} stayWithin
710 Node.prototype.traversePreviousNode = function(stayWithin)
712 if (stayWithin && this === stayWithin)
714 var node = this.previousSibling;
715 while (node && node.lastChild)
716 node = node.lastChild;
719 return this.parentNode;
724 * @param {string=} placeholder
725 * @return {boolean} true if was truncated
727 Node.prototype.setTextContentTruncatedIfNeeded = function(text, placeholder)
729 // Huge texts in the UI reduce rendering performance drastically.
730 // Moreover, Blink/WebKit uses <unsigned short> internally for storing text content
731 // length, so texts longer than 65535 are inherently displayed incorrectly.
732 const maxTextContentLength = 65535;
734 if (typeof text === "string" && text.length > maxTextContentLength) {
735 this.textContent = typeof placeholder === "string" ? placeholder : text.trimEnd(maxTextContentLength);
739 this.textContent = text;
746 function isEnterKey(event) {
748 return event.keyCode !== 229 && event.keyIdentifier === "Enter";
751 function consumeEvent(e)