textarea.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. (function($) {
  2. var blurredEle, theStartKey;
  3. var ulNode=document.createElement('ul');
  4. $(ulNode).addClass("dropDown").addClass("account_list")
  5. .attr('id','autoCompleteDropDown');
  6. function getCaretPosition(domElement) {
  7. var iCaretPos = 0;
  8. if(document.selection) {
  9. domElement.focus();
  10. var oSel = document.selection.createRange();
  11. oSel.moveStart('character', -domElement.value.length);
  12. iCaretPos = oSel.text.length;
  13. }
  14. else if(domElement.selectionStart || domElement.selectionStart === '0') {
  15. iCaretPos = domElement.selectionStart;
  16. }
  17. return iCaretPos;
  18. }
  19. function setCaretPosition(domElement, pos) {
  20. if(domElement.setSelectionRange) {
  21. domElement.focus();
  22. domElement.setSelectionRange(pos, pos);
  23. }
  24. else if(domElement.createTextRange) {
  25. var range = domElement.createTextRange();
  26. range.collapse(true);
  27. range.moveEnd('character', pos);
  28. range.moveStart('character', pos);
  29. range.select();
  30. }
  31. }
  32. function getLastestPositionOfStartKey(ele, startKey) {
  33. return ele.value.slice(0, getCaretPosition(ele)).lastIndexOf(startKey);
  34. }
  35. function extractNewInputs(node, startKey) {
  36. if(getLastestPositionOfStartKey(node, startKey) >= 0) {
  37. return node.value.slice(getLastestPositionOfStartKey(node, startKey), getCaretPosition(node));
  38. }
  39. return '';
  40. }
  41. function filterData(originData,resultName,matchedInputs) {
  42. return !!matchedInputs && originData.filter(function(data) {
  43. return data.name.slice(0,matchedInputs.length-1).toLowerCase() === matchedInputs.substr(1).toLowerCase();
  44. });
  45. }
  46. function fillDropDown(node,data,resultname,prepend,instance,callback) {
  47. getDropDown().data("instance",instance);
  48. getDropDown().find('li').remove();
  49. data = data.slice(0,5);
  50. data &&
  51. data.forEach(function(ele) {
  52. if(ele) {
  53. var liNode = document.createElement('li');
  54. $(liNode).hover(function() {
  55. $(this).parent().find('li.hoverLi').removeClass('hoverLi');
  56. $(this).addClass("hoverLi");
  57. },function() {
  58. $(this).removeClass("hoverLi");
  59. }).click(function() {
  60. blurredEle && addToken(blurredEle,prepend,callback);
  61. blurredEle = null;
  62. getDropDown().removeClass('showDropDown').addClass('hideDropDown');
  63. });
  64. if(resultname) {
  65. if(resultname == "acct") {
  66. $(liNode).data("value",prepend+ele[resultname]+" ");
  67. $(liNode).addClass("account_box").append($("<div>").addClass("icon_box").append($("<img>").attr("src",ele.avatar).css("float","left")))
  68. .append($("<div>").addClass("label_box").append($("<span>").addClass("dn").append($("<h3>").html(ele.display_name).addClass("emoji_poss"))).append($("<span>").addClass("un").html(prepend+ele.acct)));
  69. }
  70. else {
  71. $(liNode).data("value",prepend+ele[resultname]+": ");
  72. if(ele.value) {
  73. $(liNode).addClass("account_box").append($("<div>").addClass("icon_box").append($("<span>").addClass("emoji_poss").html(ele.value).css("float","left").css("font-size","32px")))
  74. .append($("<div>").addClass("label_box").append($("<span>").addClass("dn").append($("<h3>").html(ele.name))));
  75. }
  76. else {
  77. $(liNode).addClass("account_box").append($("<div>").addClass("icon_box").append($("<img>").attr("src",ele.url).css("float","left")))
  78. .append($("<div>").addClass("label_box").append($("<span>").addClass("dn").append($("<h3>").html(ele.name))));
  79. }
  80. }
  81. }
  82. else {
  83. $(liNode).data("value",prepend+ele+" ");
  84. $(liNode).addClass("account_box").append($("<div>").addClass("icon_box").append($("<span>").addClass("emoji_poss").html("#️⃣").css("float","left").css("font-size","32px")))
  85. .append($("<div>").addClass("label_box").append($("<span>").addClass("dn").append($("<h3>").html(prepend+ele))));
  86. }
  87. node.append(liNode);
  88. }
  89. });
  90. replace_emoji();
  91. }
  92. function getDropDown() {
  93. return $("#autoCompleteDropDown");
  94. }
  95. function belongsTo(instance) {
  96. if(getDropDown().data("instance") == instance) return true;
  97. else return false;
  98. }
  99. function getHoveredLi() {
  100. return getDropDown().find('li.hoverLi');
  101. }
  102. function addToken(node,startKey,callback) {
  103. var token = getHoveredLi().data("value");
  104. var inputsUtilCaret = node.value
  105. .slice(0, getLastestPositionOfStartKey(node,startKey))
  106. .concat(token);
  107. node.value = inputsUtilCaret
  108. .concat(node.value.slice(getCaretPosition(node)));
  109. setCaretPosition(node, inputsUtilCaret.length);
  110. getDropdownRemoved();
  111. if(callback && typeof callback == "function") {
  112. callback();
  113. }
  114. }
  115. function hasDropDown() {
  116. return getDropDown().length;
  117. }
  118. function hasHoveredList() {
  119. return getHoveredLi().length;
  120. }
  121. function getDropdownRemoved() {
  122. if(hasDropDown()) {
  123. setTimeout(function() {getDropDown().remove()},0);
  124. }
  125. }
  126. function figureKeycodeOption(e,instance) {
  127. if((e.keyCode === 38 || e.keyCode === 40 || e.keyCode === 13) && hasDropDown() && getDropDown().css('opacity') === '1') {
  128. // 38: arrowUp; 40: arrowDown; 13: Enter;
  129. e.preventDefault();
  130. }
  131. switch(e.keyCode) {
  132. case 38:
  133. if(hasHoveredList() && belongsTo(instance)) {
  134. var preLi = getHoveredLi().removeClass('hoverLi').prev();
  135. preLi ? preLi.addClass('hoverLi') : getDropDown().last().addClass('hoverLi');
  136. }
  137. else if(hasDropDown() && !hasHoveredList() && belongsTo(instance)) {
  138. getDropDown().children().last().addClass('hoverLi');
  139. }
  140. break;
  141. case 40:
  142. if(hasHoveredList() && belongsTo(instance)) {
  143. var nextLi = getHoveredLi().removeClass('hoverLi').next();
  144. nextLi ? nextLi.addClass('hoverLi') : getDropDown().first().addClass('hoverLi');
  145. }
  146. else if(hasDropDown() && !hasHoveredList() && belongsTo(instance)) {
  147. getDropDown().children().first().addClass('hoverLi');
  148. }
  149. break;
  150. default:
  151. break;
  152. }
  153. }
  154. function filterSourceData(e,node,config) {
  155. var startKey = config.startkey;
  156. var endKey = config.endkey;
  157. if((e.keyCode === 38 || e.keyCode === 40) && hasDropDown()&& getDropDown().css('opacity') === '1' || e.keyCode === 16) {
  158. //38: arrowUp; 40: arrowDown; 16: shift;
  159. e.preventDefault();
  160. return;
  161. }
  162. else if(e.keyCode === 27 && hasDropDown() && getDropDown().css('opacity') === '1') {
  163. // 27: Esc;
  164. getDropdownRemoved();
  165. return;
  166. }
  167. switch(e.keyCode){
  168. case 13:
  169. if(hasHoveredList() && belongsTo(config.instance)) {
  170. addToken(node,startKey,config.callback);
  171. }
  172. return;
  173. default:
  174. break;
  175. }
  176. if(node.value.slice(getCaretPosition(node)-1, getCaretPosition(node)) === endKey){
  177. getDropdownRemoved();
  178. return;
  179. }
  180. if(extractNewInputs(node,startKey).length > 1 && extractNewInputs(node,startKey).indexOf(endKey) == -1) {
  181. if(config.arrayname) {
  182. api.get("search?q="+encodeURIComponent(extractNewInputs(node,startKey))+"&resolve=false&limit=5",function(matchedData) {
  183. matchedData = matchedData[config.arrayname];
  184. if(matchedData.length) {
  185. if(hasDropDown()){
  186. getDropDown().find('li').remove();
  187. }
  188. else {
  189. $(ulNode).insertAfter(node);
  190. }
  191. fillDropDown(getDropDown(),matchedData,config.resultname,config.startkey,config.instance,config.callback);
  192. getDropDown().removeClass('hideDropDown').addClass('showDropDown');
  193. }
  194. else {
  195. getDropdownRemoved();
  196. }
  197. if(hasDropDown()){
  198. var pos = $(node).getCaretPixelPosition();
  199. getDropDown().css({
  200. 'left': node.offsetLeft + pos.left,
  201. 'top': node.offsetTop + pos.top
  202. });
  203. }
  204. });
  205. }
  206. else {
  207. var matchedData = filterData(config.source,config.resultname,extractNewInputs(node,startKey));
  208. if(matchedData.length) {
  209. if(hasDropDown()){
  210. getDropDown().find('li').remove();
  211. }
  212. else {
  213. $(ulNode).insertAfter(node);
  214. }
  215. fillDropDown(getDropDown(),matchedData,config.resultname,config.startkey,config.instance,config.callback);
  216. getDropDown().removeClass('hideDropDown').addClass('showDropDown');
  217. }
  218. else {
  219. getDropdownRemoved();
  220. }
  221. if(hasDropDown()){
  222. var pos = $(node).getCaretPixelPosition();
  223. getDropDown().css({
  224. 'left': node.offsetLeft + pos.left,
  225. 'top': node.offsetTop + pos.top
  226. });
  227. }
  228. }
  229. }
  230. }
  231. $.fn.autoCompleteToken = function(config) {
  232. if(config == "destroy") {
  233. this.off("keydown");
  234. this.off("keyup");
  235. this.off("blur");
  236. }
  237. else {
  238. this.keydown(function(e) {
  239. figureKeycodeOption(e,config.instance);
  240. });
  241. this.keyup(function(e) {
  242. filterSourceData(e,this,config);
  243. });
  244. this.blur(function() {
  245. blurredEle = this;
  246. theStartKey = config.startkey;
  247. });
  248. }
  249. }
  250. }(jQuery));
  251. $(document).click(function(e) {
  252. if(!$(e.target).closest('#autoCompleteDropDown').length) {
  253. $("#autoCompleteDropDown").removeClass('showDropDown').addClass('hideDropDown');
  254. }
  255. });
  256. (function($, window, document) {
  257. // @license under Apache license
  258. // * @author Bevis Zhao (i@bevis.me, http://bevis.me)
  259. $(function() {
  260. var calculator = {
  261. primaryStyles: ['fontFamily', 'fontSize', 'fontWeight', 'fontVariant', 'fontStyle',
  262. 'paddingLeft', 'paddingTop', 'paddingBottom', 'paddingRight',
  263. 'marginLeft', 'marginTop', 'marginBottom', 'marginRight',
  264. 'borderLeftColor', 'borderTopColor', 'borderBottomColor', 'borderRightColor',
  265. 'borderLeftStyle', 'borderTopStyle', 'borderBottomStyle', 'borderRightStyle',
  266. 'borderLeftWidth', 'borderTopWidth', 'borderBottomWidth', 'borderRightWidth',
  267. 'line-height', 'outline'],
  268. specificStyle: {
  269. 'word-wrap': 'break-word',
  270. 'overflow-x': 'hidden',
  271. 'overflow-y': 'auto'
  272. },
  273. simulator: $('<div id="textarea_simulator" contenteditable="true"/>').css({
  274. position: 'absolute',
  275. top: 0,
  276. left: 0,
  277. visibility: 'hidden'
  278. }).appendTo(document.body),
  279. toHtml : function(text) {
  280. return text.replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g, '<br>')
  281. .replace(/(\s)/g,'<span style="white-space:pre-wrap;">$1</span>');
  282. },
  283. getCaretPixelPosition:function() {
  284. var cal = calculator, self = this, element = self[0], elementOffset = self.offset();
  285. cal.simulator.empty();
  286. $.each(cal.primaryStyles, function(index, styleName) {
  287. self.cloneStyle(cal.simulator, styleName);
  288. });
  289. cal.simulator.css($.extend({
  290. 'width': self.width(),
  291. 'height': self.height()
  292. },cal.specificStyle));
  293. var value = self.val(), cursorPosition = self.getCursorPosition();
  294. var beforeText = value.substring(0, cursorPosition),
  295. afterText = value.substring(cursorPosition);
  296. var before = $('<span class="before"/>').html(cal.toHtml(beforeText)),
  297. focus = $('<span class="focus"/>'),
  298. after = $('<span class="after"/>').html(cal.toHtml(afterText));
  299. cal.simulator.append(before).append(focus).append(after);
  300. var focusOffset = focus.offset(), simulatorOffset = cal.simulator.offset();
  301. // alert(focusOffset.left+ ',' +simulatorOffset.left + ',' + element.scrollLeft);
  302. return {
  303. top: focusOffset.top - simulatorOffset.top - element.scrollTop
  304. + (navigator.userAgent.indexOf("Firefox") != -1 ? 0 : parseInt(self.getComputedStyle("fontSize"))),
  305. left: focus[0].offsetLeft -cal.simulator[0].offsetLeft - element.scrollLeft
  306. };
  307. }
  308. };
  309. $.fn.extend({
  310. getComputedStyle:function(styleName) {
  311. if(this.length == 0) return;
  312. var thiz = this[0];
  313. var result = this.css(styleName);
  314. result = result || ($.browser.msie ?
  315. thiz.currentStyle[styleName]:
  316. document.defaultView.getComputedStyle(thiz, null)[styleName]);
  317. return result;
  318. },
  319. cloneStyle:function(target, styleName) {
  320. var styleVal = this.getComputedStyle(styleName);
  321. if (!!styleVal) {
  322. $(target).css(styleName, styleVal);
  323. }
  324. },
  325. cloneAllStyle:function(target, style) {
  326. var thiz = this[0];
  327. for (var styleName in thiz.style) {
  328. var val = thiz.style[styleName];
  329. typeof val == 'string' || typeof val == 'number'
  330. ? this.cloneStyle(target, styleName)
  331. : NaN;
  332. }
  333. },
  334. getCursorPosition:function() {
  335. var thiz = this[0], result = 0;
  336. if('selectionStart' in thiz) {
  337. result = thiz.selectionStart;
  338. }
  339. else if('selection' in document) {
  340. var range = document.selection.createRange();
  341. if(parseInt($.browser.version) > 6) {
  342. thiz.focus();
  343. var length = document.selection.createRange().text.length;
  344. range.moveStart('character', - thiz.value.length);
  345. result = range.text.length - length;
  346. }
  347. else {
  348. var bodyRange = document.body.createTextRange();
  349. bodyRange.moveToElementText(thiz);
  350. for(; bodyRange.compareEndPoints("StartToStart", range) < 0; result++)
  351. bodyRange.moveStart('character', 1);
  352. for(var i = 0; i <= result; i ++){
  353. if (thiz.value.charAt(i) == '\n')
  354. result++;
  355. }
  356. var enterCount = thiz.value.split('\n').length - 1;
  357. result -= enterCount;
  358. return result;
  359. }
  360. }
  361. return result;
  362. },
  363. getCaretPixelPosition: calculator.getCaretPixelPosition
  364. });
  365. });
  366. })(jQuery, window, document);