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 {string=} direction
36 Node.prototype.rangeOfWord = function(offset, stopCharacters, stayWithinNode, direction)
44 stayWithinNode = this;
46 if (!direction || direction === "backward" || direction === "both") {
49 if (node === stayWithinNode) {
51 startNode = stayWithinNode;
55 if (node.nodeType === Node.TEXT_NODE) {
56 var start = (node === this ? (offset - 1) : (node.nodeValue.length - 1));
57 for (var i = start; i >= 0; --i) {
58 if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
69 node = node.traversePreviousNode(stayWithinNode);
73 startNode = stayWithinNode;
81 if (!direction || direction === "forward" || direction === "both") {
84 if (node === stayWithinNode) {
86 endNode = stayWithinNode;
90 if (node.nodeType === Node.TEXT_NODE) {
91 var start = (node === this ? offset : 0);
92 for (var i = start; i < node.nodeValue.length; ++i) {
93 if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
104 node = node.traverseNextNode(stayWithinNode);
108 endNode = stayWithinNode;
109 endOffset = stayWithinNode.nodeType === Node.TEXT_NODE ? stayWithinNode.nodeValue.length : stayWithinNode.childNodes.length;
116 var result = this.ownerDocument.createRange();
117 result.setStart(startNode, startOffset);
118 result.setEnd(endNode, endOffset);
123 Node.prototype.traverseNextTextNode = function(stayWithin)
125 var node = this.traverseNextNode(stayWithin);
129 while (node && node.nodeType !== Node.TEXT_NODE)
130 node = node.traverseNextNode(stayWithin);
135 Node.prototype.rangeBoundaryForOffset = function(offset)
137 var node = this.traverseNextTextNode(this);
138 while (node && offset > node.nodeValue.length) {
139 offset -= node.nodeValue.length;
140 node = node.traverseNextTextNode(this);
143 return { container: this, offset: 0 };
144 return { container: node, offset: offset };
147 Element.prototype.removeMatchingStyleClasses = function(classNameRegex)
149 var regex = new RegExp("(^|\\s+)" + classNameRegex + "($|\\s+)");
150 if (regex.test(this.className))
151 this.className = this.className.replace(regex, " ");
155 * @param {number|undefined} x
156 * @param {number|undefined} y
157 * @param {!Element=} relativeTo
159 Element.prototype.positionAt = function(x, y, relativeTo)
161 var shift = {x: 0, y: 0};
163 shift = relativeTo.boxInWindow(this.ownerDocument.defaultView);
165 if (typeof x === "number")
166 this.style.setProperty("left", (shift.x + x) + "px");
168 this.style.removeProperty("left");
170 if (typeof y === "number")
171 this.style.setProperty("top", (shift.y + y) + "px");
173 this.style.removeProperty("top");
176 Element.prototype.isScrolledToBottom = function()
178 // This code works only for 0-width border.
179 // Both clientHeight and scrollHeight are rounded to integer values, so we tolerate
181 return Math.abs(this.scrollTop + this.clientHeight - this.scrollHeight) <= 1;
185 * @param {!Node} fromNode
186 * @param {!Node} toNode
188 function removeSubsequentNodes(fromNode, toNode)
190 for (var node = fromNode; node && node !== toNode; ) {
191 var nodeToRemove = node;
192 node = node.nextSibling;
193 nodeToRemove.remove();
199 * @param {number} width
200 * @param {number} height
202 function Size(width, height)
205 this.height = height;
209 * @param {?Size} size
212 Size.prototype.isEqual = function(size)
214 return !!size && this.width === size.width && this.height === size.height;
218 * @param {!Size|number} size
221 Size.prototype.widthToMax = function(size)
223 return new Size(Math.max(this.width, (typeof size === "number" ? size : size.width)), this.height);
227 * @param {!Size|number} size
230 Size.prototype.addWidth = function(size)
232 return new Size(this.width + (typeof size === "number" ? size : size.width), this.height);
236 * @param {!Size|number} size
239 Size.prototype.heightToMax = function(size)
241 return new Size(this.width, Math.max(this.height, (typeof size === "number" ? size : size.height)));
245 * @param {!Size|number} size
248 Size.prototype.addHeight = function(size)
250 return new Size(this.width, this.height + (typeof size === "number" ? size : size.height));
255 * @param {!Size} minimum
256 * @param {?Size=} preferred
258 function Constraints(minimum, preferred)
263 this.minimum = minimum;
268 this.preferred = preferred || minimum;
270 if (this.minimum.width > this.preferred.width || this.minimum.height > this.preferred.height)
271 throw new Error("Minimum size is greater than preferred.");
275 * @param {?Constraints} constraints
278 Constraints.prototype.isEqual = function(constraints)
280 return !!constraints && this.minimum.isEqual(constraints.minimum) && this.preferred.isEqual(constraints.preferred);
284 * @param {!Constraints|number} value
285 * @return {!Constraints}
287 Constraints.prototype.widthToMax = function(value)
289 if (typeof value === "number")
290 return new Constraints(this.minimum.widthToMax(value), this.preferred.widthToMax(value));
291 return new Constraints(this.minimum.widthToMax(value.minimum), this.preferred.widthToMax(value.preferred));
295 * @param {!Constraints|number} value
296 * @return {!Constraints}
298 Constraints.prototype.addWidth = function(value)
300 if (typeof value === "number")
301 return new Constraints(this.minimum.addWidth(value), this.preferred.addWidth(value));
302 return new Constraints(this.minimum.addWidth(value.minimum), this.preferred.addWidth(value.preferred));
306 * @param {!Constraints|number} value
307 * @return {!Constraints}
309 Constraints.prototype.heightToMax = function(value)
311 if (typeof value === "number")
312 return new Constraints(this.minimum.heightToMax(value), this.preferred.heightToMax(value));
313 return new Constraints(this.minimum.heightToMax(value.minimum), this.preferred.heightToMax(value.preferred));
317 * @param {!Constraints|number} value
318 * @return {!Constraints}
320 Constraints.prototype.addHeight = function(value)
322 if (typeof value === "number")
323 return new Constraints(this.minimum.addHeight(value), this.preferred.addHeight(value));
324 return new Constraints(this.minimum.addHeight(value.minimum), this.preferred.addHeight(value.preferred));
328 * @param {?Element=} containerElement
331 Element.prototype.measurePreferredSize = function(containerElement)
333 containerElement = containerElement || document.body;
334 containerElement.appendChild(this);
335 this.positionAt(0, 0);
336 var result = new Size(this.offsetWidth, this.offsetHeight);
337 this.positionAt(undefined, undefined);
343 * @param {!Event} event
346 Element.prototype.containsEventPoint = function(event)
348 var box = this.getBoundingClientRect();
349 return box.left < event.x && event.x < box.right &&
350 box.top < event.y && event.y < box.bottom;
353 Node.prototype.enclosingNodeOrSelfWithNodeNameInArray = function(nameArray)
355 for (var node = this; node && node !== this.ownerDocument; node = node.parentNode)
356 for (var i = 0; i < nameArray.length; ++i)
357 if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase())
362 Node.prototype.enclosingNodeOrSelfWithNodeName = function(nodeName)
364 return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);
368 * @param {string} className
369 * @param {!Element=} stayWithin
371 Node.prototype.enclosingNodeOrSelfWithClass = function(className, stayWithin)
373 for (var node = this; node && node !== stayWithin && node !== this.ownerDocument; node = node.parentNode)
374 if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains(className))
379 Element.prototype.query = function(query)
381 return this.ownerDocument.evaluate(query, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
384 Element.prototype.removeChildren = function()
387 this.textContent = "";
390 Element.prototype.isInsertionCaretInside = function()
392 var selection = window.getSelection();
393 if (!selection.rangeCount || !selection.isCollapsed)
395 var selectionRange = selection.getRangeAt(0);
396 return selectionRange.startContainer.isSelfOrDescendant(this);
400 * @param {string} elementName
401 * @param {string=} className
403 Document.prototype.createElementWithClass = function(elementName, className)
405 var element = this.createElement(elementName);
407 element.className = className;
412 * @param {string=} className
414 Element.prototype.createChild = function(elementName, className)
416 var element = this.ownerDocument.createElementWithClass(elementName, className);
417 this.appendChild(element);
421 DocumentFragment.prototype.createChild = Element.prototype.createChild;
424 * @param {string} text
426 Element.prototype.createTextChild = function(text)
428 var element = this.ownerDocument.createTextNode(text);
429 this.appendChild(element);
433 DocumentFragment.prototype.createTextChild = Element.prototype.createTextChild;
438 Element.prototype.totalOffsetLeft = function()
440 return this.totalOffset().left;
446 Element.prototype.totalOffsetTop = function()
448 return this.totalOffset().top;
452 Element.prototype.totalOffset = function()
454 var rect = this.getBoundingClientRect();
455 return { left: rect.left, top: rect.top };
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();
588 Text.prototype.select = function(start, end)
591 end = end || this.textContent.length;
596 var selection = this.ownerDocument.defaultView.getSelection();
597 selection.removeAllRanges();
598 var range = this.ownerDocument.createRange();
599 range.setStart(this, start);
600 range.setEnd(this, end);
601 selection.addRange(range);
605 Element.prototype.selectionLeftOffset = function()
607 // Calculate selection offset relative to the current element.
609 var selection = window.getSelection();
610 if (!selection.containsNode(this, true))
613 var leftOffset = selection.anchorOffset;
614 var node = selection.anchorNode;
616 while (node !== this) {
617 while (node.previousSibling) {
618 node = node.previousSibling;
619 leftOffset += node.textContent.length;
621 node = node.parentNode;
627 Node.prototype.isAncestor = function(node)
632 var currentNode = node.parentNode;
633 while (currentNode) {
634 if (this === currentNode)
636 currentNode = currentNode.parentNode;
641 Node.prototype.isDescendant = function(descendant)
643 return !!descendant && descendant.isAncestor(this);
646 Node.prototype.isSelfOrAncestor = function(node)
648 return !!node && (node === this || this.isAncestor(node));
651 Node.prototype.isSelfOrDescendant = function(node)
653 return !!node && (node === this || this.isDescendant(node));
656 Node.prototype.traverseNextNode = function(stayWithin)
658 var node = this.firstChild;
662 if (stayWithin && this === stayWithin)
665 node = this.nextSibling;
670 while (node && !node.nextSibling && (!stayWithin || !node.parentNode || node.parentNode !== stayWithin))
671 node = node.parentNode;
675 return node.nextSibling;
678 Node.prototype.traversePreviousNode = function(stayWithin)
680 if (stayWithin && this === stayWithin)
682 var node = this.previousSibling;
683 while (node && node.lastChild)
684 node = node.lastChild;
687 return this.parentNode;
692 * @param {string=} placeholder
693 * @return {boolean} true if was truncated
695 Node.prototype.setTextContentTruncatedIfNeeded = function(text, placeholder)
697 // Huge texts in the UI reduce rendering performance drastically.
698 // Moreover, Blink/WebKit uses <unsigned short> internally for storing text content
699 // length, so texts longer than 65535 are inherently displayed incorrectly.
700 const maxTextContentLength = 65535;
702 if (typeof text === "string" && text.length > maxTextContentLength) {
703 this.textContent = typeof placeholder === "string" ? placeholder : text.trimEnd(maxTextContentLength);
707 this.textContent = text;
714 function isEnterKey(event) {
716 return event.keyCode !== 229 && event.keyIdentifier === "Enter";
719 function consumeEvent(e)