jquery.emojiarea.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /**
  2. * emojiarea - A rich textarea control that supports emojis, WYSIWYG-style.
  3. * Copyright (c) 2012 DIY Co
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
  6. * file except in compliance with the License. You may obtain a copy of the License at:
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software distributed under
  10. * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. * ANY KIND, either express or implied. See the License for the specific language
  12. * governing permissions and limitations under the License.
  13. *
  14. * @author Brian Reavis <brian@diy.org>
  15. */
  16. (function($, window, document) {
  17. var ELEMENT_NODE = 1;
  18. var TEXT_NODE = 3;
  19. var TAGS_BLOCK = ['p', 'div', 'pre', 'form'];
  20. var KEY_ESC = 27;
  21. var KEY_TAB = 9;
  22. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  23. $.emojiarea = {
  24. path: '',
  25. icons: {},
  26. defaults: {
  27. button: null,
  28. buttonLabel: 'Emojis',
  29. buttonPosition: 'after'
  30. }
  31. };
  32. $.fn.emojiarea = function(options) {
  33. options = $.extend({}, $.emojiarea.defaults, options);
  34. return this.each(function() {
  35. var $textarea = $(this);
  36. if ('contentEditable' in document.body && options.wysiwyg !== false) {
  37. new EmojiArea_WYSIWYG($textarea, options);
  38. } else {
  39. new EmojiArea_Plain($textarea, options);
  40. }
  41. });
  42. };
  43. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  44. var util = {};
  45. util.restoreSelection = (function() {
  46. if (window.getSelection) {
  47. return function(savedSelection) {
  48. var sel = window.getSelection();
  49. sel.removeAllRanges();
  50. for (var i = 0, len = savedSelection.length; i < len; ++i) {
  51. sel.addRange(savedSelection[i]);
  52. }
  53. };
  54. } else if (document.selection && document.selection.createRange) {
  55. return function(savedSelection) {
  56. if (savedSelection) {
  57. savedSelection.select();
  58. }
  59. };
  60. }
  61. })();
  62. util.saveSelection = (function() {
  63. if (window.getSelection) {
  64. return function() {
  65. var sel = window.getSelection(), ranges = [];
  66. if (sel.rangeCount) {
  67. for (var i = 0, len = sel.rangeCount; i < len; ++i) {
  68. ranges.push(sel.getRangeAt(i));
  69. }
  70. }
  71. return ranges;
  72. };
  73. } else if (document.selection && document.selection.createRange) {
  74. return function() {
  75. var sel = document.selection;
  76. return (sel.type.toLowerCase() !== 'none') ? sel.createRange() : null;
  77. };
  78. }
  79. })();
  80. util.replaceSelection = (function() {
  81. if (window.getSelection) {
  82. return function(content) {
  83. var range, sel = window.getSelection();
  84. var node = typeof content === 'string' ? document.createTextNode(content) : content;
  85. if (sel.getRangeAt && sel.rangeCount) {
  86. range = sel.getRangeAt(0);
  87. range.deleteContents();
  88. range.insertNode(document.createTextNode(' '));
  89. range.insertNode(node);
  90. range.setStart(node, 0);
  91. window.setTimeout(function() {
  92. range = document.createRange();
  93. range.setStartAfter(node);
  94. range.collapse(true);
  95. sel.removeAllRanges();
  96. sel.addRange(range);
  97. }, 0);
  98. }
  99. }
  100. } else if (document.selection && document.selection.createRange) {
  101. return function(content) {
  102. var range = document.selection.createRange();
  103. if (typeof content === 'string') {
  104. range.text = content;
  105. } else {
  106. range.pasteHTML(content.outerHTML);
  107. }
  108. }
  109. }
  110. })();
  111. util.insertAtCursor = function(text, el) {
  112. text = ' ' + text;
  113. var val = el.value, endIndex, startIndex, range;
  114. if (typeof el.selectionStart != 'undefined' && typeof el.selectionEnd != 'undefined') {
  115. startIndex = el.selectionStart;
  116. endIndex = el.selectionEnd;
  117. el.value = val.substring(0, startIndex) + text + val.substring(el.selectionEnd);
  118. el.selectionStart = el.selectionEnd = startIndex + text.length;
  119. } else if (typeof document.selection != 'undefined' && typeof document.selection.createRange != 'undefined') {
  120. el.focus();
  121. range = document.selection.createRange();
  122. range.text = text;
  123. range.select();
  124. }
  125. };
  126. util.extend = function(a, b) {
  127. if (typeof a === 'undefined' || !a) { a = {}; }
  128. if (typeof b === 'object') {
  129. for (var key in b) {
  130. if (b.hasOwnProperty(key)) {
  131. a[key] = b[key];
  132. }
  133. }
  134. }
  135. return a;
  136. };
  137. util.escapeRegex = function(str) {
  138. return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
  139. };
  140. util.htmlEntities = function(str) {
  141. return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  142. };
  143. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  144. var EmojiArea = function() {};
  145. EmojiArea.prototype.setup = function() {
  146. var self = this;
  147. this.$editor.on('focus', function() { self.hasFocus = true; });
  148. this.$editor.on('blur', function() { self.hasFocus = false; });
  149. this.setupButton();
  150. };
  151. EmojiArea.prototype.setupButton = function() {
  152. var self = this;
  153. var $button;
  154. if (this.options.button) {
  155. $button = $(this.options.button);
  156. } else if (this.options.button !== false) {
  157. $button = $('<a href="javascript:void(0)">');
  158. $button.html(this.options.buttonLabel);
  159. $button.addClass('emoji-button');
  160. $button.attr({title: this.options.buttonLabel});
  161. this.$editor[this.options.buttonPosition]($button);
  162. } else {
  163. $button = $('');
  164. }
  165. $button.on('click', function(e) {
  166. EmojiMenu.show(self);
  167. e.stopPropagation();
  168. });
  169. this.$button = $button;
  170. };
  171. EmojiArea.createIcon = function(emoji) {
  172. var filename = $.emojiarea.icons[emoji];
  173. var path = $.emojiarea.path || '';
  174. if (path.length && path.charAt(path.length - 1) !== '/') {
  175. path += '/';
  176. }
  177. return '<img src="' + path + filename + '" alt="' + util.htmlEntities(emoji) + '">';
  178. };
  179. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  180. /**
  181. * Editor (plain-text)
  182. *
  183. * @constructor
  184. * @param {object} $textarea
  185. * @param {object} options
  186. */
  187. var EmojiArea_Plain = function($textarea, options) {
  188. this.options = options;
  189. this.$textarea = $textarea;
  190. this.$editor = $textarea;
  191. this.setup();
  192. };
  193. EmojiArea_Plain.prototype.insert = function(emoji) {
  194. if (!$.emojiarea.icons.hasOwnProperty(emoji)) return;
  195. util.insertAtCursor(emoji, this.$textarea[0]);
  196. this.$textarea.trigger('change');
  197. };
  198. EmojiArea_Plain.prototype.val = function() {
  199. return this.$textarea.val();
  200. };
  201. util.extend(EmojiArea_Plain.prototype, EmojiArea.prototype);
  202. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  203. /**
  204. * Editor (rich)
  205. *
  206. * @constructor
  207. * @param {object} $textarea
  208. * @param {object} options
  209. */
  210. var EmojiArea_WYSIWYG = function($textarea, options) {
  211. var self = this;
  212. this.options = options;
  213. this.$textarea = $textarea;
  214. this.$editor = $('<div>').addClass('emoji-wysiwyg-editor');
  215. this.$editor.text($textarea.val());
  216. this.$editor.attr({contenteditable: 'true'});
  217. this.$editor.on('blur keyup paste', function() { return self.onChange.apply(self, arguments); });
  218. this.$editor.on('mousedown focus', function() { document.execCommand('enableObjectResizing', false, false); });
  219. this.$editor.on('blur', function() { document.execCommand('enableObjectResizing', true, true); });
  220. var html = this.$editor.text();
  221. var emojis = $.emojiarea.icons;
  222. for (var key in emojis) {
  223. if (emojis.hasOwnProperty(key)) {
  224. html = html.replace(new RegExp(util.escapeRegex(key), 'g'), EmojiArea.createIcon(key));
  225. }
  226. }
  227. this.$editor.html(html);
  228. $textarea.hide().after(this.$editor);
  229. this.setup();
  230. this.$button.on('mousedown', function() {
  231. if (self.hasFocus) {
  232. self.selection = util.saveSelection();
  233. }
  234. });
  235. };
  236. EmojiArea_WYSIWYG.prototype.onChange = function() {
  237. this.$textarea.val(this.val()).trigger('change');
  238. };
  239. EmojiArea_WYSIWYG.prototype.insert = function(emoji) {
  240. var content;
  241. var $img = $(EmojiArea.createIcon(emoji));
  242. if ($img[0].attachEvent) {
  243. $img[0].attachEvent('onresizestart', function(e) { e.returnValue = false; }, false);
  244. }
  245. this.$editor.trigger('focus');
  246. if (this.selection) {
  247. util.restoreSelection(this.selection);
  248. }
  249. try { util.replaceSelection($img[0]); } catch (e) {}
  250. this.onChange();
  251. };
  252. EmojiArea_WYSIWYG.prototype.val = function() {
  253. var lines = [];
  254. var line = [];
  255. var flush = function() {
  256. lines.push(line.join(''));
  257. line = [];
  258. };
  259. var sanitizeNode = function(node) {
  260. if (node.nodeType === TEXT_NODE) {
  261. line.push(node.nodeValue);
  262. } else if (node.nodeType === ELEMENT_NODE) {
  263. var tagName = node.tagName.toLowerCase();
  264. var isBlock = TAGS_BLOCK.indexOf(tagName) !== -1;
  265. if (isBlock && line.length) flush();
  266. if (tagName === 'img') {
  267. var alt = node.getAttribute('alt') || '';
  268. if (alt) line.push(alt);
  269. return;
  270. } else if (tagName === 'br') {
  271. flush();
  272. }
  273. var children = node.childNodes;
  274. for (var i = 0; i < children.length; i++) {
  275. sanitizeNode(children[i]);
  276. }
  277. if (isBlock && line.length) flush();
  278. }
  279. };
  280. var children = this.$editor[0].childNodes;
  281. for (var i = 0; i < children.length; i++) {
  282. sanitizeNode(children[i]);
  283. }
  284. if (line.length) flush();
  285. return lines.join('\n');
  286. };
  287. util.extend(EmojiArea_WYSIWYG.prototype, EmojiArea.prototype);
  288. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  289. /**
  290. * Emoji Dropdown Menu
  291. *
  292. * @constructor
  293. * @param {object} emojiarea
  294. */
  295. var EmojiMenu = function() {
  296. var self = this;
  297. var $body = $(document.body);
  298. var $window = $(window);
  299. this.visible = false;
  300. this.emojiarea = null;
  301. this.$menu = $('<div>');
  302. this.$menu.addClass('emoji-menu');
  303. this.$menu.hide();
  304. this.$items = $('<div>').appendTo(this.$menu);
  305. $body.append(this.$menu);
  306. $body.on('keydown', function(e) {
  307. if (e.keyCode === KEY_ESC || e.keyCode === KEY_TAB) {
  308. self.hide();
  309. }
  310. });
  311. $body.on('mouseup', function() {
  312. self.hide();
  313. });
  314. $window.on('resize', function() {
  315. if (self.visible) self.reposition();
  316. });
  317. this.$menu.on('mouseup', 'a', function(e) {
  318. e.stopPropagation();
  319. return false;
  320. });
  321. this.$menu.on('click', 'a', function(e) {
  322. var emoji = $('.label', $(this)).text();
  323. window.setTimeout(function() {
  324. self.onItemSelected.apply(self, [emoji]);
  325. }, 0);
  326. e.stopPropagation();
  327. return false;
  328. });
  329. this.load();
  330. };
  331. EmojiMenu.prototype.onItemSelected = function(emoji) {
  332. this.emojiarea.insert(emoji);
  333. this.hide();
  334. };
  335. EmojiMenu.prototype.load = function() {
  336. var html = [];
  337. var options = $.emojiarea.icons;
  338. var path = $.emojiarea.path;
  339. if (path.length && path.charAt(path.length - 1) !== '/') {
  340. path += '/';
  341. }
  342. for (var key in options) {
  343. if (options.hasOwnProperty(key)) {
  344. var filename = options[key];
  345. html.push('<a href="javascript:void(0)" title="' + util.htmlEntities(key) + '">' + EmojiArea.createIcon(key) + '<span class="label">' + util.htmlEntities(key) + '</span></a>');
  346. }
  347. }
  348. this.$items.html(html.join(''));
  349. };
  350. EmojiMenu.prototype.reposition = function() {
  351. var $button = this.emojiarea.$button;
  352. var offset = $button.offset();
  353. offset.top += $button.outerHeight();
  354. offset.left += Math.round($button.outerWidth() / 2);
  355. this.$menu.css({
  356. top: offset.top,
  357. left: offset.left
  358. });
  359. };
  360. EmojiMenu.prototype.hide = function(callback) {
  361. if (this.emojiarea) {
  362. this.emojiarea.menu = null;
  363. this.emojiarea.$button.removeClass('on');
  364. this.emojiarea = null;
  365. }
  366. this.visible = false;
  367. this.$menu.hide();
  368. };
  369. EmojiMenu.prototype.show = function(emojiarea) {
  370. if (this.emojiarea && this.emojiarea === emojiarea) return;
  371. this.emojiarea = emojiarea;
  372. this.emojiarea.menu = this;
  373. this.reposition();
  374. this.$menu.show();
  375. this.visible = true;
  376. };
  377. EmojiMenu.show = (function() {
  378. var menu = null;
  379. return function(emojiarea) {
  380. menu = menu || new EmojiMenu();
  381. menu.show(emojiarea);
  382. };
  383. })();
  384. })(jQuery, window, document);