bililiteRange.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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: 1.5
  4. // Copyright (c) 2010 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. bililiteRange = function(el, debug){
  26. var ret;
  27. if (debug){
  28. ret = new NothingRange(); // Easier to force it to use the no-selection type than to try to find an old browser
  29. }else if (document.selection){
  30. // Internet Explorer
  31. ret = new IERange();
  32. }else if (window.getSelection && el.setSelectionRange){
  33. // Standards. Element is an input or textarea
  34. ret = new InputRange();
  35. }else if (window.getSelection){
  36. // Standards, with any other kind of element
  37. ret = new W3CRange()
  38. }else{
  39. // doesn't support selection
  40. ret = new NothingRange();
  41. }
  42. ret._el = el;
  43. // determine parent document, as implemented by John McLear <john@mclear.co.uk>
  44. ret._doc = el.ownerDocument;
  45. ret._win = 'defaultView' in ret._doc ? ret._doc.defaultView : ret._doc.parentWindow;
  46. ret._textProp = textProp(el);
  47. ret._bounds = [0, ret.length()];
  48. return ret;
  49. }
  50. function textProp(el){
  51. // returns the property that contains the text of the element
  52. if (typeof el.value != 'undefined') return 'value';
  53. if (typeof el.text != 'undefined') return 'text';
  54. if (typeof el.textContent != 'undefined') return 'textContent';
  55. return 'innerText';
  56. }
  57. // base class
  58. function Range(){}
  59. Range.prototype = {
  60. length: function() {
  61. return this._el[this._textProp].replace(/\r/g, '').length; // need to correct for IE's CrLf weirdness
  62. },
  63. bounds: function(s){
  64. if (s === 'all'){
  65. this._bounds = [0, this.length()];
  66. }else if (s === 'start'){
  67. this._bounds = [0, 0];
  68. }else if (s === 'end'){
  69. this._bounds = [this.length(), this.length()];
  70. }else if (s === 'selection'){
  71. this.bounds ('all'); // first select the whole thing for constraining
  72. this._bounds = this._nativeSelection();
  73. }else if (s){
  74. this._bounds = s; // don't do error checking now; things may change at a moment's notice
  75. }else{
  76. var b = [
  77. Math.max(0, Math.min (this.length(), this._bounds[0])),
  78. Math.max(0, Math.min (this.length(), this._bounds[1]))
  79. ];
  80. b[1] = Math.max(b[0], b[1]);
  81. return b; // need to constrain it to fit
  82. }
  83. return this; // allow for chaining
  84. },
  85. select: function(){
  86. this._nativeSelect(this._nativeRange(this.bounds()));
  87. return this; // allow for chaining
  88. },
  89. text: function(text, select){
  90. if (arguments.length){
  91. this._nativeSetText(text, this._nativeRange(this.bounds()));
  92. try { // signal the text change (IE < 9 doesn't support this, so we live with it)
  93. this._el.dispatchEvent(new CustomEvent('input', {detail: {text: text, bounds: this.bounds()}}));
  94. }catch(e){ /* ignore */ }
  95. if (select == 'start'){
  96. this.bounds ([this._bounds[0], this._bounds[0]]);
  97. }else if (select == 'end'){
  98. this.bounds ([this._bounds[0]+text.length, this._bounds[0]+text.length]);
  99. }else if (select == 'all'){
  100. this.bounds ([this._bounds[0], this._bounds[0]+text.length]);
  101. }
  102. return this; // allow for chaining
  103. }else{
  104. return this._nativeGetText(this._nativeRange(this.bounds()));
  105. }
  106. },
  107. insertEOL: function (){
  108. this._nativeEOL();
  109. this._bounds = [this._bounds[0]+1, this._bounds[0]+1]; // move past the EOL marker
  110. return this;
  111. },
  112. scrollIntoView: function(){
  113. this._nativeScrollIntoView(this._nativeRange(this.bounds()));
  114. return this;
  115. }
  116. };
  117. // allow extensions ala jQuery
  118. bililiteRange.fn = Range.prototype; // to allow monkey patching
  119. bililiteRange.extend = function(fns){
  120. for (fn in fns) Range.prototype[fn] = fns[fn];
  121. };
  122. function IERange(){}
  123. IERange.prototype = new Range();
  124. IERange.prototype._nativeRange = function (bounds){
  125. var rng;
  126. if (this._el.tagName == 'INPUT'){
  127. // IE 8 is very inconsistent; textareas have createTextRange but it doesn't work
  128. rng = this._el.createTextRange();
  129. }else{
  130. rng = this._doc.body.createTextRange ();
  131. rng.moveToElementText(this._el);
  132. }
  133. if (bounds){
  134. if (bounds[1] < 0) bounds[1] = 0; // IE tends to run elements out of bounds
  135. if (bounds[0] > this.length()) bounds[0] = this.length();
  136. if (bounds[1] < rng.text.replace(/\r/g, '').length){ // correct for IE's CrLf wierdness
  137. // 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
  138. rng.moveEnd ('character', -1);
  139. rng.moveEnd ('character', bounds[1]-rng.text.replace(/\r/g, '').length);
  140. }
  141. if (bounds[0] > 0) rng.moveStart('character', bounds[0]);
  142. }
  143. return rng;
  144. };
  145. IERange.prototype._nativeSelect = function (rng){
  146. rng.select();
  147. };
  148. IERange.prototype._nativeSelection = function (){
  149. // returns [start, end] for the selection constrained to be in element
  150. var rng = this._nativeRange(); // range of the element to constrain to
  151. var len = this.length();
  152. if (this._doc.selection.type != 'Text') return [len, len]; // append to the end
  153. var sel = this._doc.selection.createRange();
  154. try{
  155. return [
  156. iestart(sel, rng),
  157. ieend (sel, rng)
  158. ];
  159. }catch (e){
  160. // IE gets upset sometimes about comparing text to input elements, but the selections cannot overlap, so make a best guess
  161. return (sel.parentElement().sourceIndex < this._el.sourceIndex) ? [0,0] : [len, len];
  162. }
  163. };
  164. IERange.prototype._nativeGetText = function (rng){
  165. return rng.text.replace(/\r/g, ''); // correct for IE's CrLf weirdness
  166. };
  167. IERange.prototype._nativeSetText = function (text, rng){
  168. rng.text = text;
  169. };
  170. IERange.prototype._nativeEOL = function(){
  171. if (typeof this._el.value != 'undefined'){
  172. this.text('\n'); // for input and textarea, insert it straight
  173. }else{
  174. this._nativeRange(this.bounds()).pasteHTML('<br/>');
  175. }
  176. };
  177. IERange.prototype._nativeScrollIntoView = function(rng){
  178. rng.scrollIntoView();
  179. }
  180. // IE internals
  181. function iestart(rng, constraint){
  182. // 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
  183. var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf wierdness
  184. if (rng.compareEndPoints ('StartToStart', constraint) <= 0) return 0; // at or before the beginning
  185. if (rng.compareEndPoints ('StartToEnd', constraint) >= 0) return len;
  186. for (var i = 0; rng.compareEndPoints ('StartToStart', constraint) > 0; ++i, rng.moveStart('character', -1));
  187. return i;
  188. }
  189. function ieend (rng, constraint){
  190. // 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
  191. var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf wierdness
  192. if (rng.compareEndPoints ('EndToEnd', constraint) >= 0) return len; // at or after the end
  193. if (rng.compareEndPoints ('EndToStart', constraint) <= 0) return 0;
  194. for (var i = 0; rng.compareEndPoints ('EndToStart', constraint) > 0; ++i, rng.moveEnd('character', -1));
  195. return i;
  196. }
  197. // an input element in a standards document. "Native Range" is just the bounds array
  198. function InputRange(){}
  199. InputRange.prototype = new Range();
  200. InputRange.prototype._nativeRange = function(bounds) {
  201. return bounds || [0, this.length()];
  202. };
  203. InputRange.prototype._nativeSelect = function (rng){
  204. this._el.setSelectionRange(rng[0], rng[1]);
  205. };
  206. InputRange.prototype._nativeSelection = function(){
  207. return [this._el.selectionStart, this._el.selectionEnd];
  208. };
  209. InputRange.prototype._nativeGetText = function(rng){
  210. return this._el.value.substring(rng[0], rng[1]);
  211. };
  212. InputRange.prototype._nativeSetText = function(text, rng){
  213. var val = this._el.value;
  214. this._el.value = val.substring(0, rng[0]) + text + val.substring(rng[1]);
  215. };
  216. InputRange.prototype._nativeEOL = function(){
  217. this.text('\n');
  218. };
  219. InputRange.prototype._nativeScrollIntoView = function(rng){
  220. // I can't remember where I found this clever hack to find the location of text in a text area
  221. var style = getComputedStyle(this._el);
  222. var oldheight = style.height;
  223. var oldval = this._el.value;
  224. var oldselection = this._nativeSelection();
  225. this._el.style.height = '1px';
  226. this._el.value = oldval.slice(0, rng[0]);
  227. var top = this._el.scrollHeight;
  228. // this gives the bottom of the text, so we have to subtract the height of a single line
  229. this._el.value = 'X';
  230. top -= 2*this._el.scrollHeight; // show at least a line above
  231. this._el.style.height = oldheight;
  232. this._el.value = oldval;
  233. this._nativeSelect(oldselection);
  234. // scroll into position if necessary
  235. if (this._el.scrollTop > top || this._el.scrollTop+this._el.clientHeight < top){
  236. this._el.scrollTop = top;
  237. }
  238. // now scroll the element into view; get its position as in jQuery.offset
  239. var rect = this._el.getBoundingClientRect();
  240. rect.top += this._win.pageYOffset - this._doc.documentElement.clientTop;
  241. rect.left += this._win.pageXOffset - this._doc.documentElement.clientLeft;
  242. // create an element to scroll to
  243. var div = this._doc.createElement('div');
  244. div.style.position = 'absolute';
  245. div.style.top = (rect.top+top-this._el.scrollTop)+'px'; // adjust for how far in the range is; it may not have scrolled all the way to the top
  246. div.style.left = rect.left+'px';
  247. div.innerHTML = '&nbsp;';
  248. this._doc.body.appendChild(div);
  249. div.scrollIntoViewIfNeeded ? div.scrollIntoViewIfNeeded() : div.scrollIntoView();
  250. div.parentNode.removeChild(div);
  251. }
  252. function W3CRange(){}
  253. W3CRange.prototype = new Range();
  254. W3CRange.prototype._nativeRange = function (bounds){
  255. var rng = this._doc.createRange();
  256. rng.selectNodeContents(this._el);
  257. if (bounds){
  258. w3cmoveBoundary (rng, bounds[0], true, this._el);
  259. rng.collapse (true);
  260. w3cmoveBoundary (rng, bounds[1]-bounds[0], false, this._el);
  261. }
  262. return rng;
  263. };
  264. W3CRange.prototype._nativeSelect = function (rng){
  265. this._win.getSelection().removeAllRanges();
  266. this._win.getSelection().addRange (rng);
  267. };
  268. W3CRange.prototype._nativeSelection = function (){
  269. // returns [start, end] for the selection constrained to be in element
  270. var rng = this._nativeRange(); // range of the element to constrain to
  271. if (this._win.getSelection().rangeCount == 0) return [this.length(), this.length()]; // append to the end
  272. var sel = this._win.getSelection().getRangeAt(0);
  273. return [
  274. w3cstart(sel, rng),
  275. w3cend (sel, rng)
  276. ];
  277. }
  278. W3CRange.prototype._nativeGetText = function (rng){
  279. return rng.toString();
  280. };
  281. W3CRange.prototype._nativeSetText = function (text, rng){
  282. rng.deleteContents();
  283. rng.insertNode (this._doc.createTextNode(text));
  284. this._el.normalize(); // merge the text with the surrounding text
  285. };
  286. W3CRange.prototype._nativeEOL = function(){
  287. var rng = this._nativeRange(this.bounds());
  288. rng.deleteContents();
  289. var br = this._doc.createElement('br');
  290. br.setAttribute ('_moz_dirty', ''); // for Firefox
  291. rng.insertNode (br);
  292. rng.insertNode (this._doc.createTextNode('\n'));
  293. rng.collapse (false);
  294. };
  295. W3CRange.prototype._nativeScrollIntoView = function(rng){
  296. // can't scroll to a range; have to scroll to an element instead
  297. var span = this._doc.createElement('span');
  298. rng.insertNode(span);
  299. span.scrollIntoViewIfNeeded ? span.scrollIntoViewIfNeeded() : span.scrollIntoView();
  300. span.parentNode.removeChild(span);
  301. }
  302. // W3C internals
  303. function nextnode (node, root){
  304. // in-order traversal
  305. // we've already visited node, so get kids then siblings
  306. if (node.firstChild) return node.firstChild;
  307. if (node.nextSibling) return node.nextSibling;
  308. if (node===root) return null;
  309. while (node.parentNode){
  310. // get uncles
  311. node = node.parentNode;
  312. if (node == root) return null;
  313. if (node.nextSibling) return node.nextSibling;
  314. }
  315. return null;
  316. }
  317. function w3cmoveBoundary (rng, n, bStart, el){
  318. // move the boundary (bStart == true ? start : end) n characters forward, up to the end of element el. Forward only!
  319. // if the start is moved after the end, then an exception is raised
  320. if (n <= 0) return;
  321. var node = rng[bStart ? 'startContainer' : 'endContainer'];
  322. if (node.nodeType == 3){
  323. // we may be starting somewhere into the text
  324. n += rng[bStart ? 'startOffset' : 'endOffset'];
  325. }
  326. while (node){
  327. if (node.nodeType == 3){
  328. if (n <= node.nodeValue.length){
  329. rng[bStart ? 'setStart' : 'setEnd'](node, n);
  330. // special case: if we end next to a <br>, include that node.
  331. if (n == node.nodeValue.length){
  332. // skip past zero-length text nodes
  333. for (var next = nextnode (node, el); next && next.nodeType==3 && next.nodeValue.length == 0; next = nextnode(next, el)){
  334. rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
  335. }
  336. if (next && next.nodeType == 1 && next.nodeName == "BR") rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
  337. }
  338. return;
  339. }else{
  340. rng[bStart ? 'setStartAfter' : 'setEndAfter'](node); // skip past this one
  341. n -= node.nodeValue.length; // and eat these characters
  342. }
  343. }
  344. node = nextnode (node, el);
  345. }
  346. }
  347. var START_TO_START = 0; // from the w3c definitions
  348. var START_TO_END = 1;
  349. var END_TO_END = 2;
  350. var END_TO_START = 3;
  351. // from the Mozilla documentation, for range.compareBoundaryPoints(how, sourceRange)
  352. // -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.
  353. // * Range.END_TO_END compares the end boundary-point of sourceRange to the end boundary-point of range.
  354. // * Range.END_TO_START compares the end boundary-point of sourceRange to the start boundary-point of range.
  355. // * Range.START_TO_END compares the start boundary-point of sourceRange to the end boundary-point of range.
  356. // * Range.START_TO_START compares the start boundary-point of sourceRange to the start boundary-point of range.
  357. function w3cstart(rng, constraint){
  358. if (rng.compareBoundaryPoints (START_TO_START, constraint) <= 0) return 0; // at or before the beginning
  359. if (rng.compareBoundaryPoints (END_TO_START, constraint) >= 0) return constraint.toString().length;
  360. rng = rng.cloneRange(); // don't change the original
  361. rng.setEnd (constraint.endContainer, constraint.endOffset); // they now end at the same place
  362. return constraint.toString().length - rng.toString().length;
  363. }
  364. function w3cend (rng, constraint){
  365. if (rng.compareBoundaryPoints (END_TO_END, constraint) >= 0) return constraint.toString().length; // at or after the end
  366. if (rng.compareBoundaryPoints (START_TO_END, constraint) <= 0) return 0;
  367. rng = rng.cloneRange(); // don't change the original
  368. rng.setStart (constraint.startContainer, constraint.startOffset); // they now start at the same place
  369. return rng.toString().length;
  370. }
  371. function NothingRange(){}
  372. NothingRange.prototype = new Range();
  373. NothingRange.prototype._nativeRange = function(bounds) {
  374. return bounds || [0,this.length()];
  375. };
  376. NothingRange.prototype._nativeSelect = function (rng){ // do nothing
  377. };
  378. NothingRange.prototype._nativeSelection = function(){
  379. return [0,0];
  380. };
  381. NothingRange.prototype._nativeGetText = function (rng){
  382. return this._el[this._textProp].substring(rng[0], rng[1]);
  383. };
  384. NothingRange.prototype._nativeSetText = function (text, rng){
  385. var val = this._el[this._textProp];
  386. this._el[this._textProp] = val.substring(0, rng[0]) + text + val.substring(rng[1]);
  387. };
  388. NothingRange.prototype._nativeEOL = function(){
  389. this.text('\n');
  390. };
  391. NothingRange.prototype._nativeScrollIntoView = function(){
  392. this._el.scrollIntoView();
  393. };
  394. })();