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