textarea.js 12 KB

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