jquery.textarea.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /*
  2. * Tabby jQuery plugin version 0.12
  3. *
  4. * Ted Devito - http://teddevito.com/demos/textarea.html
  5. *
  6. * Copyright (c) 2009 Ted Devito
  7. *
  8. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
  9. * conditions are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
  13. * in the documentation and/or other materials provided with the distribution.
  14. * 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written
  15. * permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
  19. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  20. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  22. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. *
  24. */
  25. // create closure
  26. (function($) {
  27. // plugin definition
  28. $.fn.tabby = function(options) {
  29. //debug(this);
  30. // build main options before element iteration
  31. var opts = $.extend({}, $.fn.tabby.defaults, options);
  32. var pressed = $.fn.tabby.pressed;
  33. // iterate and reformat each matched element
  34. return this.each(function() {
  35. $this = $(this);
  36. // build element specific options
  37. var options = $.meta ? $.extend({}, opts, $this.data()) : opts;
  38. $this.bind('keydown',function (e) {
  39. var kc = $.fn.tabby.catch_kc(e);
  40. if (16 == kc) pressed.shft = true;
  41. /*
  42. because both CTRL+TAB and ALT+TAB default to an event (changing tab/window) that
  43. will prevent js from capturing the keyup event, we'll set a timer on releasing them.
  44. */
  45. if (17 == kc) {pressed.ctrl = true; setTimeout(function(){$.fn.tabby.pressed.ctrl = false;},1000);}
  46. if (18 == kc) {pressed.alt = true; setTimeout(function(){$.fn.tabby.pressed.alt = false;},1000);}
  47. if (9 == kc && !pressed.ctrl && !pressed.alt) {
  48. e.preventDefault; // does not work in O9.63 ??
  49. pressed.last = kc; setTimeout(function(){$.fn.tabby.pressed.last = null;},0);
  50. process_keypress ($(e.target).get(0), pressed.shft, options);
  51. return false;
  52. }
  53. }).bind('keyup',function (e) {
  54. if (16 == $.fn.tabby.catch_kc(e)) pressed.shft = false;
  55. }).bind('blur',function (e) { // workaround for Opera -- http://www.webdeveloper.com/forum/showthread.php?p=806588
  56. if (9 == pressed.last) $(e.target).one('focus',function (e) {pressed.last = null;}).get(0).focus();
  57. });
  58. });
  59. };
  60. // define and expose any extra methods
  61. $.fn.tabby.catch_kc = function(e) { return e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which; };
  62. $.fn.tabby.pressed = {shft : false, ctrl : false, alt : false, last: null};
  63. // private function for debugging
  64. function debug($obj) {
  65. if (window.console && window.console.log)
  66. window.console.log('textarea count: ' + $obj.size());
  67. };
  68. function process_keypress (o,shft,options) {
  69. var scrollTo = o.scrollTop;
  70. //var tabString = String.fromCharCode(9);
  71. // gecko; o.setSelectionRange is only available when the text box has focus
  72. if (o.setSelectionRange) gecko_tab (o, shft, options);
  73. // ie; document.selection is always available
  74. else if (document.selection) ie_tab (o, shft, options);
  75. o.scrollTop = scrollTo;
  76. }
  77. // plugin defaults
  78. $.fn.tabby.defaults = {tabString : String.fromCharCode(9)};
  79. function gecko_tab (o, shft, options) {
  80. var ss = o.selectionStart;
  81. var es = o.selectionEnd;
  82. // when there's no selection and we're just working with the caret, we'll add/remove the tabs at the caret, providing more control
  83. if(ss == es) {
  84. // SHIFT+TAB
  85. if (shft) {
  86. // check to the left of the caret first
  87. if (ss-options.tabString == o.value.substring(ss-options.tabString.length, ss)) {
  88. o.value = o.value.substring(0, ss-options.tabString.length) + o.value.substring(ss); // put it back together omitting one character to the left
  89. o.focus();
  90. o.setSelectionRange(ss - options.tabString.length, ss - options.tabString.length);
  91. }
  92. // then check to the right of the caret
  93. else if (ss-options.tabString == o.value.substring(ss, ss + options.tabString.length)) {
  94. o.value = o.value.substring(0, ss) + o.value.substring(ss + options.tabString.length); // put it back together omitting one character to the right
  95. o.focus();
  96. o.setSelectionRange(ss,ss);
  97. }
  98. }
  99. // TAB
  100. else {
  101. o.value = o.value.substring(0, ss) + options.tabString + o.value.substring(ss);
  102. o.focus();
  103. o.setSelectionRange(ss + options.tabString.length, ss + options.tabString.length);
  104. }
  105. }
  106. // selections will always add/remove tabs from the start of the line
  107. else {
  108. while (ss < o.value.length && o.value.charAt(ss).match(/[ \t]/)) ss++;
  109. // split the textarea up into lines and figure out which lines are included in the selection
  110. var lines = o.value.split("\n");
  111. var indices = new Array();
  112. var sl = 0; // start of the line
  113. var el = 0; // end of the line
  114. var sel = false;
  115. for (var i in lines) {
  116. el = sl + lines[i].length;
  117. indices.push({start: sl, end: el, selected: (sl <= ss && el > ss) || (el >= es && sl < es) || (sl > ss && el < es)});
  118. sl = el + 1;// for "\n"
  119. }
  120. // walk through the array of lines (indices) and add tabs where appropriate
  121. var modifier = 0;
  122. for (var i in indices) {
  123. if (indices[i].selected) {
  124. var pos = indices[i].start + modifier; // adjust for tabs already inserted/removed
  125. // SHIFT+TAB
  126. if (shft && options.tabString == o.value.substring(pos,pos+options.tabString.length)) { // only SHIFT+TAB if there's a tab at the start of the line
  127. o.value = o.value.substring(0,pos) + o.value.substring(pos + options.tabString.length); // omit the tabstring to the right
  128. modifier -= options.tabString.length;
  129. }
  130. // TAB
  131. else if (!shft) {
  132. o.value = o.value.substring(0,pos) + options.tabString + o.value.substring(pos); // insert the tabstring
  133. modifier += options.tabString.length;
  134. }
  135. }
  136. }
  137. o.focus();
  138. var ns = ss + ((modifier > 0) ? options.tabString.length : (modifier < 0) ? -options.tabString.length : 0);
  139. var ne = es + modifier;
  140. o.setSelectionRange(ns,ne);
  141. }
  142. }
  143. function ie_tab (o, shft, options) {
  144. var range = document.selection.createRange();
  145. if (o == range.parentElement()) {
  146. // when there's no selection and we're just working with the caret, we'll add/remove the tabs at the caret, providing more control
  147. if ('' == range.text) {
  148. // SHIFT+TAB
  149. if (shft) {
  150. var bookmark = range.getBookmark();
  151. //first try to the left by moving opening up our empty range to the left
  152. range.moveStart('character', -options.tabString.length);
  153. if (options.tabString == range.text) {
  154. range.text = '';
  155. } else {
  156. // if that didn't work then reset the range and try opening it to the right
  157. range.moveToBookmark(bookmark);
  158. range.moveEnd('character', options.tabString.length);
  159. if (options.tabString == range.text)
  160. range.text = '';
  161. }
  162. // move the pointer to the start of them empty range and select it
  163. range.collapse(true);
  164. range.select();
  165. }
  166. else {
  167. // very simple here. just insert the tab into the range and put the pointer at the end
  168. range.text = options.tabString;
  169. range.collapse(false);
  170. range.select();
  171. }
  172. }
  173. // selections will always add/remove tabs from the start of the line
  174. else {
  175. var selection_text = range.text;
  176. var selection_len = selection_text.length;
  177. var selection_arr = selection_text.split("\r\n");
  178. var before_range = document.body.createTextRange();
  179. before_range.moveToElementText(o);
  180. before_range.setEndPoint("EndToStart", range);
  181. var before_text = before_range.text;
  182. var before_arr = before_text.split("\r\n");
  183. var before_len = before_text.length; // - before_arr.length + 1;
  184. var after_range = document.body.createTextRange();
  185. after_range.moveToElementText(o);
  186. after_range.setEndPoint("StartToEnd", range);
  187. var after_text = after_range.text; // we can accurately calculate distance to the end because we're not worried about MSIE trimming a \r\n
  188. var end_range = document.body.createTextRange();
  189. end_range.moveToElementText(o);
  190. end_range.setEndPoint("StartToEnd", before_range);
  191. var end_text = end_range.text; // we can accurately calculate distance to the end because we're not worried about MSIE trimming a \r\n
  192. var check_html = $(o).html();
  193. $("#r3").text(before_len + " + " + selection_len + " + " + after_text.length + " = " + check_html.length);
  194. if((before_len + end_text.length) < check_html.length) {
  195. before_arr.push("");
  196. before_len += 2; // for the \r\n that was trimmed
  197. if (shft && options.tabString == selection_arr[0].substring(0,options.tabString.length))
  198. selection_arr[0] = selection_arr[0].substring(options.tabString.length);
  199. else if (!shft) selection_arr[0] = options.tabString + selection_arr[0];
  200. } else {
  201. if (shft && options.tabString == before_arr[before_arr.length-1].substring(0,options.tabString.length))
  202. before_arr[before_arr.length-1] = before_arr[before_arr.length-1].substring(options.tabString.length);
  203. else if (!shft) before_arr[before_arr.length-1] = options.tabString + before_arr[before_arr.length-1];
  204. }
  205. for (var i = 1; i < selection_arr.length; i++) {
  206. if (shft && options.tabString == selection_arr[i].substring(0,options.tabString.length))
  207. selection_arr[i] = selection_arr[i].substring(options.tabString.length);
  208. else if (!shft) selection_arr[i] = options.tabString + selection_arr[i];
  209. }
  210. if (1 == before_arr.length && 0 == before_len) {
  211. if (shft && options.tabString == selection_arr[0].substring(0,options.tabString.length))
  212. selection_arr[0] = selection_arr[0].substring(options.tabString.length);
  213. else if (!shft) selection_arr[0] = options.tabString + selection_arr[0];
  214. }
  215. if ((before_len + selection_len + after_text.length) < check_html.length) {
  216. selection_arr.push("");
  217. selection_len += 2; // for the \r\n that was trimmed
  218. }
  219. before_range.text = before_arr.join("\r\n");
  220. range.text = selection_arr.join("\r\n");
  221. var new_range = document.body.createTextRange();
  222. new_range.moveToElementText(o);
  223. if (0 < before_len) new_range.setEndPoint("StartToEnd", before_range);
  224. else new_range.setEndPoint("StartToStart", before_range);
  225. new_range.setEndPoint("EndToEnd", range);
  226. new_range.select();
  227. }
  228. }
  229. }
  230. // end of closure
  231. })(jQuery);