2 * Copyright (C) 2007 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14 * its contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * Contains diff method based on Javascript Diff Algorithm By John Resig
29 * http://ejohn.org/files/jsdiff.js (released under the MIT license).
32 Function.prototype.bind = function(thisObject)
35 var args = Array.prototype.slice.call(arguments, 1);
38 return func.apply(thisObject, args.concat(Array.prototype.slice.call(arguments, 0)));
40 bound.toString = function() {
41 return "bound: " + func;
47 * @param {string=} direction
49 Node.prototype.rangeOfWord = function(offset, stopCharacters, stayWithinNode, direction)
57 stayWithinNode = this;
59 if (!direction || direction === "backward" || direction === "both") {
62 if (node === stayWithinNode) {
64 startNode = stayWithinNode;
68 if (node.nodeType === Node.TEXT_NODE) {
69 var start = (node === this ? (offset - 1) : (node.nodeValue.length - 1));
70 for (var i = start; i >= 0; --i) {
71 if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
82 node = node.traversePreviousNode(stayWithinNode);
86 startNode = stayWithinNode;
94 if (!direction || direction === "forward" || direction === "both") {
97 if (node === stayWithinNode) {
99 endNode = stayWithinNode;
103 if (node.nodeType === Node.TEXT_NODE) {
104 var start = (node === this ? offset : 0);
105 for (var i = start; i < node.nodeValue.length; ++i) {
106 if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
117 node = node.traverseNextNode(stayWithinNode);
121 endNode = stayWithinNode;
122 endOffset = stayWithinNode.nodeType === Node.TEXT_NODE ? stayWithinNode.nodeValue.length : stayWithinNode.childNodes.length;
129 var result = this.ownerDocument.createRange();
130 result.setStart(startNode, startOffset);
131 result.setEnd(endNode, endOffset);
136 Node.prototype.traverseNextTextNode = function(stayWithin)
138 var node = this.traverseNextNode(stayWithin);
142 while (node && node.nodeType !== Node.TEXT_NODE)
143 node = node.traverseNextNode(stayWithin);
148 Node.prototype.rangeBoundaryForOffset = function(offset)
150 var node = this.traverseNextTextNode(this);
151 while (node && offset > node.nodeValue.length) {
152 offset -= node.nodeValue.length;
153 node = node.traverseNextTextNode(this);
156 return { container: this, offset: 0 };
157 return { container: node, offset: offset };
160 Element.prototype.removeStyleClass = function(className)
162 this.classList.remove(className);
165 Element.prototype.removeMatchingStyleClasses = function(classNameRegex)
167 var regex = new RegExp("(^|\\s+)" + classNameRegex + "($|\\s+)");
168 if (regex.test(this.className))
169 this.className = this.className.replace(regex, " ");
172 Element.prototype.addStyleClass = function(className)
174 this.classList.add(className);
177 Element.prototype.hasStyleClass = function(className)
179 return this.classList.contains(className);
182 Element.prototype.positionAt = function(x, y)
184 this.style.left = x + "px";
185 this.style.top = y + "px";
188 Element.prototype.pruneEmptyTextNodes = function()
190 var sibling = this.firstChild;
192 var nextSibling = sibling.nextSibling;
193 if (sibling.nodeType === this.TEXT_NODE && sibling.nodeValue === "")
194 this.removeChild(sibling);
195 sibling = nextSibling;
199 Element.prototype.isScrolledToBottom = function()
201 // This code works only for 0-width border
202 return this.scrollTop + this.clientHeight === this.scrollHeight;
205 Node.prototype.enclosingNodeOrSelfWithNodeNameInArray = function(nameArray)
207 for (var node = this; node && node !== this.ownerDocument; node = node.parentNode)
208 for (var i = 0; i < nameArray.length; ++i)
209 if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase())
214 Node.prototype.enclosingNodeOrSelfWithNodeName = function(nodeName)
216 return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);
219 Node.prototype.enclosingNodeOrSelfWithClass = function(className)
221 for (var node = this; node && node !== this.ownerDocument; node = node.parentNode)
222 if (node.nodeType === Node.ELEMENT_NODE && node.hasStyleClass(className))
227 Node.prototype.enclosingNodeWithClass = function(className)
229 if (!this.parentNode)
231 return this.parentNode.enclosingNodeOrSelfWithClass(className);
234 Element.prototype.query = function(query)
236 return this.ownerDocument.evaluate(query, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
239 Element.prototype.removeChildren = function()
242 this.textContent = "";
245 Element.prototype.isInsertionCaretInside = function()
247 var selection = window.getSelection();
248 if (!selection.rangeCount || !selection.isCollapsed)
250 var selectionRange = selection.getRangeAt(0);
251 return selectionRange.startContainer === this || selectionRange.startContainer.isDescendant(this);
255 * @param {string=} className
257 Element.prototype.createChild = function(elementName, className)
259 var element = this.ownerDocument.createElement(elementName);
261 element.className = className;
262 this.appendChild(element);
266 DocumentFragment.prototype.createChild = Element.prototype.createChild;
268 Element.prototype.totalOffsetLeft = function()
271 for (var element = this; element; element = element.offsetParent)
272 total += element.offsetLeft + (this !== element ? element.clientLeft : 0);
276 Element.prototype.totalOffsetTop = function()
279 for (var element = this; element; element = element.offsetParent)
280 total += element.offsetTop + (this !== element ? element.clientTop : 0);
288 * @param {number=} width
289 * @param {number=} height
291 function AnchorBox(x, y, width, height)
295 this.width = width || 0;
296 this.height = height || 0;
300 * @return {AnchorBox}
302 Element.prototype.offsetRelativeToWindow = function(targetWindow)
304 var elementOffset = new AnchorBox();
305 var curElement = this;
306 var curWindow = this.ownerDocument.defaultView;
307 while (curWindow && curElement) {
308 elementOffset.x += curElement.totalOffsetLeft();
309 elementOffset.y += curElement.totalOffsetTop();
310 if (curWindow === targetWindow)
313 curElement = curWindow.frameElement;
314 curWindow = curWindow.parent;
317 return elementOffset;
321 * @return {AnchorBox}
323 Element.prototype.boxInWindow = function(targetWindow, relativeParent)
325 targetWindow = targetWindow || this.ownerDocument.defaultView;
326 var bodyElement = this.ownerDocument.body;
327 relativeParent = relativeParent || bodyElement;
329 var anchorBox = this.offsetRelativeToWindow(window);
330 anchorBox.width = this.offsetWidth;
331 anchorBox.height = this.offsetHeight;
333 var anchorElement = this;
334 while (anchorElement && anchorElement !== relativeParent && anchorElement !== bodyElement) {
335 if (anchorElement.scrollLeft)
336 anchorBox.x -= anchorElement.scrollLeft;
337 if (anchorElement.scrollTop)
338 anchorBox.y -= anchorElement.scrollTop;
339 anchorElement = anchorElement.parentElement;
342 var parentOffset = relativeParent.offsetRelativeToWindow(window);
343 anchorBox.x -= parentOffset.x;
344 anchorBox.y -= parentOffset.y;
348 Element.prototype.setTextAndTitle = function(text)
350 this.textContent = text;
354 KeyboardEvent.prototype.__defineGetter__("data", function()
356 // Emulate "data" attribute from DOM 3 TextInput event.
357 // See http://www.w3.org/TR/DOM-Level-3-Events/#events-Events-TextEvent-data
360 if (!this.ctrlKey && !this.metaKey)
361 return String.fromCharCode(this.charCode);
366 if (!this.ctrlKey && !this.metaKey && !this.altKey)
367 return String.fromCharCode(this.which);
373 Text.prototype.select = function(start, end)
376 end = end || this.textContent.length;
381 var selection = this.ownerDocument.defaultView.getSelection();
382 selection.removeAllRanges();
383 var range = this.ownerDocument.createRange();
384 range.setStart(this, start);
385 range.setEnd(this, end);
386 selection.addRange(range);
390 Element.prototype.selectionLeftOffset = function()
392 // Calculate selection offset relative to the current element.
394 var selection = window.getSelection();
395 if (!selection.containsNode(this, true))
398 var leftOffset = selection.anchorOffset;
399 var node = selection.anchorNode;
401 while (node !== this) {
402 while (node.previousSibling) {
403 node = node.previousSibling;
404 leftOffset += node.textContent.length;
406 node = node.parentNode;
412 String.prototype.hasSubstring = function(string, caseInsensitive)
414 if (!caseInsensitive)
415 return this.indexOf(string) !== -1;
416 return this.match(new RegExp(string.escapeForRegExp(), "i"));
419 String.prototype.findAll = function(string)
422 var i = this.indexOf(string);
425 i = this.indexOf(string, i + string.length);
430 String.prototype.lineEndings = function()
432 if (!this._lineEndings) {
433 this._lineEndings = this.findAll("\n");
434 this._lineEndings.push(this.length);
436 return this._lineEndings;
439 String.prototype.asParsedURL = function()
447 var match = this.match(/^([^:]+):\/\/([^\/:]*)(?::([\d]+))?(?:(\/[^#]*)(?:#(.*))?)?$/i);
451 result.scheme = match[1].toLowerCase();
452 result.host = match[2];
453 result.port = match[3];
454 result.path = match[4] || "/";
455 result.fragment = match[5];
457 result.lastPathComponent = "";
459 // First cut the query params.
460 var path = result.path;
461 var indexOfQuery = path.indexOf("?");
462 if (indexOfQuery !== -1)
463 path = path.substring(0, indexOfQuery);
465 // Then take last path component.
466 var lastSlashIndex = path.lastIndexOf("/");
467 if (lastSlashIndex !== -1)
468 result.lastPathComponent = path.substring(lastSlashIndex + 1);
473 String.prototype.escapeCharacters = function(chars)
475 var foundChar = false;
476 for (var i = 0; i < chars.length; ++i) {
477 if (this.indexOf(chars.charAt(i)) !== -1) {
487 for (var i = 0; i < this.length; ++i) {
488 if (chars.indexOf(this.charAt(i)) !== -1)
490 result += this.charAt(i);
496 String.prototype.escapeForRegExp = function()
498 return this.escapeCharacters("^[]{}()\\.$*+?|");
501 String.prototype.escapeHTML = function()
503 return this.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """); //" doublequotes just for editor
506 String.prototype.collapseWhitespace = function()
508 return this.replace(/[\s\xA0]+/g, " ");
511 String.prototype.trimMiddle = function(maxLength)
513 if (this.length <= maxLength)
515 var leftHalf = maxLength >> 1;
516 var rightHalf = maxLength - leftHalf - 1;
517 return this.substr(0, leftHalf) + "\u2026" + this.substr(this.length - rightHalf, rightHalf);
520 String.prototype.trimURL = function(baseURLDomain)
522 var result = this.replace(/^(https|http|file):\/\//i, "");
524 result = result.replace(new RegExp("^" + baseURLDomain.escapeForRegExp(), "i"), "");
528 String.prototype.removeURLFragment = function()
530 var fragmentIndex = this.indexOf("#");
531 if (fragmentIndex == -1)
532 fragmentIndex = this.length;
533 return this.substring(0, fragmentIndex);
536 Node.prototype.isAncestor = function(node)
541 var currentNode = node.parentNode;
542 while (currentNode) {
543 if (this === currentNode)
545 currentNode = currentNode.parentNode;
550 Node.prototype.isDescendant = function(descendant)
552 return !!descendant && descendant.isAncestor(this);
555 Node.prototype.traverseNextNode = function(stayWithin)
557 var node = this.firstChild;
561 if (stayWithin && this === stayWithin)
564 node = this.nextSibling;
569 while (node && !node.nextSibling && (!stayWithin || !node.parentNode || node.parentNode !== stayWithin))
570 node = node.parentNode;
574 return node.nextSibling;
577 Node.prototype.traversePreviousNode = function(stayWithin)
579 if (stayWithin && this === stayWithin)
581 var node = this.previousSibling;
582 while (node && node.lastChild)
583 node = node.lastChild;
586 return this.parentNode;
589 Number.constrain = function(num, min, max)
598 Date.prototype.toISO8601Compact = function()
602 return x > 9 ? '' + x : '0' + x
604 return this.getFullYear() +
605 leadZero(this.getMonth() + 1) +
606 leadZero(this.getDate()) + 'T' +
607 leadZero(this.getHours()) +
608 leadZero(this.getMinutes()) +
609 leadZero(this.getSeconds());
612 HTMLTextAreaElement.prototype.moveCursorToEnd = function()
614 var length = this.value.length;
615 this.setSelectionRange(length, length);
618 Object.defineProperty(Array.prototype, "remove",
623 value: function(value, onlyFirst)
626 var index = this.indexOf(value);
628 this.splice(index, 1);
632 var length = this.length;
633 for (var i = 0; i < length; ++i) {
634 if (this[i] === value)
640 Object.defineProperty(Array.prototype, "keySet",
648 for (var i = 0; i < this.length; ++i)
649 keys[this[i]] = true;
654 Object.defineProperty(Array.prototype, "upperBound",
657 * @this {Array.<number>}
659 value: function(value)
662 var count = this.length;
664 var step = count >> 1;
665 var middle = first + step;
666 if (value >= this[middle]) {
676 Array.diff = function(left, right)
684 for (var i = 0; i < n.length; i++) {
685 if (ns[n[i]] == null)
686 ns[n[i]] = { rows: [], o: null };
687 ns[n[i]].rows.push(i);
690 for (var i = 0; i < o.length; i++) {
691 if (os[o[i]] == null)
692 os[o[i]] = { rows: [], n: null };
693 os[o[i]].rows.push(i);
697 if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
698 n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] };
699 o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] };
703 for (var i = 0; i < n.length - 1; i++) {
704 if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) {
705 n[i + 1] = { text: n[i + 1], row: n[i].row + 1 };
706 o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 };
710 for (var i = n.length - 1; i > 0; i--) {
711 if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
712 n[i - 1] == o[n[i].row - 1]) {
713 n[i - 1] = { text: n[i - 1], row: n[i].row - 1 };
714 o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 };
718 return { left: o, right: n };
721 Array.convert = function(list)
723 // Cast array-like object to an array.
724 return Array.prototype.slice.call(list);
728 * @param {string} format
729 * @param {...*} var_arg
731 String.sprintf = function(format, var_arg)
733 return String.vsprintf(format, Array.prototype.slice.call(arguments, 1));
736 String.tokenizeFormatString = function(format)
739 var substitutionIndex = 0;
741 function addStringToken(str)
743 tokens.push({ type: "string", value: str });
746 function addSpecifierToken(specifier, precision, substitutionIndex)
748 tokens.push({ type: "specifier", specifier: specifier, precision: precision, substitutionIndex: substitutionIndex });
752 for (var precentIndex = format.indexOf("%", index); precentIndex !== -1; precentIndex = format.indexOf("%", index)) {
753 addStringToken(format.substring(index, precentIndex));
754 index = precentIndex + 1;
756 if (format[index] === "%") {
762 if (!isNaN(format[index])) {
763 // The first character is a number, it might be a substitution index.
764 var number = parseInt(format.substring(index), 10);
765 while (!isNaN(format[index]))
767 // If the number is greater than zero and ends with a "$",
768 // then this is a substitution index.
769 if (number > 0 && format[index] === "$") {
770 substitutionIndex = (number - 1);
776 if (format[index] === ".") {
777 // This is a precision specifier. If no digit follows the ".",
778 // then the precision should be zero.
780 precision = parseInt(format.substring(index), 10);
781 if (isNaN(precision))
783 while (!isNaN(format[index]))
787 addSpecifierToken(format[index], precision, substitutionIndex);
793 addStringToken(format.substring(index));
798 String.standardFormatters = {
799 d: function(substitution)
801 return !isNaN(substitution) ? substitution : 0;
804 f: function(substitution, token)
806 if (substitution && token.precision > -1)
807 substitution = substitution.toFixed(token.precision);
808 return !isNaN(substitution) ? substitution : (token.precision > -1 ? Number(0).toFixed(token.precision) : 0);
811 s: function(substitution)
817 String.vsprintf = function(format, substitutions)
819 return String.format(format, substitutions, String.standardFormatters, "", function(a, b) { return a + b; }).formattedResult;
822 String.format = function(format, substitutions, formatters, initialValue, append)
824 if (!format || !substitutions || !substitutions.length)
825 return { formattedResult: append(initialValue, format), unusedSubstitutions: substitutions };
827 function prettyFunctionName()
829 return "String.format(\"" + format + "\", \"" + substitutions.join("\", \"") + "\")";
834 console.warn(prettyFunctionName() + ": " + msg);
839 console.error(prettyFunctionName() + ": " + msg);
842 var result = initialValue;
843 var tokens = String.tokenizeFormatString(format);
844 var usedSubstitutionIndexes = {};
846 for (var i = 0; i < tokens.length; ++i) {
847 var token = tokens[i];
849 if (token.type === "string") {
850 result = append(result, token.value);
854 if (token.type !== "specifier") {
855 error("Unknown token type \"" + token.type + "\" found.");
859 if (token.substitutionIndex >= substitutions.length) {
860 // If there are not enough substitutions for the current substitutionIndex
861 // just output the format specifier literally and move on.
862 error("not enough substitution arguments. Had " + substitutions.length + " but needed " + (token.substitutionIndex + 1) + ", so substitution was skipped.");
863 result = append(result, "%" + (token.precision > -1 ? token.precision : "") + token.specifier);
867 usedSubstitutionIndexes[token.substitutionIndex] = true;
869 if (!(token.specifier in formatters)) {
870 // Encountered an unsupported format character, treat as a string.
871 warn("unsupported format character \u201C" + token.specifier + "\u201D. Treating as a string.");
872 result = append(result, substitutions[token.substitutionIndex]);
876 result = append(result, formatters[token.specifier](substitutions[token.substitutionIndex], token));
879 var unusedSubstitutions = [];
880 for (var i = 0; i < substitutions.length; ++i) {
881 if (i in usedSubstitutionIndexes)
883 unusedSubstitutions.push(substitutions[i]);
886 return { formattedResult: result, unusedSubstitutions: unusedSubstitutions };
889 function isEnterKey(event) {
891 return event.keyCode !== 229 && event.keyIdentifier === "Enter";
895 * @param {Element} element
896 * @param {number} offset
897 * @param {number} length
898 * @param {Array.<Object>=} domChanges
900 function highlightSearchResult(element, offset, length, domChanges)
902 var result = highlightSearchResults(element, [{offset: offset, length: length }], domChanges);
903 return result.length ? result[0] : null;
907 * @param {Element} element
908 * @param {Array.<Object>} resultRanges
909 * @param {Array.<Object>=} changes
911 function highlightSearchResults(element, resultRanges, changes)
913 return highlightRangesWithStyleClass(element, resultRanges, "webkit-search-result", changes);
918 * @param {Element} element
919 * @param {Array.<Object>} resultRanges
920 * @param {string} styleClass
921 * @param {Array.<Object>=} changes
923 function highlightRangesWithStyleClass(element, resultRanges, styleClass, changes)
925 changes = changes || [];
926 var highlightNodes = [];
927 var lineText = element.textContent;
928 var ownerDocument = element.ownerDocument;
929 var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
931 var snapshotLength = textNodeSnapshot.snapshotLength;
932 if (snapshotLength === 0)
933 return highlightNodes;
936 var rangeEndOffset = 0;
937 for (var i = 0; i < snapshotLength; ++i) {
939 range.offset = rangeEndOffset;
940 range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
941 rangeEndOffset = range.offset + range.length;
942 nodeRanges.push(range);
946 for (var i = 0; i < resultRanges.length; ++i) {
947 var startOffset = resultRanges[i].offset;
948 var endOffset = startOffset + resultRanges[i].length;
950 while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
952 var endIndex = startIndex;
953 while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
955 if (endIndex === snapshotLength)
958 var highlightNode = ownerDocument.createElement("span");
959 highlightNode.className = styleClass;
960 highlightNode.textContent = lineText.substring(startOffset, endOffset);
962 var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
963 var lastText = lastTextNode.textContent;
964 lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
965 changes.push({ node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent });
967 if (startIndex === endIndex) {
968 lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
969 changes.push({ node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement });
970 highlightNodes.push(highlightNode);
972 var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
973 lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
974 changes.push({ node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement });
976 var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
977 var firstText = firstTextNode.textContent;
978 var anchorElement = firstTextNode.nextSibling;
980 firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
981 changes.push({ node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement });
982 highlightNodes.push(highlightNode);
984 firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
985 changes.push({ node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent });
987 for (var j = startIndex + 1; j < endIndex; j++) {
988 var textNode = textNodeSnapshot.snapshotItem(j);
989 var text = textNode.textContent;
990 textNode.textContent = "";
991 changes.push({ node: textNode, type: "changed", oldText: text, newText: textNode.textContent });
994 startIndex = endIndex;
995 nodeRanges[startIndex].offset = endOffset;
996 nodeRanges[startIndex].length = lastTextNode.textContent.length;
999 return highlightNodes;
1002 function applyDomChanges(domChanges)
1004 for (var i = 0, size = domChanges.length; i < size; ++i) {
1005 var entry = domChanges[i];
1006 switch (entry.type) {
1008 entry.parent.insertBefore(entry.node, entry.nextSibling);
1011 entry.node.textContent = entry.newText;
1017 function revertDomChanges(domChanges)
1019 for (var i = domChanges.length - 1; i >= 0; --i) {
1020 var entry = domChanges[i];
1021 switch (entry.type) {
1023 if (entry.node.parentElement)
1024 entry.node.parentElement.removeChild(entry.node);
1027 entry.node.textContent = entry.oldText;
1034 * @param {string} query
1035 * @param {boolean} caseSensitive
1036 * @param {boolean} isRegex
1039 function createSearchRegex(query, caseSensitive, isRegex)
1041 var regexFlags = caseSensitive ? "g" : "gi";
1046 regexObject = new RegExp(query, regexFlags);
1053 regexObject = createPlainTextSearchRegex(query, regexFlags);
1059 * @param {string} query
1060 * @param {string=} flags
1063 function createPlainTextSearchRegex(query, flags)
1065 // This should be kept the same as the one in ContentSearchUtils.cpp.
1066 var regexSpecialCharacters = "[](){}+-*.,?\\^$|";
1068 for (var i = 0; i < query.length; ++i) {
1069 var c = query.charAt(i);
1070 if (regexSpecialCharacters.indexOf(c) != -1)
1074 return new RegExp(regex, flags || "");
1078 * @param {RegExp} regex
1079 * @param {string} content
1082 function countRegexMatches(regex, content)
1087 while (text && (match = regex.exec(text))) {
1088 if (match[0].length > 0)
1090 text = text.substring(match.index + 1);
1096 * @param {number} value
1097 * @param {number} symbolsCount
1100 function numberToStringWithSpacesPadding(value, symbolsCount)
1102 var numberString = value.toString();
1103 var paddingLength = Math.max(0, symbolsCount - numberString.length);
1104 var paddingString = Array(paddingLength + 1).join("\u00a0");
1105 return paddingString + numberString;
1119 * @param {string} baseContent
1120 * @param {string} newContent
1121 * @return {TextDiff}
1123 TextDiff.compute = function(baseContent, newContent)
1125 var oldLines = baseContent.split(/\r?\n/);
1126 var newLines = newContent.split(/\r?\n/);
1128 var diff = Array.diff(oldLines, newLines);
1130 var diffData = new TextDiff();
1133 var right = diff.right;
1134 for (var i = 0; i < right.length; ++i) {
1135 if (typeof right[i] === "string") {
1136 if (right.length > i + 1 && right[i + 1].row === i + 1 - offset)
1137 diffData.changed.push(i);
1139 diffData.added.push(i);
1143 offset = i - right[i].row;