DOMExtension.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /*
  2. * Copyright (C) 2007 Apple Inc. All rights reserved.
  3. * Copyright (C) 2012 Google Inc. All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. *
  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.
  17. *
  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.
  28. *
  29. * Contains diff method based on Javascript Diff Algorithm By John Resig
  30. * http://ejohn.org/files/jsdiff.js (released under the MIT license).
  31. */
  32. /**
  33. * @param {string=} direction
  34. */
  35. Node.prototype.rangeOfWord = function(offset, stopCharacters, stayWithinNode, direction)
  36. {
  37. var startNode;
  38. var startOffset = 0;
  39. var endNode;
  40. var endOffset = 0;
  41. if (!stayWithinNode)
  42. stayWithinNode = this;
  43. if (!direction || direction === "backward" || direction === "both") {
  44. var node = this;
  45. while (node) {
  46. if (node === stayWithinNode) {
  47. if (!startNode)
  48. startNode = stayWithinNode;
  49. break;
  50. }
  51. if (node.nodeType === Node.TEXT_NODE) {
  52. var start = (node === this ? (offset - 1) : (node.nodeValue.length - 1));
  53. for (var i = start; i >= 0; --i) {
  54. if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
  55. startNode = node;
  56. startOffset = i + 1;
  57. break;
  58. }
  59. }
  60. }
  61. if (startNode)
  62. break;
  63. node = node.traversePreviousNode(stayWithinNode);
  64. }
  65. if (!startNode) {
  66. startNode = stayWithinNode;
  67. startOffset = 0;
  68. }
  69. } else {
  70. startNode = this;
  71. startOffset = offset;
  72. }
  73. if (!direction || direction === "forward" || direction === "both") {
  74. node = this;
  75. while (node) {
  76. if (node === stayWithinNode) {
  77. if (!endNode)
  78. endNode = stayWithinNode;
  79. break;
  80. }
  81. if (node.nodeType === Node.TEXT_NODE) {
  82. var start = (node === this ? offset : 0);
  83. for (var i = start; i < node.nodeValue.length; ++i) {
  84. if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
  85. endNode = node;
  86. endOffset = i;
  87. break;
  88. }
  89. }
  90. }
  91. if (endNode)
  92. break;
  93. node = node.traverseNextNode(stayWithinNode);
  94. }
  95. if (!endNode) {
  96. endNode = stayWithinNode;
  97. endOffset = stayWithinNode.nodeType === Node.TEXT_NODE ? stayWithinNode.nodeValue.length : stayWithinNode.childNodes.length;
  98. }
  99. } else {
  100. endNode = this;
  101. endOffset = offset;
  102. }
  103. var result = this.ownerDocument.createRange();
  104. result.setStart(startNode, startOffset);
  105. result.setEnd(endNode, endOffset);
  106. return result;
  107. }
  108. Node.prototype.traverseNextTextNode = function(stayWithin)
  109. {
  110. var node = this.traverseNextNode(stayWithin);
  111. if (!node)
  112. return;
  113. while (node && node.nodeType !== Node.TEXT_NODE)
  114. node = node.traverseNextNode(stayWithin);
  115. return node;
  116. }
  117. Node.prototype.rangeBoundaryForOffset = function(offset)
  118. {
  119. var node = this.traverseNextTextNode(this);
  120. while (node && offset > node.nodeValue.length) {
  121. offset -= node.nodeValue.length;
  122. node = node.traverseNextTextNode(this);
  123. }
  124. if (!node)
  125. return { container: this, offset: 0 };
  126. return { container: node, offset: offset };
  127. }
  128. /**
  129. * @param {string} className
  130. */
  131. Element.prototype.removeStyleClass = function(className)
  132. {
  133. this.classList.remove(className);
  134. }
  135. Element.prototype.removeMatchingStyleClasses = function(classNameRegex)
  136. {
  137. var regex = new RegExp("(^|\\s+)" + classNameRegex + "($|\\s+)");
  138. if (regex.test(this.className))
  139. this.className = this.className.replace(regex, " ");
  140. }
  141. /**
  142. * @param {string} className
  143. */
  144. Element.prototype.addStyleClass = function(className)
  145. {
  146. this.classList.add(className);
  147. }
  148. /**
  149. * @param {string} className
  150. * @return {boolean}
  151. */
  152. Element.prototype.hasStyleClass = function(className)
  153. {
  154. return this.classList.contains(className);
  155. }
  156. /**
  157. * @param {string} className
  158. * @param {*} enable
  159. */
  160. Element.prototype.enableStyleClass = function(className, enable)
  161. {
  162. if (enable)
  163. this.addStyleClass(className);
  164. else
  165. this.removeStyleClass(className);
  166. }
  167. /**
  168. * @param {number|undefined} x
  169. * @param {number|undefined} y
  170. */
  171. Element.prototype.positionAt = function(x, y)
  172. {
  173. if (typeof x === "number")
  174. this.style.setProperty("left", x + "px");
  175. else
  176. this.style.removeProperty("left");
  177. if (typeof y === "number")
  178. this.style.setProperty("top", y + "px");
  179. else
  180. this.style.removeProperty("top");
  181. }
  182. Element.prototype.isScrolledToBottom = function()
  183. {
  184. // This code works only for 0-width border
  185. return this.scrollTop + this.clientHeight === this.scrollHeight;
  186. }
  187. /**
  188. * @param {Node} fromNode
  189. * @param {Node} toNode
  190. */
  191. function removeSubsequentNodes(fromNode, toNode)
  192. {
  193. for (var node = fromNode; node && node !== toNode; ) {
  194. var nodeToRemove = node;
  195. node = node.nextSibling;
  196. nodeToRemove.remove();
  197. }
  198. }
  199. /**
  200. * @constructor
  201. * @param {number} width
  202. * @param {number} height
  203. */
  204. function Size(width, height)
  205. {
  206. this.width = width;
  207. this.height = height;
  208. }
  209. /**
  210. * @param {Element=} containerElement
  211. * @return {Size}
  212. */
  213. Element.prototype.measurePreferredSize = function(containerElement)
  214. {
  215. containerElement = containerElement || document.body;
  216. containerElement.appendChild(this);
  217. this.positionAt(0, 0);
  218. var result = new Size(this.offsetWidth, this.offsetHeight);
  219. this.positionAt(undefined, undefined);
  220. this.remove();
  221. return result;
  222. }
  223. Node.prototype.enclosingNodeOrSelfWithNodeNameInArray = function(nameArray)
  224. {
  225. for (var node = this; node && node !== this.ownerDocument; node = node.parentNode)
  226. for (var i = 0; i < nameArray.length; ++i)
  227. if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase())
  228. return node;
  229. return null;
  230. }
  231. Node.prototype.enclosingNodeOrSelfWithNodeName = function(nodeName)
  232. {
  233. return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);
  234. }
  235. /**
  236. * @param {string} className
  237. * @param {Element=} stayWithin
  238. */
  239. Node.prototype.enclosingNodeOrSelfWithClass = function(className, stayWithin)
  240. {
  241. for (var node = this; node && node !== stayWithin && node !== this.ownerDocument; node = node.parentNode)
  242. if (node.nodeType === Node.ELEMENT_NODE && node.hasStyleClass(className))
  243. return node;
  244. return null;
  245. }
  246. Element.prototype.query = function(query)
  247. {
  248. return this.ownerDocument.evaluate(query, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  249. }
  250. Element.prototype.removeChildren = function()
  251. {
  252. if (this.firstChild)
  253. this.textContent = "";
  254. }
  255. Element.prototype.isInsertionCaretInside = function()
  256. {
  257. var selection = window.getSelection();
  258. if (!selection.rangeCount || !selection.isCollapsed)
  259. return false;
  260. var selectionRange = selection.getRangeAt(0);
  261. return selectionRange.startContainer.isSelfOrDescendant(this);
  262. }
  263. /**
  264. * @param {string=} className
  265. */
  266. Element.prototype.createChild = function(elementName, className)
  267. {
  268. var element = this.ownerDocument.createElement(elementName);
  269. if (className)
  270. element.className = className;
  271. this.appendChild(element);
  272. return element;
  273. }
  274. DocumentFragment.prototype.createChild = Element.prototype.createChild;
  275. /**
  276. * @param {string} text
  277. */
  278. Element.prototype.createTextChild = function(text)
  279. {
  280. var element = this.ownerDocument.createTextNode(text);
  281. this.appendChild(element);
  282. return element;
  283. }
  284. DocumentFragment.prototype.createTextChild = Element.prototype.createTextChild;
  285. /**
  286. * @return {number}
  287. */
  288. Element.prototype.totalOffsetLeft = function()
  289. {
  290. return this.totalOffset().left;
  291. }
  292. /**
  293. * @return {number}
  294. */
  295. Element.prototype.totalOffsetTop = function()
  296. {
  297. return this.totalOffset().top;
  298. }
  299. Element.prototype.totalOffset = function()
  300. {
  301. var totalLeft = 0;
  302. var totalTop = 0;
  303. for (var element = this; element; element = element.offsetParent) {
  304. totalLeft += element.offsetLeft;
  305. totalTop += element.offsetTop;
  306. if (this !== element) {
  307. totalLeft += element.clientLeft - element.scrollLeft;
  308. totalTop += element.clientTop - element.scrollTop;
  309. }
  310. }
  311. return { left: totalLeft, top: totalTop };
  312. }
  313. Element.prototype.scrollOffset = function()
  314. {
  315. var curLeft = 0;
  316. var curTop = 0;
  317. for (var element = this; element; element = element.scrollParent) {
  318. curLeft += element.scrollLeft;
  319. curTop += element.scrollTop;
  320. }
  321. return { left: curLeft, top: curTop };
  322. }
  323. /**
  324. * @constructor
  325. * @param {number=} x
  326. * @param {number=} y
  327. * @param {number=} width
  328. * @param {number=} height
  329. */
  330. function AnchorBox(x, y, width, height)
  331. {
  332. this.x = x || 0;
  333. this.y = y || 0;
  334. this.width = width || 0;
  335. this.height = height || 0;
  336. }
  337. /**
  338. * @param {Window} targetWindow
  339. * @return {AnchorBox}
  340. */
  341. Element.prototype.offsetRelativeToWindow = function(targetWindow)
  342. {
  343. var elementOffset = new AnchorBox();
  344. var curElement = this;
  345. var curWindow = this.ownerDocument.defaultView;
  346. while (curWindow && curElement) {
  347. elementOffset.x += curElement.totalOffsetLeft();
  348. elementOffset.y += curElement.totalOffsetTop();
  349. if (curWindow === targetWindow)
  350. break;
  351. curElement = curWindow.frameElement;
  352. curWindow = curWindow.parent;
  353. }
  354. return elementOffset;
  355. }
  356. /**
  357. * @param {Window} targetWindow
  358. * @return {AnchorBox}
  359. */
  360. Element.prototype.boxInWindow = function(targetWindow)
  361. {
  362. targetWindow = targetWindow || this.ownerDocument.defaultView;
  363. var anchorBox = this.offsetRelativeToWindow(window);
  364. anchorBox.width = Math.min(this.offsetWidth, window.innerWidth - anchorBox.x);
  365. anchorBox.height = Math.min(this.offsetHeight, window.innerHeight - anchorBox.y);
  366. return anchorBox;
  367. }
  368. /**
  369. * @param {string} text
  370. */
  371. Element.prototype.setTextAndTitle = function(text)
  372. {
  373. this.textContent = text;
  374. this.title = text;
  375. }
  376. KeyboardEvent.prototype.__defineGetter__("data", function()
  377. {
  378. // Emulate "data" attribute from DOM 3 TextInput event.
  379. // See http://www.w3.org/TR/DOM-Level-3-Events/#events-Events-TextEvent-data
  380. switch (this.type) {
  381. case "keypress":
  382. if (!this.ctrlKey && !this.metaKey)
  383. return String.fromCharCode(this.charCode);
  384. else
  385. return "";
  386. case "keydown":
  387. case "keyup":
  388. if (!this.ctrlKey && !this.metaKey && !this.altKey)
  389. return String.fromCharCode(this.which);
  390. else
  391. return "";
  392. }
  393. });
  394. /**
  395. * @param {boolean=} preventDefault
  396. */
  397. Event.prototype.consume = function(preventDefault)
  398. {
  399. this.stopImmediatePropagation();
  400. if (preventDefault)
  401. this.preventDefault();
  402. this.handled = true;
  403. }
  404. Text.prototype.select = function(start, end)
  405. {
  406. start = start || 0;
  407. end = end || this.textContent.length;
  408. if (start < 0)
  409. start = end + start;
  410. var selection = this.ownerDocument.defaultView.getSelection();
  411. selection.removeAllRanges();
  412. var range = this.ownerDocument.createRange();
  413. range.setStart(this, start);
  414. range.setEnd(this, end);
  415. selection.addRange(range);
  416. return this;
  417. }
  418. Element.prototype.selectionLeftOffset = function()
  419. {
  420. // Calculate selection offset relative to the current element.
  421. var selection = window.getSelection();
  422. if (!selection.containsNode(this, true))
  423. return null;
  424. var leftOffset = selection.anchorOffset;
  425. var node = selection.anchorNode;
  426. while (node !== this) {
  427. while (node.previousSibling) {
  428. node = node.previousSibling;
  429. leftOffset += node.textContent.length;
  430. }
  431. node = node.parentNode;
  432. }
  433. return leftOffset;
  434. }
  435. Node.prototype.isAncestor = function(node)
  436. {
  437. if (!node)
  438. return false;
  439. var currentNode = node.parentNode;
  440. while (currentNode) {
  441. if (this === currentNode)
  442. return true;
  443. currentNode = currentNode.parentNode;
  444. }
  445. return false;
  446. }
  447. Node.prototype.isDescendant = function(descendant)
  448. {
  449. return !!descendant && descendant.isAncestor(this);
  450. }
  451. Node.prototype.isSelfOrAncestor = function(node)
  452. {
  453. return !!node && (node === this || this.isAncestor(node));
  454. }
  455. Node.prototype.isSelfOrDescendant = function(node)
  456. {
  457. return !!node && (node === this || this.isDescendant(node));
  458. }
  459. Node.prototype.traverseNextNode = function(stayWithin)
  460. {
  461. var node = this.firstChild;
  462. if (node)
  463. return node;
  464. if (stayWithin && this === stayWithin)
  465. return null;
  466. node = this.nextSibling;
  467. if (node)
  468. return node;
  469. node = this;
  470. while (node && !node.nextSibling && (!stayWithin || !node.parentNode || node.parentNode !== stayWithin))
  471. node = node.parentNode;
  472. if (!node)
  473. return null;
  474. return node.nextSibling;
  475. }
  476. Node.prototype.traversePreviousNode = function(stayWithin)
  477. {
  478. if (stayWithin && this === stayWithin)
  479. return null;
  480. var node = this.previousSibling;
  481. while (node && node.lastChild)
  482. node = node.lastChild;
  483. if (node)
  484. return node;
  485. return this.parentNode;
  486. }
  487. function isEnterKey(event) {
  488. // Check if in IME.
  489. return event.keyCode !== 229 && event.keyIdentifier === "Enter";
  490. }
  491. function consumeEvent(e)
  492. {
  493. e.consume();
  494. }
  495. /**
  496. * Mutation observers leak memory. Keep track of them and disconnect
  497. * on unload.
  498. * @constructor
  499. * @param {function(Array.<WebKitMutation>)} handler
  500. */
  501. function NonLeakingMutationObserver(handler)
  502. {
  503. this._observer = new WebKitMutationObserver(handler);
  504. NonLeakingMutationObserver._instances.push(this);
  505. if (!NonLeakingMutationObserver._unloadListener) {
  506. NonLeakingMutationObserver._unloadListener = function() {
  507. while (NonLeakingMutationObserver._instances.length)
  508. NonLeakingMutationObserver._instances[NonLeakingMutationObserver._instances.length - 1].disconnect();
  509. };
  510. window.addEventListener("unload", NonLeakingMutationObserver._unloadListener, false);
  511. }
  512. }
  513. NonLeakingMutationObserver._instances = [];
  514. NonLeakingMutationObserver.prototype = {
  515. /**
  516. * @param {Element} element
  517. * @param {Object} config
  518. */
  519. observe: function(element, config)
  520. {
  521. if (this._observer)
  522. this._observer.observe(element, config);
  523. },
  524. disconnect: function()
  525. {
  526. if (this._observer)
  527. this._observer.disconnect();
  528. NonLeakingMutationObserver._instances.remove(this);
  529. delete this._observer;
  530. }
  531. }