You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

765 lines
29 KiB

  1. // Cross-broswer implementation of text ranges and selections
  2. // documentation: http://bililite.com/blog/2011/01/17/cross-browser-text-ranges-and-selections/
  3. // Version: 2.6
  4. // Copyright (c) 2013 Daniel Wachsstock
  5. // MIT license:
  6. // Permission is hereby granted, free of charge, to any person
  7. // obtaining a copy of this software and associated documentation
  8. // files (the "Software"), to deal in the Software without
  9. // restriction, including without limitation the rights to use,
  10. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the
  12. // Software is furnished to do so, subject to the following
  13. // conditions:
  14. // The above copyright notice and this permission notice shall be
  15. // included in all copies or substantial portions of the Software.
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. (function(){
  25. // a bit of weirdness with IE11: using 'focus' is flaky, even if I'm not bubbling, as far as I can tell.
  26. var focusEvent = 'onfocusin' in document.createElement('input') ? 'focusin' : 'focus';
  27. // IE11 normalize is buggy (http://connect.microsoft.com/IE/feedback/details/809424/node-normalize-removes-text-if-dashes-are-present)
  28. var n = document.createElement('div');
  29. n.appendChild(document.createTextNode('x-'));
  30. n.appendChild(document.createTextNode('x'));
  31. n.normalize();
  32. var canNormalize = n.firstChild.length == 3;
  33. bililiteRange = function(el, debug){
  34. var ret;
  35. if (debug){
  36. ret = new NothingRange(); // Easier to force it to use the no-selection type than to try to find an old browser
  37. }else if (window.getSelection && el.setSelectionRange){
  38. // Standards. Element is an input or textarea
  39. // note that some input elements do not allow selections
  40. try{
  41. el.selectionStart; // even getting the selection in such an element will throw
  42. ret = new InputRange();
  43. }catch(e){
  44. ret = new NothingRange();
  45. }
  46. }else if (window.getSelection){
  47. // Standards, with any other kind of element
  48. ret = new W3CRange();
  49. }else if (document.selection){
  50. // Internet Explorer
  51. ret = new IERange();
  52. }else{
  53. // doesn't support selection
  54. ret = new NothingRange();
  55. }
  56. ret._el = el;
  57. // determine parent document, as implemented by John McLear <john@mclear.co.uk>
  58. ret._doc = el.ownerDocument;
  59. ret._win = 'defaultView' in ret._doc ? ret._doc.defaultView : ret._doc.parentWindow;
  60. ret._textProp = textProp(el);
  61. ret._bounds = [0, ret.length()];
  62. // There's no way to detect whether a focus event happened as a result of a click (which should change the selection)
  63. // or as a result of a keyboard event (a tab in) or a script action (el.focus()). So we track it globally, which is a hack, and is likely to fail
  64. // in edge cases (right-clicks, drag-n-drop), and is vulnerable to a lower-down handler preventing bubbling.
  65. // I just don't know a better way.
  66. // I'll hack my event-listening code below, rather than create an entire new bilililiteRange, potentially before the DOM has loaded
  67. if (!('bililiteRangeMouseDown' in ret._doc)){
  68. var _doc = {_el: ret._doc};
  69. ret._doc.bililiteRangeMouseDown = false;
  70. bililiteRange.fn.listen.call(_doc, 'mousedown', function() {
  71. ret._doc.bililiteRangeMouseDown = true;
  72. });
  73. bililiteRange.fn.listen.call(_doc, 'mouseup', function() {
  74. ret._doc.bililiteRangeMouseDown = false;
  75. });
  76. }
  77. // note that bililiteRangeSelection is an array, which means that copying it only copies the address, which points to the original.
  78. // make sure that we never let it (always do return [bililiteRangeSelection[0], bililiteRangeSelection[1]]), which means never returning
  79. // this._bounds directly
  80. if (!('bililiteRangeSelection' in el)){
  81. // start tracking the selection
  82. function trackSelection(evt){
  83. if (evt && evt.which == 9){
  84. // do tabs my way, by restoring the selection
  85. // there's a flash of the browser's selection, but I don't see a way of avoiding that
  86. ret._nativeSelect(ret._nativeRange(el.bililiteRangeSelection));
  87. }else{
  88. el.bililiteRangeSelection = ret._nativeSelection();
  89. }
  90. }
  91. trackSelection();
  92. // only IE does this right and allows us to grab the selection before blurring
  93. if ('onbeforedeactivate' in el){
  94. ret.listen('beforedeactivate', trackSelection);
  95. }else{
  96. // with standards-based browsers, have to listen for every user interaction
  97. ret.listen('mouseup', trackSelection).listen('keyup', trackSelection);
  98. }
  99. ret.listen(focusEvent, function(){
  100. // restore the correct selection when the element comes into focus (mouse clicks change the position of the selection)
  101. // Note that Firefox will not fire the focus event until the window/tab is active even if el.focus() is called
  102. // https://bugzilla.mozilla.org/show_bug.cgi?id=566671
  103. if (!ret._doc.bililiteRangeMouseDown){
  104. ret._nativeSelect(ret._nativeRange(el.bililiteRangeSelection));
  105. }
  106. });
  107. }
  108. if (!('oninput' in el)){
  109. // give IE8 a chance. Note that this still fails in IE11, which has has oninput on contenteditable elements but does not
  110. // dispatch input events. See http://connect.microsoft.com/IE/feedback/details/794285/ie10-11-input-event-does-not-fire-on-div-with-contenteditable-set
  111. // TODO: revisit this when I have IE11 running on my development machine
  112. var inputhack = function() {ret.dispatch({type: 'input', bubbles: true}) };
  113. ret.listen('keyup', inputhack);
  114. ret.listen('cut', inputhack);
  115. ret.listen('paste', inputhack);
  116. ret.listen('drop', inputhack);
  117. el.oninput = 'patched';
  118. }
  119. return ret;
  120. }
  121. function textProp(el){
  122. // returns the property that contains the text of the element
  123. // note that for <body> elements the text attribute represents the obsolete text color, not the textContent.
  124. // we document that these routines do not work for <body> elements so that should not be relevant
  125. // Bugfix for https://github.com/dwachss/bililiteRange/issues/18
  126. // Adding typeof check of string for el.value in case for li elements
  127. if (typeof el.value === 'string') return 'value';
  128. if (typeof el.text != 'undefined') return 'text';
  129. if (typeof el.textContent != 'undefined') return 'textContent';
  130. return 'innerText';
  131. }
  132. // base class
  133. function Range(){}
  134. Range.prototype = {
  135. length: function() {
  136. return this._el[this._textProp].replace(/\r/g, '').length; // need to correct for IE's CrLf weirdness
  137. },
  138. bounds: function(s){
  139. if (bililiteRange.bounds[s]){
  140. this._bounds = bililiteRange.bounds[s].apply(this);
  141. }else if (s){
  142. this._bounds = s; // don't do error checking now; things may change at a moment's notice
  143. }else{
  144. var b = [
  145. Math.max(0, Math.min (this.length(), this._bounds[0])),
  146. Math.max(0, Math.min (this.length(), this._bounds[1]))
  147. ];
  148. b[1] = Math.max(b[0], b[1]);
  149. return b; // need to constrain it to fit
  150. }
  151. return this; // allow for chaining
  152. },
  153. select: function(){
  154. var b = this._el.bililiteRangeSelection = this.bounds();
  155. if (this._el === this._doc.activeElement){
  156. // only actually select if this element is active!
  157. this._nativeSelect(this._nativeRange(b));
  158. }
  159. this.dispatch({type: 'select', bubbles: true});
  160. return this; // allow for chaining
  161. },
  162. text: function(text, select){
  163. if (arguments.length){
  164. var bounds = this.bounds(), el = this._el;
  165. // signal the input per DOM 3 input events, http://www.w3.org/TR/DOM-Level-3-Events/#h4_events-inputevents
  166. // we add another field, bounds, which are the bounds of the original text before being changed.
  167. this.dispatch({type: 'beforeinput', bubbles: true,
  168. data: text, bounds: bounds});
  169. this._nativeSetText(text, this._nativeRange(bounds));
  170. if (select == 'start'){
  171. this.bounds ([bounds[0], bounds[0]]);
  172. }else if (select == 'end'){
  173. this.bounds ([bounds[0]+text.length, bounds[0]+text.length]);
  174. }else if (select == 'all'){
  175. this.bounds ([bounds[0], bounds[0]+text.length]);
  176. }
  177. this.dispatch({type: 'input', bubbles: true,
  178. data: text, bounds: bounds});
  179. return this; // allow for chaining
  180. }else{
  181. return this._nativeGetText(this._nativeRange(this.bounds())).replace(/\r/g, ''); // need to correct for IE's CrLf weirdness
  182. }
  183. },
  184. insertEOL: function (){
  185. this._nativeEOL();
  186. this._bounds = [this._bounds[0]+1, this._bounds[0]+1]; // move past the EOL marker
  187. return this;
  188. },
  189. sendkeys: function (text){
  190. var self = this;
  191. this.data().sendkeysOriginalText = this.text();
  192. this.data().sendkeysBounds = undefined;
  193. function simplechar (rng, c){
  194. if (/^{[^}]*}$/.test(c)) c = c.slice(1,-1); // deal with unknown {key}s
  195. for (var i =0; i < c.length; ++i){
  196. var x = c.charCodeAt(i);
  197. rng.dispatch({type: 'keypress', bubbles: true, keyCode: x, which: x, charCode: x});
  198. }
  199. rng.text(c, 'end');
  200. }
  201. text.replace(/{[^}]*}|[^{]+|{/g, function(part){
  202. (bililiteRange.sendkeys[part] || simplechar)(self, part, simplechar);
  203. });
  204. this.bounds(this.data().sendkeysBounds);
  205. this.dispatch({type: 'sendkeys', which: text});
  206. return this;
  207. },
  208. top: function(){
  209. return this._nativeTop(this._nativeRange(this.bounds()));
  210. },
  211. scrollIntoView: function(scroller){
  212. var top = this.top();
  213. // scroll into position if necessary
  214. if (this._el.scrollTop > top || this._el.scrollTop+this._el.clientHeight < top){
  215. if (scroller){
  216. scroller.call(this._el, top);
  217. }else{
  218. this._el.scrollTop = top;
  219. }
  220. }
  221. return this;
  222. },
  223. wrap: function (n){
  224. this._nativeWrap(n, this._nativeRange(this.bounds()));
  225. return this;
  226. },
  227. selection: function(text){
  228. if (arguments.length){
  229. return this.bounds('selection').text(text, 'end').select();
  230. }else{
  231. return this.bounds('selection').text();
  232. }
  233. },
  234. clone: function(){
  235. return bililiteRange(this._el).bounds(this.bounds());
  236. },
  237. all: function(text){
  238. if (arguments.length){
  239. this.dispatch ({type: 'beforeinput', bubbles: true, data: text});
  240. this._el[this._textProp] = text;
  241. this.dispatch ({type: 'input', bubbles: true, data: text});
  242. return this;
  243. }else{
  244. return this._el[this._textProp].replace(/\r/g, ''); // need to correct for IE's CrLf weirdness
  245. }
  246. },
  247. element: function() { return this._el },
  248. // includes a quickie polyfill for CustomEvent for IE that isn't perfect but works for me
  249. // IE10 allows custom events but not "new CustomEvent"; have to do it the old-fashioned way
  250. dispatch: function(opts){
  251. opts = opts || {};
  252. var event = document.createEvent ? document.createEvent('CustomEvent') : this._doc.createEventObject();
  253. event.initCustomEvent && event.initCustomEvent(opts.type, !!opts.bubbles, !!opts.cancelable, opts.detail);
  254. for (var key in opts) event[key] = opts[key];
  255. // dispatch event asynchronously (in the sense of on the next turn of the event loop; still should be fired in order of dispatch
  256. var el = this._el;
  257. setTimeout(function(){
  258. try {
  259. el.dispatchEvent ? el.dispatchEvent(event) : el.fireEvent("on" + opts.type, document.createEventObject());
  260. }catch(e){
  261. // IE8 will not let me fire custom events at all. Call them directly
  262. var listeners = el['listen'+opts.type];
  263. if (listeners) for (var i = 0; i < listeners.length; ++i){
  264. listeners[i].call(el, event);
  265. }
  266. }
  267. }, 0);
  268. return this;
  269. },
  270. listen: function (type, func){
  271. var el = this._el;
  272. if (el.addEventListener){
  273. el.addEventListener(type, func);
  274. }else{
  275. el.attachEvent("on" + type, func);
  276. // IE8 can't even handle custom events created with createEventObject (though it permits attachEvent), so we have to make our own
  277. var listeners = el['listen'+type] = el['listen'+type] || [];
  278. listeners.push(func);
  279. }
  280. return this;
  281. },
  282. dontlisten: function (type, func){
  283. var el = this._el;
  284. if (el.removeEventListener){
  285. el.removeEventListener(type, func);
  286. }else try{
  287. el.detachEvent("on" + type, func);
  288. }catch(e){
  289. var listeners = el['listen'+type];
  290. if (listeners) for (var i = 0; i < listeners.length; ++i){
  291. if (listeners[i] === func) listeners[i] = function(){}; // replace with a noop
  292. }
  293. }
  294. return this;
  295. }
  296. };
  297. // allow extensions ala jQuery
  298. bililiteRange.fn = Range.prototype; // to allow monkey patching
  299. bililiteRange.extend = function(fns){
  300. for (fn in fns) Range.prototype[fn] = fns[fn];
  301. };
  302. //bounds functions
  303. bililiteRange.bounds = {
  304. all: function() { return [0, this.length()] },
  305. start: function () { return [0,0] },
  306. end: function () { return [this.length(), this.length()] },
  307. selection: function(){
  308. if (this._el === this._doc.activeElement){
  309. this.bounds ('all'); // first select the whole thing for constraining
  310. return this._nativeSelection();
  311. }else{
  312. return this._el.bililiteRangeSelection;
  313. }
  314. }
  315. };
  316. // sendkeys functions
  317. bililiteRange.sendkeys = {
  318. '{enter}': function (rng){
  319. rng.dispatch({type: 'keypress', bubbles: true, keyCode: '\n', which: '\n', charCode: '\n'});
  320. rng.insertEOL();
  321. },
  322. '{tab}': function (rng, c, simplechar){
  323. simplechar(rng, '\t'); // useful for inserting what would be whitespace
  324. },
  325. '{newline}': function (rng, c, simplechar){
  326. simplechar(rng, '\n'); // useful for inserting what would be whitespace (and if I don't want to use insertEOL, which does some fancy things)
  327. },
  328. '{backspace}': function (rng){
  329. var b = rng.bounds();
  330. if (b[0] == b[1]) rng.bounds([b[0]-1, b[0]]); // no characters selected; it's just an insertion point. Remove the previous character
  331. rng.text('', 'end'); // delete the characters and update the selection
  332. },
  333. '{del}': function (rng){
  334. var b = rng.bounds();
  335. if (b[0] == b[1]) rng.bounds([b[0], b[0]+1]); // no characters selected; it's just an insertion point. Remove the next character
  336. rng.text('', 'end'); // delete the characters and update the selection
  337. },
  338. '{rightarrow}': function (rng){
  339. var b = rng.bounds();
  340. if (b[0] == b[1]) ++b[1]; // no characters selected; it's just an insertion point. Move to the right
  341. rng.bounds([b[1], b[1]]);
  342. },
  343. '{leftarrow}': function (rng){
  344. var b = rng.bounds();
  345. if (b[0] == b[1]) --b[0]; // no characters selected; it's just an insertion point. Move to the left
  346. rng.bounds([b[0], b[0]]);
  347. },
  348. '{selectall}' : function (rng){
  349. rng.bounds('all');
  350. },
  351. '{selection}': function (rng){
  352. // insert the characters without the sendkeys processing
  353. var s = rng.data().sendkeysOriginalText;
  354. for (var i =0; i < s.length; ++i){
  355. var x = s.charCodeAt(i);
  356. rng.dispatch({type: 'keypress', bubbles: true, keyCode: x, which: x, charCode: x});
  357. }
  358. rng.text(s, 'end');
  359. },
  360. '{mark}' : function (rng){
  361. rng.data().sendkeysBounds = rng.bounds();
  362. }
  363. };
  364. // Synonyms from the proposed DOM standard (http://www.w3.org/TR/DOM-Level-3-Events-key/)
  365. bililiteRange.sendkeys['{Enter}'] = bililiteRange.sendkeys['{enter}'];
  366. bililiteRange.sendkeys['{Backspace}'] = bililiteRange.sendkeys['{backspace}'];
  367. bililiteRange.sendkeys['{Delete}'] = bililiteRange.sendkeys['{del}'];
  368. bililiteRange.sendkeys['{ArrowRight}'] = bililiteRange.sendkeys['{rightarrow}'];
  369. bililiteRange.sendkeys['{ArrowLeft}'] = bililiteRange.sendkeys['{leftarrow}'];
  370. function IERange(){}
  371. IERange.prototype = new Range();
  372. IERange.prototype._nativeRange = function (bounds){
  373. var rng;
  374. if (this._el.tagName == 'INPUT'){
  375. // IE 8 is very inconsistent; textareas have createTextRange but it doesn't work
  376. rng = this._el.createTextRange();
  377. }else{
  378. rng = this._doc.body.createTextRange ();
  379. rng.moveToElementText(this._el);
  380. }
  381. if (bounds){
  382. if (bounds[1] < 0) bounds[1] = 0; // IE tends to run elements out of bounds
  383. if (bounds[0] > this.length()) bounds[0] = this.length();
  384. if (bounds[1] < rng.text.replace(/\r/g, '').length){ // correct for IE's CrLf weirdness
  385. // block-display elements have an invisible, uncounted end of element marker, so we move an extra one and use the current length of the range
  386. rng.moveEnd ('character', -1);
  387. rng.moveEnd ('character', bounds[1]-rng.text.replace(/\r/g, '').length);
  388. }
  389. if (bounds[0] > 0) rng.moveStart('character', bounds[0]);
  390. }
  391. return rng;
  392. };
  393. IERange.prototype._nativeSelect = function (rng){
  394. rng.select();
  395. };
  396. IERange.prototype._nativeSelection = function (){
  397. // returns [start, end] for the selection constrained to be in element
  398. var rng = this._nativeRange(); // range of the element to constrain to
  399. var len = this.length();
  400. var sel = this._doc.selection.createRange();
  401. try{
  402. return [
  403. iestart(sel, rng),
  404. ieend (sel, rng)
  405. ];
  406. }catch (e){
  407. // TODO: determine if this is still necessary, since we only call _nativeSelection if _el is active
  408. // IE gets upset sometimes about comparing text to input elements, but the selections cannot overlap, so make a best guess
  409. return (sel.parentElement().sourceIndex < this._el.sourceIndex) ? [0,0] : [len, len];
  410. }
  411. };
  412. IERange.prototype._nativeGetText = function (rng){
  413. return rng.text;
  414. };
  415. IERange.prototype._nativeSetText = function (text, rng){
  416. rng.text = text;
  417. };
  418. IERange.prototype._nativeEOL = function(){
  419. if ('value' in this._el){
  420. this.text('\n'); // for input and textarea, insert it straight
  421. }else{
  422. this._nativeRange(this.bounds()).pasteHTML('\n<br/>');
  423. }
  424. };
  425. IERange.prototype._nativeTop = function(rng){
  426. var startrng = this._nativeRange([0,0]);
  427. return rng.boundingTop - startrng.boundingTop;
  428. }
  429. IERange.prototype._nativeWrap = function(n, rng) {
  430. // hacky to use string manipulation but I don't see another way to do it.
  431. var div = document.createElement('div');
  432. div.appendChild(n);
  433. // insert the existing range HTML after the first tag
  434. var html = div.innerHTML.replace('><', '>'+rng.htmlText+'<');
  435. rng.pasteHTML(html);
  436. };
  437. // IE internals
  438. function iestart(rng, constraint){
  439. // returns the position (in character) of the start of rng within constraint. If it's not in constraint, returns 0 if it's before, length if it's after
  440. var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf weirdness
  441. if (rng.compareEndPoints ('StartToStart', constraint) <= 0) return 0; // at or before the beginning
  442. if (rng.compareEndPoints ('StartToEnd', constraint) >= 0) return len;
  443. for (var i = 0; rng.compareEndPoints ('StartToStart', constraint) > 0; ++i, rng.moveStart('character', -1));
  444. return i;
  445. }
  446. function ieend (rng, constraint){
  447. // returns the position (in character) of the end of rng within constraint. If it's not in constraint, returns 0 if it's before, length if it's after
  448. var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf weirdness
  449. if (rng.compareEndPoints ('EndToEnd', constraint) >= 0) return len; // at or after the end
  450. if (rng.compareEndPoints ('EndToStart', constraint) <= 0) return 0;
  451. for (var i = 0; rng.compareEndPoints ('EndToStart', constraint) > 0; ++i, rng.moveEnd('character', -1));
  452. return i;
  453. }
  454. // an input element in a standards document. "Native Range" is just the bounds array
  455. function InputRange(){}
  456. InputRange.prototype = new Range();
  457. InputRange.prototype._nativeRange = function(bounds) {
  458. return bounds || [0, this.length()];
  459. };
  460. InputRange.prototype._nativeSelect = function (rng){
  461. this._el.setSelectionRange(rng[0], rng[1]);
  462. };
  463. InputRange.prototype._nativeSelection = function(){
  464. return [this._el.selectionStart, this._el.selectionEnd];
  465. };
  466. InputRange.prototype._nativeGetText = function(rng){
  467. return this._el.value.substring(rng[0], rng[1]);
  468. };
  469. InputRange.prototype._nativeSetText = function(text, rng){
  470. var val = this._el.value;
  471. this._el.value = val.substring(0, rng[0]) + text + val.substring(rng[1]);
  472. };
  473. InputRange.prototype._nativeEOL = function(){
  474. this.text('\n');
  475. };
  476. InputRange.prototype._nativeTop = function(rng){
  477. // I can't remember where I found this clever hack to find the location of text in a text area
  478. var clone = this._el.cloneNode(true);
  479. clone.style.visibility = 'hidden';
  480. clone.style.position = 'absolute';
  481. this._el.parentNode.insertBefore(clone, this._el);
  482. clone.style.height = '1px';
  483. clone.value = this._el.value.slice(0, rng[0]);
  484. var top = clone.scrollHeight;
  485. // this gives the bottom of the text, so we have to subtract the height of a single line
  486. clone.value = 'X';
  487. top -= clone.scrollHeight;
  488. clone.parentNode.removeChild(clone);
  489. return top;
  490. }
  491. InputRange.prototype._nativeWrap = function() {throw new Error("Cannot wrap in a text element")};
  492. function W3CRange(){}
  493. W3CRange.prototype = new Range();
  494. W3CRange.prototype._nativeRange = function (bounds){
  495. var rng = this._doc.createRange();
  496. rng.selectNodeContents(this._el);
  497. if (bounds){
  498. w3cmoveBoundary (rng, bounds[0], true, this._el);
  499. rng.collapse (true);
  500. w3cmoveBoundary (rng, bounds[1]-bounds[0], false, this._el);
  501. }
  502. return rng;
  503. };
  504. W3CRange.prototype._nativeSelect = function (rng){
  505. this._win.getSelection().removeAllRanges();
  506. this._win.getSelection().addRange (rng);
  507. };
  508. W3CRange.prototype._nativeSelection = function (){
  509. // returns [start, end] for the selection constrained to be in element
  510. var rng = this._nativeRange(); // range of the element to constrain to
  511. if (this._win.getSelection().rangeCount == 0) return [this.length(), this.length()]; // append to the end
  512. var sel = this._win.getSelection().getRangeAt(0);
  513. return [
  514. w3cstart(sel, rng),
  515. w3cend (sel, rng)
  516. ];
  517. }
  518. W3CRange.prototype._nativeGetText = function (rng){
  519. return String.prototype.slice.apply(this._el.textContent, this.bounds());
  520. // return rng.toString(); // this fails in IE11 since it insists on inserting \r's before \n's in Ranges. node.textContent works as expected
  521. };
  522. W3CRange.prototype._nativeSetText = function (text, rng){
  523. rng.deleteContents();
  524. rng.insertNode (this._doc.createTextNode(text));
  525. if (canNormalize) this._el.normalize(); // merge the text with the surrounding text
  526. };
  527. W3CRange.prototype._nativeEOL = function(){
  528. var rng = this._nativeRange(this.bounds());
  529. rng.deleteContents();
  530. var br = this._doc.createElement('br');
  531. br.setAttribute ('_moz_dirty', ''); // for Firefox
  532. rng.insertNode (br);
  533. rng.insertNode (this._doc.createTextNode('\n'));
  534. rng.collapse (false);
  535. };
  536. W3CRange.prototype._nativeTop = function(rng){
  537. if (this.length == 0) return 0; // no text, no scrolling
  538. if (rng.toString() == ''){
  539. var textnode = this._doc.createTextNode('X');
  540. rng.insertNode (textnode);
  541. }
  542. var startrng = this._nativeRange([0,1]);
  543. var top = rng.getBoundingClientRect().top - startrng.getBoundingClientRect().top;
  544. if (textnode) textnode.parentNode.removeChild(textnode);
  545. return top;
  546. }
  547. W3CRange.prototype._nativeWrap = function(n, rng) {
  548. rng.surroundContents(n);
  549. };
  550. // W3C internals
  551. function nextnode (node, root){
  552. // in-order traversal
  553. // we've already visited node, so get kids then siblings
  554. if (node.firstChild) return node.firstChild;
  555. if (node.nextSibling) return node.nextSibling;
  556. if (node===root) return null;
  557. while (node.parentNode){
  558. // get uncles
  559. node = node.parentNode;
  560. if (node == root) return null;
  561. if (node.nextSibling) return node.nextSibling;
  562. }
  563. return null;
  564. }
  565. function w3cmoveBoundary (rng, n, bStart, el){
  566. // move the boundary (bStart == true ? start : end) n characters forward, up to the end of element el. Forward only!
  567. // if the start is moved after the end, then an exception is raised
  568. if (n <= 0) return;
  569. var node = rng[bStart ? 'startContainer' : 'endContainer'];
  570. if (node.nodeType == 3){
  571. // we may be starting somewhere into the text
  572. n += rng[bStart ? 'startOffset' : 'endOffset'];
  573. }
  574. while (node){
  575. if (node.nodeType == 3){
  576. var length = node.nodeValue.length;
  577. if (n <= length){
  578. rng[bStart ? 'setStart' : 'setEnd'](node, n);
  579. // special case: if we end next to a <br>, include that node.
  580. if (n == length){
  581. // skip past zero-length text nodes
  582. for (var next = nextnode (node, el); next && next.nodeType==3 && next.nodeValue.length == 0; next = nextnode(next, el)){
  583. rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
  584. }
  585. if (next && next.nodeType == 1 && next.nodeName == "BR") rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
  586. }
  587. return;
  588. }else{
  589. rng[bStart ? 'setStartAfter' : 'setEndAfter'](node); // skip past this one
  590. n -= length; // and eat these characters
  591. }
  592. }
  593. node = nextnode (node, el);
  594. }
  595. }
  596. var START_TO_START = 0; // from the w3c definitions
  597. var START_TO_END = 1;
  598. var END_TO_END = 2;
  599. var END_TO_START = 3;
  600. // from the Mozilla documentation, for range.compareBoundaryPoints(how, sourceRange)
  601. // -1, 0, or 1, indicating whether the corresponding boundary-point of range is respectively before, equal to, or after the corresponding boundary-point of sourceRange.
  602. // * Range.END_TO_END compares the end boundary-point of sourceRange to the end boundary-point of range.
  603. // * Range.END_TO_START compares the end boundary-point of sourceRange to the start boundary-point of range.
  604. // * Range.START_TO_END compares the start boundary-point of sourceRange to the end boundary-point of range.
  605. // * Range.START_TO_START compares the start boundary-point of sourceRange to the start boundary-point of range.
  606. function w3cstart(rng, constraint){
  607. if (rng.compareBoundaryPoints (START_TO_START, constraint) <= 0) return 0; // at or before the beginning
  608. if (rng.compareBoundaryPoints (END_TO_START, constraint) >= 0) return constraint.toString().length;
  609. rng = rng.cloneRange(); // don't change the original
  610. rng.setEnd (constraint.endContainer, constraint.endOffset); // they now end at the same place
  611. return constraint.toString().replace(/\r/g, '').length - rng.toString().replace(/\r/g, '').length;
  612. }
  613. function w3cend (rng, constraint){
  614. if (rng.compareBoundaryPoints (END_TO_END, constraint) >= 0) return constraint.toString().length; // at or after the end
  615. if (rng.compareBoundaryPoints (START_TO_END, constraint) <= 0) return 0;
  616. rng = rng.cloneRange(); // don't change the original
  617. rng.setStart (constraint.startContainer, constraint.startOffset); // they now start at the same place
  618. return rng.toString().replace(/\r/g, '').length;
  619. }
  620. function NothingRange(){}
  621. NothingRange.prototype = new Range();
  622. NothingRange.prototype._nativeRange = function(bounds) {
  623. return bounds || [0,this.length()];
  624. };
  625. NothingRange.prototype._nativeSelect = function (rng){ // do nothing
  626. };
  627. NothingRange.prototype._nativeSelection = function(){
  628. return [0,0];
  629. };
  630. NothingRange.prototype._nativeGetText = function (rng){
  631. return this._el[this._textProp].substring(rng[0], rng[1]);
  632. };
  633. NothingRange.prototype._nativeSetText = function (text, rng){
  634. var val = this._el[this._textProp];
  635. this._el[this._textProp] = val.substring(0, rng[0]) + text + val.substring(rng[1]);
  636. };
  637. NothingRange.prototype._nativeEOL = function(){
  638. this.text('\n');
  639. };
  640. NothingRange.prototype._nativeTop = function(){
  641. return 0;
  642. };
  643. NothingRange.prototype._nativeWrap = function() {throw new Error("Wrapping not implemented")};
  644. // data for elements, similar to jQuery data, but allows for monitoring with custom events
  645. var data = []; // to avoid attaching javascript objects to DOM elements, to avoid memory leaks
  646. bililiteRange.fn.data = function(){
  647. var index = this.element().bililiteRangeData;
  648. if (index == undefined){
  649. index = this.element().bililiteRangeData = data.length;
  650. data[index] = new Data(this);
  651. }
  652. return data[index];
  653. }
  654. try {
  655. Object.defineProperty({},'foo',{}); // IE8 will throw an error
  656. var Data = function(rng) {
  657. // we use JSON.stringify to display the data values. To make some of those non-enumerable, we have to use properties
  658. Object.defineProperty(this, 'values', {
  659. value: {}
  660. });
  661. Object.defineProperty(this, 'sourceRange', {
  662. value: rng
  663. });
  664. Object.defineProperty(this, 'toJSON', {
  665. value: function(){
  666. var ret = {};
  667. for (var i in Data.prototype) if (i in this.values) ret[i] = this.values[i];
  668. return ret;
  669. }
  670. });
  671. // to display all the properties (not just those changed), use JSON.stringify(state.all)
  672. Object.defineProperty(this, 'all', {
  673. get: function(){
  674. var ret = {};
  675. for (var i in Data.prototype) ret[i] = this[i];
  676. return ret;
  677. }
  678. });
  679. }
  680. Data.prototype = {};
  681. Object.defineProperty(Data.prototype, 'values', {
  682. value: {}
  683. });
  684. Object.defineProperty(Data.prototype, 'monitored', {
  685. value: {}
  686. });
  687. bililiteRange.data = function (name, newdesc){
  688. newdesc = newdesc || {};
  689. var desc = Object.getOwnPropertyDescriptor(Data.prototype, name) || {};
  690. if ('enumerable' in newdesc) desc.enumerable = !!newdesc.enumerable;
  691. if (!('enumerable' in desc)) desc.enumerable = true; // default
  692. if ('value' in newdesc) Data.prototype.values[name] = newdesc.value;
  693. if ('monitored' in newdesc) Data.prototype.monitored[name] = newdesc.monitored;
  694. desc.configurable = true;
  695. desc.get = function (){
  696. if (name in this.values) return this.values[name];
  697. return Data.prototype.values[name];
  698. };
  699. desc.set = function (value){
  700. this.values[name] = value;
  701. if (Data.prototype.monitored[name]) this.sourceRange.dispatch({
  702. type: 'bililiteRangeData',
  703. bubbles: true,
  704. detail: {name: name, value: value}
  705. });
  706. }
  707. Object.defineProperty(Data.prototype, name, desc);
  708. }
  709. }catch(err){
  710. // if we can't set object property properties, just use old-fashioned properties
  711. Data = function(rng){ this.sourceRange = rng };
  712. Data.prototype = {};
  713. bililiteRange.data = function(name, newdesc){
  714. if ('value' in newdesc) Data.prototype[name] = newdesc.value;
  715. }
  716. }
  717. })();
  718. // Polyfill for forEach, per Mozilla documentation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill
  719. if (!Array.prototype.forEach)
  720. {
  721. Array.prototype.forEach = function(fun /*, thisArg */)
  722. {
  723. "use strict";
  724. if (this === void 0 || this === null)
  725. throw new TypeError();
  726. var t = Object(this);
  727. var len = t.length >>> 0;
  728. if (typeof fun !== "function")
  729. throw new TypeError();
  730. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  731. for (var i = 0; i < len; i++)
  732. {
  733. if (i in t)
  734. fun.call(thisArg, t[i], i, t);
  735. }
  736. };
  737. }