textarea.js 12 KB

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