GitHub Custom Emojis

Add custom emojis from json source

当前为 2016-04-12 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Custom Emojis
  3. // @version 0.2.4
  4. // @description Add custom emojis from json source
  5. // @namespace https://github.com/StylishThemes
  6. // @include /https?://((gist)\.)?github\.com/
  7. // @grant GM_addStyle
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // @grant GM_xmlhttpRequest
  11. // @grant GM_info
  12. // @connect *
  13. // @run-at document-end
  14. // @require https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js
  15. // @require https://greasyfork.org/scripts/16936-ichord-caret-js/code/ichord-Caretjs.js?version=106431
  16. // @require https://greasyfork.org/scripts/16996-ichord-at-js-mod/code/ichord-Atjs-mod.js?version=109194
  17. // @require https://cdnjs.cloudflare.com/ajax/libs/ion-rangeslider/2.1.2/js/ion.rangeSlider.min.js
  18. // ==/UserScript==
  19. /* global jQuery, GM_addStyle, GM_getValue, GM_setValue, GM_xmlhttpRequest, GM_info */
  20. /* eslint-disable indent, quotes */
  21. (function($) {
  22. 'use strict';
  23.  
  24. var ghe = {
  25.  
  26. version : GM_info.script.version,
  27.  
  28. vars : {
  29. // delay until package.json allowed to load
  30. delay : 8.64e7, // 24 hours in milliseconds
  31.  
  32. // base url to fetch package.json
  33. root : 'https://raw.githubusercontent.com/StylishThemes/GitHub-Custom-Emojis/master/',
  34. emojiClass : 'ghe-custom-emoji',
  35. emojiTxtTemplate : '~${name}',
  36. emojiImgTemplate : ':_${name}:',
  37. maxEmojiZoom : 3,
  38. maxEmojiHeight : 150,
  39.  
  40. // Keyboard shortcut to open panel
  41. keyboardOpen : 'g+=',
  42. keyboardDelay : 1000
  43. },
  44.  
  45. regex : {
  46. // nodes to skip while traversing the dom
  47. skipElm : /^(script|style|svg|iframe|br|meta|link|textarea|input|code|pre)$/i,
  48. // emoji template
  49. template : /\$\{name\}/,
  50. // character to escape in regex
  51. charsToEsc : /[-\/\\^$*+?.()|[\]{}]/g
  52. },
  53.  
  54. defaults : {
  55. activeZoom : 1.8,
  56. caseSensitive : false,
  57. rangeHeight : '20;40', // min;max as set by ion.rangeSlider
  58. insertAsImage : false,
  59. // emoji json sources
  60. sources : [
  61. 'https://raw.githubusercontent.com/StylishThemes/GitHub-Custom-Emojis/master/collections/emoji-custom.json',
  62. 'https://raw.githubusercontent.com/StylishThemes/GitHub-Custom-Emojis/master/collections/emoji-crazy-rabbit.json',
  63. 'https://raw.githubusercontent.com/StylishThemes/GitHub-Custom-Emojis/master/collections/emoji-onion-head.json',
  64. 'https://raw.githubusercontent.com/StylishThemes/GitHub-Custom-Emojis/master/collections/emoji-unicode.json',
  65. 'https://raw.githubusercontent.com/StylishThemes/GitHub-Custom-Emojis/master/collections/emoji-custom-text.json'
  66. ]
  67. },
  68.  
  69. // emoji json stored here
  70. collections : {},
  71.  
  72. // GitHub ajax containers
  73. containers : [
  74. '#js-pjax-container',
  75. '#js-repo-pjax-container',
  76. '.js-contribution-activity',
  77. '.more-repos', // loading "more" of "Your repositories"
  78. '#dashboard .news', // loading "more" news
  79. '.js-preview-body' // comment previews
  80. ],
  81.  
  82. // promises used when loading JSON
  83. promises : {},
  84.  
  85. getStoredValues : function() {
  86. var defaults = this.defaults;
  87. this.settings = {
  88. rangeHeight : GM_getValue('rangeHeight', defaults.rangeHeight),
  89. activeZoom : GM_getValue('activeZoom', defaults.activeZoom),
  90. caseSensitive : GM_getValue('caseSensitive', defaults.caseSensitive),
  91. insertAsImage : GM_getValue('insertAsImage', defaults.insertAsImage),
  92. sources : GM_getValue('sources', defaults.sources),
  93.  
  94. date : GM_getValue('date', 0)
  95. };
  96.  
  97. this.collections = GM_getValue('collections', {});
  98.  
  99. debug('Retrieved stored values & collections', this.settings, this.collections);
  100. },
  101.  
  102. storeVal : function(key, set, $el) {
  103. var tmp,
  104. val = set[key];
  105. GM_setValue(key, val);
  106. if (typeof val === 'boolean') {
  107. $el.prop('checked', val);
  108. } else {
  109. $el.val(val);
  110. }
  111. // update sliders
  112. if ($el.hasClass('ghe-height')) {
  113. tmp = val.split(';');
  114. $el.data('ionRangeSlider').update({
  115. from: tmp[0],
  116. to: tmp[1]
  117. });
  118. } else if ($el.hasClass('ghe-zoom')) {
  119. $el.data('ionRangeSlider').update({
  120. from: val
  121. });
  122. }
  123. },
  124.  
  125. setStoredValues : function(reset) {
  126. var $el, tmp, len, indx,
  127. s = ghe.settings,
  128. d = ghe.defaults,
  129. $panel = $('#ghe-settings-inner');
  130.  
  131. ghe.busy = true;
  132. ghe.storeVal('caseSensitive', reset ? d : s, $panel.find('.ghe-case'));
  133. ghe.storeVal('insertAsImage', reset ? d : s, $panel.find('.ghe-image'));
  134. ghe.storeVal('activeZoom', reset ? d : s, $panel.find('.ghe-zoom'));
  135. ghe.storeVal('rangeHeight', reset ? d : s, $panel.find('.ghe-height'));
  136.  
  137. GM_setValue('collections', this.collections);
  138. GM_setValue('date', s.date);
  139.  
  140. if (reset) {
  141. // add defaults back into source list; but don't remove any new stuff
  142. len = d.sources.length;
  143. for (indx = 0; indx < len; indx++) {
  144. if (s.sources.indexOf(d.sources[indx]) < 0) {
  145. s.sources[s.sources.length] = d.sources[indx];
  146. }
  147. }
  148. } else if (reset === false) {
  149. // Refresh sources, so clear out collections
  150. this.collections = {};
  151. }
  152. tmp = s.sources;
  153. len = tmp.length;
  154. GM_setValue('sources', tmp);
  155. for (indx = 0; indx < len; indx++) {
  156. if ($panel.find('.ghe-source').eq(indx).length) {
  157. $el = $panel
  158. .find('.ghe-source-input')
  159. .eq(indx)
  160. .attr('data-url', tmp[indx]);
  161. } else {
  162. $el = $(ghe.sourceHTML)
  163. .appendTo($panel.find('.ghe-sources'))
  164. .find('.ghe-source-input')
  165. .attr('data-url', tmp[indx]);
  166. }
  167. // only show file name when not focused
  168. ghe.showFileName($el);
  169. }
  170. // remove extras
  171. $panel.find('.ghe-source').filter(':gt(' + len + ')').remove();
  172. if (reset) {
  173. this.updateSettings();
  174. }
  175. if (typeof reset === 'boolean') {
  176. // reset autocomplete after refresh or restore so we're using the
  177. // most up-to-date collection data
  178. $('.comment-form-textarea').atwho('destroy');
  179. }
  180. debug((reset ? 'Resetting' : 'Saving') + ' current values & updating panel', s);
  181. ghe.busy = false;
  182. },
  183.  
  184. updateSettings : function() {
  185. this.isUpdating = true;
  186. var settings = this.settings,
  187. $panel = $('#ghe-settings-inner');
  188. settings.rangeHeight = $panel.find('.ghe-height').val();
  189. settings.activeZoom = $panel.find('.ghe-zoom').val();
  190. settings.insertAsImage = $panel.find('.ghe-image').is(':checked');
  191. settings.caseSensitive = $panel.find('.ghe-case').is(':checked');
  192. settings.sources = $panel.find('.ghe-source-input').map(function() {
  193. return $(this).attr('data-url');
  194. }).get();
  195.  
  196. // update case-sensitive regex
  197. this.setRegex();
  198.  
  199. debug('Updating user settings', settings);
  200. this.updateStyleSheet();
  201. this.isUpdating = false;
  202. },
  203.  
  204. loadEmojiJson : function(update) {
  205. // only load emoji.json once a day, or after a forced update
  206. if (update || (new Date().getTime() > this.settings.date + this.vars.delay)) {
  207. var indx,
  208. promises = [],
  209. sources = this.settings.sources,
  210. len = sources.length;
  211. for (indx = 0; indx < len; indx++) {
  212. promises[promises.length] = this.fetchCustomEmojis(sources[indx]);
  213. }
  214. $.when.apply(null, promises).done(function() {
  215. ghe.checkPage();
  216. ghe.promises = [];
  217. ghe.settings.date = new Date().getTime();
  218. GM_setValue('date', ghe.settings.date);
  219. GM_setValue('collections', ghe.collections);
  220. });
  221. }
  222. },
  223.  
  224. fetchCustomEmojis : function(url) {
  225. if (!this.promises[url]) {
  226. this.promises[url] = $.Deferred(function(defer) {
  227. debug('Fetching custom emoji list', url);
  228. GM_xmlhttpRequest({
  229. method : 'GET',
  230. url : url,
  231. onload : function(response) {
  232. var json = false;
  233. try {
  234. json = JSON.parse(response.responseText);
  235. } catch (err) {
  236. debug('Invalid JSON', url);
  237. return defer.reject();
  238. }
  239. if (json && json[0].name) {
  240. // save url to make removing the entry easier
  241. json[0].url = url;
  242. ghe.collections[json[0].name] = json;
  243. debug('Adding "' + json[0].name + '" Emoji Collection');
  244. }
  245. return defer.resolve();
  246. }
  247. });
  248. }).promise();
  249. }
  250. return this.promises[url];
  251. },
  252.  
  253. // Using: document.evaluate('//*[text()[contains(.,":_")]]', document.body, null,
  254. // XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
  255. // to find matching content as it is much faster than scanning each node
  256. checkPage : function() {
  257. this.isUpdating = true;
  258. var node,
  259. indx = 0,
  260. parts = this.vars.emojiImgTemplate.split('${name}'), // parts = [':_', ':']
  261. // adding "//" starts from document, so if node is defined, don't
  262. // include it so the search starts from the node
  263. path = '//*[text()[contains(.,"' + parts[0] + '")]]',
  264. nodes = document.evaluate(path, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null),
  265. len = nodes.snapshotLength;
  266. try {
  267. node = nodes.snapshotItem(indx);
  268. while (node && indx++ < len) {
  269. if (!ghe.regex.skipElm.test(node.nodeName)) {
  270. ghe.findEmoji(node);
  271. }
  272. node = nodes.snapshotItem(indx);
  273. }
  274. } catch (e) {
  275. debug('Nothing to replace!', e);
  276. }
  277. this.isUpdating = false;
  278. },
  279.  
  280. findEmoji : function(node) {
  281. var indx, len, group, match, matchesLen, name,
  282. regex = ghe.regex.nameRegex,
  283. matches = [],
  284. emojis = this.collections,
  285. str = node.textContent;
  286. while ((match = regex.exec(str)) !== null) {
  287. matches[matches.length] = match[1];
  288. }
  289. if (matches && matches[0]) {
  290. matchesLen = matches.length;
  291. for (group in emojis) {
  292. // cycle through the collections (except text type)
  293. if (emojis.hasOwnProperty(group) && emojis[group][0].type !== 'text') {
  294. len = emojis[group].length;
  295. for (indx = 1; indx < len; indx++) {
  296. name = emojis[group][indx].name;
  297. for (match = 0; match < matchesLen; match++) {
  298. if (name === matches[match]) {
  299. debug('found "' + matches[match] + '" in "' + node.textContent + '"');
  300. ghe.replaceText(node, emojis[group][indx]);
  301. }
  302. }
  303. }
  304. }
  305. }
  306. }
  307. },
  308.  
  309. replaceText : function(node, emoji) {
  310. var data, pos, imgnode, middlebit, endbit,
  311. isCased = this.settings.caseSensitive,
  312. name = this.vars.emojiImgTemplate.replace(ghe.regex.template, emoji.name),
  313. skip = 0;
  314. name = isCased ? name : name.toUpperCase();
  315. // Code modified from highlight-5 (MIT license)
  316. // http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
  317. if (node.nodeType === 3) {
  318. data = isCased ? node.data : node.data.toUpperCase();
  319. pos = data.indexOf(name);
  320. pos -= (data.substr(0, pos).length - node.data.substr(0, pos).length);
  321. if (pos >= 0) {
  322. imgnode = ghe.createEmoji(emoji);
  323. middlebit = node.splitText(pos);
  324. endbit = middlebit.splitText(name.length);
  325. middlebit.parentNode.replaceChild(imgnode, middlebit);
  326. skip = 1;
  327. }
  328. } else if (node.nodeType === 1 && node.childNodes) {
  329. for (var i = 0; i < node.childNodes.length; ++i) {
  330. i += ghe.replaceText(node.childNodes[i], emoji);
  331. }
  332. }
  333. return skip;
  334. },
  335.  
  336. // This function does the surrounding for every matched piece of text
  337. // and can be customized to do what you like
  338. // <img class="emoji" title=":smile:" alt=":smile:" src="x.png" height="20" width="20" align="absmiddle">
  339. createEmoji : function(emoji) {
  340. var el = document.createElement('img');
  341. el.src = emoji.url;
  342. el.className = ghe.vars.emojiClass + ' emoji';
  343. el.title = el.alt = ghe.vars.emojiImgTemplate.replace(ghe.regex.template, emoji.name);
  344. // el.align = 'absmiddle'; // deprecated attribute
  345. return el;
  346. },
  347.  
  348. // used by autocomplete (atwho) filter function
  349. matches : function(query, labels) {
  350. if (query === '') {
  351. return 1;
  352. }
  353. labels = labels || '';
  354. var i, partial,
  355. count = 0,
  356. isCS = this.settings.caseSensitive,
  357. arry = (isCS ? labels : labels.toUpperCase()).split(/[\s,_]+/),
  358. parts = (isCS ? query : query.toUpperCase()).split(/[,_]/),
  359. len = parts.length;
  360. for (i = 0; i < len; i++) {
  361. // full match or partial
  362. partial = arry.join('_').indexOf(parts.join('_'));
  363. if (arry.indexOf(parts[i]) > -1 || partial > -1) {
  364. count++;
  365. }
  366. // give more weight to results with indexOf closer to zero
  367. if (partial > -1 && partial < len / 2) {
  368. count++;
  369. }
  370. }
  371. // return fraction of query matches
  372. return count / len;
  373. },
  374.  
  375. emojiSort : function(a, b) {
  376. return a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
  377. },
  378.  
  379. // init when comment textarea is focused
  380. initAutocomplete : function($el) {
  381. if (!$el.data('atwho')) {
  382. var indx, imgLen, txtLen, name, group,
  383. text = [],
  384. data = [];
  385. // combine data
  386. for (name in ghe.collections) {
  387. if (ghe.collections.hasOwnProperty(name)) {
  388. group = ghe.collections[name].slice(1);
  389. if (ghe.collections[name][0].type === 'text') {
  390. text = text.concat(group);
  391. } else {
  392. data = data.concat(group);
  393. }
  394. }
  395. }
  396. imgLen = data.length;
  397. if (imgLen) {
  398. // alphabetic sort
  399. data = data.sort(ghe.emojiSort);
  400. // add prepend name to labels
  401. for (indx = 0; indx < imgLen; indx++) {
  402. data[indx].labels = data[indx].name.replace(/_/g, ' ') + ' ' + data[indx].labels;
  403. }
  404. // add emoji autocomplete to comment textareas
  405. $el.atwho({
  406. // first two characters from emojiImgTemplate
  407. at : ghe.vars.emojiImgTemplate.split('${name}')[0],
  408. data : data,
  409. searchKey: 'labels',
  410. displayTpl : '<li><span><img src="${url}" height="30" /></span>${name}</li>',
  411. insertTpl : ghe.vars.emojiImgTemplate,
  412. delay : 400,
  413. callbacks : {
  414. matcher: function(flag, subtext) {
  415. var regexp = ghe.regex.emojiImgFilter,
  416. match = regexp.exec(subtext);
  417. // this next line does some magic...
  418. // for some reason, without it, moving the caret from "p" to "r" in
  419. // ":_people,fear," opens & closes the popup with each letter typed
  420. subtext.match(regexp);
  421. if (match) {
  422. return match[2] || match[1];
  423. } else {
  424. return null;
  425. }
  426. },
  427. filter: function(query, data, searchKey) {
  428. var i, item,
  429. len = data.length,
  430. _results = [];
  431. for (i = 0; i < len; i++) {
  432. item = data[i];
  433. item.atwho_order = ghe.matches(query, item[searchKey]);
  434. if (item.atwho_order > 0.9) {
  435. _results[_results.length] = item;
  436. }
  437. }
  438. return query === '' ? _results : _results.sort(function(a, b) {
  439. // descending sort
  440. return b.atwho_order - a.atwho_order;
  441. });
  442. },
  443. sorter: function(query, items) {
  444. // sorted by filter
  445. return items;
  446. },
  447. // event parameter adding in atwho.js mod
  448. beforeInsert: function(value, $li, event) {
  449. if (event.shiftKey || ghe.settings.insertAsImage) {
  450. // add image tag directly if shift is held
  451. return '<img title="' +
  452. ghe.vars.emojiImgTemplate.replace(ghe.regex.template, $li.text()) +
  453. '" src="' + $li.find('img').attr('src') + '">';
  454. }
  455. return value;
  456. }
  457. }
  458. });
  459. }
  460.  
  461. txtLen = text.length;
  462. if (txtLen) {
  463. // alphabetic sort
  464. text = text.sort(ghe.emojiSort);
  465. $el.atwho({
  466. at : ghe.vars.emojiTxtTemplate.split('${name}')[0],
  467. data : text,
  468. searchKey: 'name',
  469. // add data-emoji because of Emoji-One Chrome extension adds
  470. // hidden text and an svg image inside the span
  471. displayTpl : '<li data-emoji="${text}"><span class="ghe-text">${text}</span>${name}</li>',
  472. insertTpl : ghe.vars.emojiTxtTemplate,
  473. delay : 400,
  474. callbacks : {
  475. matcher: function(flag, subtext) {
  476. var regexp = ghe.regex.emojiTxtFilter,
  477. match = regexp.exec(subtext);
  478. // this next line does some magic...
  479. subtext.match(regexp);
  480. if (match) {
  481. return match[2] || match[1];
  482. } else {
  483. return null;
  484. }
  485. },
  486. filter: function(query, data, searchKey) {
  487. var i, item,
  488. len = data.length,
  489. _results = [];
  490. for (i = 0; i < len; i++) {
  491. item = data[i];
  492. item.atwho_order = ghe.matches(query, item[searchKey]);
  493. if (item.atwho_order > 0.9) {
  494. _results[_results.length] = item;
  495. }
  496. }
  497. return query === '' ? _results : _results.sort(function(a, b) {
  498. // descending sort
  499. return b.atwho_order - a.atwho_order;
  500. });
  501. },
  502. sorter: function(query, items) {
  503. // sorted by filter
  504. return items;
  505. },
  506. // event parameter adding in atwho.js mod
  507. beforeInsert: function(value, $li, event) {
  508. return $li.attr('data-emoji');
  509. }
  510. }
  511. });
  512. }
  513. // use classes from GitHub-Dark to make theme match GitHub-Dark
  514. $('.atwho-view').addClass('popover suggester');
  515. }
  516. },
  517.  
  518. addToolbarIcon : function() {
  519. // add Emoji setting icons
  520. var indx, $el,
  521. $toolbars = $('.toolbar-commenting'),
  522. len = $toolbars.length;
  523. for (indx = 0; indx < len; indx++) {
  524. $el = $toolbars.eq(indx);
  525. if (!$el.find('.ghe-settings-icon').length) {
  526. $el.prepend([
  527. '<button type="button" class="ghe-settings-open toolbar-item tooltipped tooltipped-n tooltipped-multiline" aria-label="Browse collections & Set Emojis Options" tabindex="-1">',
  528. '<svg class="ghe-settings-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor">',
  529. '<path d="M7.205 3.233c0 .952-.753 1.73-1.722 1.73-.953 0-1.707-.793-1.707-1.73 0-.937.762-1.73 1.707-1.73.97 0 1.73.793 1.73 1.73h-.008zm6.904 0c0 .952-.794 1.73-1.747 1.73-.95 0-1.722-.793-1.722-1.73 0-.937.795-1.73 1.73-1.73.938 0 1.747.793 1.747 1.73h-.008zM7.204 10.1v5.19c0 1.728 6.904 1.728 6.904 0V10.1M10.642 10.1v3.46"/>',
  530. '<path d="M.878 8.777s3.167 1.893 8.002 1.92c4.365.02 8.135-1.92 8.135-1.92"/>',
  531. '</svg>',
  532. '</button>'
  533. ].join(''));
  534. }
  535. }
  536. },
  537.  
  538. // dynamic stylesheet
  539. updateStyleSheet : function() {
  540. var range = this.settings.rangeHeight.split(';');
  541. ghe.$style.text([
  542. // img styling - vertically center with set height range
  543. '.atwho-view li img, #ghe-popup .select-menu-item img, img[alt="ghe-emoji"], .' +
  544. this.vars.emojiClass + ' { ' +
  545. 'margin-bottom:.25em; vertical-align:middle; ' +
  546. 'min-height: ' + (range[0] || 'none') + 'px;' +
  547. 'max-height: ' + (range[1] || 'none') + 'px }',
  548. // click (make active) on image to zoom
  549. '.' + this.vars.emojiClass + ':active, a:active img[alt="ghe-emoji"] { zoom:' +
  550. this.settings.activeZoom + ' }'
  551. ].join(''));
  552. },
  553.  
  554. addBindings : function() {
  555. var lastKey,
  556. $popup = $('#ghe-popup'),
  557. $settings = $('#ghe-settings');
  558. // Delegated bindings
  559. $('body')
  560. .on('click', '.ghe-settings-open', function() {
  561. // open all collections panel
  562. ghe.openCollections($(this));
  563. return false;
  564. })
  565. .on('click', '.ghe-collection', function() {
  566. // open targeted collection
  567. var name = $(this).attr('data-group');
  568. ghe.showCollection(name);
  569. })
  570. .on('click', '.ghe-emoji', function(e) {
  571. // click on emoji in collection to add to textarea
  572. ghe.addEmoji(e, $(this));
  573. })
  574. .on('click keypress keydown', function(e) {
  575. clearTimeout(ghe.timer);
  576. var panelVisible = $popup.hasClass('in') || $settings.hasClass('in'),
  577. openPanel = ghe.vars.keyboardOpen.split('+'),
  578. key = String.fromCharCode(e.which).toLowerCase();
  579. // press escape or click outside to close the panel
  580. if (panelVisible && e.which === 27 || e.type === 'click' && !$(e.target).closest('#ghe-wrapper').length) {
  581. ghe.closePanels();
  582. return;
  583. }
  584. // keydown is only needed for escape key detection
  585. if (e.type === 'keydown' || /(input|textarea)/i.test(document.activeElement.nodeName)) {
  586. return;
  587. }
  588. // shortcut keys need keypress
  589. if (lastKey === openPanel[0] && key === openPanel[1]) {
  590. if ($settings.hasClass('in')) {
  591. ghe.closePanels();
  592. } else {
  593. ghe.openSettings();
  594. }
  595. }
  596. lastKey = key;
  597. ghe.timer = setTimeout(function() {
  598. lastKey = null;
  599. }, ghe.vars.keyboardDelay);
  600.  
  601. // add shortcut to help menu
  602. if (key === '?') {
  603. // table doesn't exist until user presses "?"
  604. setTimeout(function() {
  605. if (!$('.ghe-shortcut').length) {
  606. $('.keyboard-mappings:eq(0) tbody:eq(0)').append([
  607. '<tr class="ghe-shortcut">',
  608. '<td class="keys">',
  609. '<kbd>' + openPanel[0] + '</kbd> <kbd>' + openPanel[1] + '</kbd>',
  610. '</td>',
  611. '<td>GitHub Emojis: open settings</td>',
  612. '</tr>'
  613. ].join(''));
  614. }
  615. }, 300);
  616. }
  617. });
  618.  
  619. // popup & settings interactions
  620. $('#ghe-popup .octicon-gear').on('click keyup', function(e) {
  621. if (e.type === 'keyup' && e.which !== 13) {
  622. return;
  623. }
  624. ghe.openSettings();
  625. });
  626. $('#ghe-settings, #ghe-settings-close, #ghe-settings-inner').on('click', function(e) {
  627. if (this.id === 'ghe-settings-inner') {
  628. e.stopPropagation();
  629. } else {
  630. ghe.closePanels();
  631. }
  632. });
  633. // ghe-checkbox added to checkboxes
  634. $('.ghe-checkbox').on('change', function() {
  635. ghe.updateSettings();
  636. });
  637. // go back - switch from single collection to showing all collections
  638. $('#ghe-popup .ghe-back').on('click', function() {
  639. $('.ghe-single-collection, .ghe-back').hide();
  640. $('.ghe-all-collections').show();
  641. });
  642.  
  643. // add new source input
  644. $('#ghe-add-source').on('click', function() {
  645. var $panel = $('#ghe-settings-inner');
  646. // lets not get crazy!
  647. if ($panel.find('.ghe-source').length < 20) {
  648. $(ghe.sourceHTML).appendTo($panel.find('.ghe-sources'));
  649. }
  650. return false;
  651. });
  652. $('#ghe-refresh-sources, #ghe-restore').on('click', function() {
  653. // update sources from settings panel
  654. ghe.setStoredValues(this.id === 'ghe-restore');
  655. // load json files
  656. ghe.loadEmojiJson(true);
  657. return false;
  658. });
  659.  
  660. // Init range slider
  661. $('.ghe-height')
  662. .val(ghe.settings.rangeHeight)
  663. .ionRangeSlider({
  664. type : 'double',
  665. min : 0,
  666. max : ghe.vars.maxEmojiHeight,
  667. onChange : function() {
  668. ghe.updateSettings();
  669. },
  670. force_edges : true,
  671. hide_min_max : true
  672. });
  673. $('.ghe-zoom')
  674. .val(ghe.settings.activeZoom)
  675. .ionRangeSlider({
  676. min : 0,
  677. max : ghe.vars.maxEmojiZoom,
  678. step : 0.1,
  679. onChange : function() {
  680. ghe.updateSettings();
  681. },
  682. force_edges : true,
  683. hide_min_max : true
  684. });
  685.  
  686. // Remove source input - delegated binding
  687. $('.ghe-settings-wrapper')
  688. .on('click', '.ghe-remove', function() {
  689. var $wrapper = $(this).closest('.ghe-source'),
  690. url = $wrapper.find('.ghe-source-input').attr('data-url');
  691. ghe.removeSource(url);
  692. $wrapper.remove();
  693. ghe.setStoredValues();
  694. return false;
  695. })
  696. .on('focus blur input change', '.ghe-source-input', function(e) {
  697. if (ghe.busy) { return; }
  698. ghe.busy = true;
  699. var val,
  700. $this = $(this);
  701. switch (e.type) {
  702. case 'focus':
  703. case 'focusin':
  704. // show entire url when focused
  705. $this.val($this.attr('data-url'));
  706. break;
  707. case 'blur':
  708. case 'focusout':
  709. ghe.showFileName($this);
  710. break;
  711. default:
  712. $this.attr('data-url', $this.val());
  713. }
  714. if (e.type === 'change' || e.which === 13) {
  715. val = $this.val();
  716. $this.attr('data-url', val);
  717. ghe.fetchCustomEmojis(val);
  718. }
  719. ghe.busy = false;
  720. });
  721.  
  722. // initialize autocomplete that add emojis, but only on focus
  723. // since every comment has a hidden textarea
  724. $('body').on('focus', '.comment-form-textarea', function() {
  725. ghe.initAutocomplete($(this));
  726. });
  727. },
  728.  
  729. showFileName : function($el) {
  730. var str = $el.attr('data-url'),
  731. v = str.substring(str.lastIndexOf('/') + 1, str.length);
  732. // show only the file name in the input when blurred
  733. // unless there is no file name
  734. $el.val(v === '' ? str : '...' + v);
  735. },
  736.  
  737. closePanels : function() {
  738. $('#ghe-popup').removeClass('in');
  739. $('#ghe-settings').removeClass('in');
  740. ghe.$currentInput = null;
  741. },
  742.  
  743. openSettings : function() {
  744. $('.modal-backdrop').click();
  745. $('#ghe-settings').addClass('in');
  746. },
  747.  
  748. openCollections : function($el) {
  749. ghe.addCollections();
  750. var pos = $el.offset();
  751. $('#ghe-settings').removeClass('in');
  752. $('#ghe-popup')
  753. .addClass('in')
  754. .css({
  755. left: pos.left + 25,
  756. top: pos.top
  757. });
  758. ghe.$currentInput = $el.closest('.previewable-comment-form').find('.comment-form-textarea');
  759. },
  760.  
  761. addCollections : function() {
  762. var indx, len, key, group, item, emoji,
  763. collections = ghe.collections,
  764. range = ghe.settings.rangeHeight.split(';'),
  765. list = [],
  766. items = [];
  767. // build collections list -
  768. for (key in collections) {
  769. if (collections.hasOwnProperty(key)) {
  770. list[list.length] = key;
  771. }
  772. }
  773. list = list.sort(function(a, b) {
  774. return a > b ? 1 : (a < b ? -1 : 0);
  775. });
  776. len = list.length;
  777. // add random image from group
  778. for (indx = 0; indx < len; indx++) {
  779. group = collections[list[indx]];
  780. // random image (skip first entry)
  781. item = Math.round(Math.random() * (group.length - 2)) + 1;
  782. emoji = group[item];
  783. items[items.length] = '<div class="select-menu-item js-navigation-item ghe-collection' +
  784. (emoji.url ? '' : ' ghe-text-collection') +
  785. '" data-group="' + list[indx] + '">' +
  786. // collection info stored in first entry
  787. group[0].name + ' <span class="ghe-right' +
  788. (emoji.url ?
  789. // images
  790. '"><img src="' + emoji.url + '" title="' +
  791. ghe.vars.emojiImgTemplate.replace(ghe.regex.template, emoji.name) + '" style="' +
  792. 'min-height:' + (range[0] || 'none') + 'px;' +
  793. 'max-height:' + (range[1] || 'none') + 'px;">' :
  794. // text
  795. ' ghe-text" title="' + emoji.name + '" style="font-size:' + group[0].previewSize +
  796. '">' + emoji.text
  797. ) + '</span></div>';
  798. }
  799. $('.ghe-single-collection, .ghe-back').hide();
  800. $('.ghe-all-collections').html(items.join('')).show();
  801. },
  802.  
  803. showCollection : function(name) {
  804. var indx, emoji,
  805. range = ghe.settings.rangeHeight.split(';'),
  806. group = ghe.collections[name].slice(1).sort(ghe.emojiSort),
  807. list = [],
  808. len = group.length;
  809. for (indx = 1; indx < len; indx++) {
  810. emoji = group[indx];
  811. list[indx - 1] = '<div class="select-menu-item js-navigation-item ghe-emoji' +
  812. (emoji.url ? '' : ' ghe-text-emoji') +
  813. '" data-name="' + emoji.name + '">' +
  814. emoji.name + '<span class="ghe-right' +
  815. (emoji.url ?
  816. // images
  817. '"><img src="' + emoji.url + '" style="' +
  818. 'min-height:' + (range[0] || 'none') + 'px;' +
  819. 'max-height:' + (range[1] || 'none') + 'px">' :
  820. // text type
  821. ' ghe-text" style="font-size:' + ghe.collections[name][0].previewSize +
  822. // data-emoji needed because Chrome emoji-one extension adds hidden
  823. // text inside the span when it replaces the text with an svg
  824. '" data-emoji="' + emoji.text + '">' + emoji.text
  825. ) + '</span></div>';
  826. }
  827. $('.ghe-all-collections').hide();
  828. $('.ghe-single-collection').html(list.join('')).show();
  829. $('.ghe-back').show();
  830. },
  831.  
  832. // add emoji from collection
  833. addEmoji : function(e, $el) {
  834. var val, emoji,
  835. $img = $el.find('img'),
  836. name = $el.attr('data-name'),
  837. caretPos = ghe.$currentInput.caret('pos');
  838. if ($img.length) {
  839. // insert into textarea
  840. if (e.shiftKey || ghe.settings.insertAsImage) {
  841. // add image tag directly if shift is held;
  842. // GitHub does NOT allow class names so we are forced to use alt
  843. emoji = '<img alt="ghe-emoji" title="' +
  844. ghe.vars.emojiImgTemplate.replace(ghe.regex.template, name) +
  845. '" src="' + $el.find('img').attr('src') + '">';
  846. } else {
  847. emoji = ghe.vars.emojiImgTemplate.replace(ghe.regex.template, name);
  848. }
  849. } else {
  850. // insert text emoji
  851. emoji = $el.find('span').attr('data-emoji');
  852. }
  853. val = ghe.$currentInput.val();
  854. ghe.$currentInput
  855. .val(val.slice(0, caretPos) + emoji + ' ' + val.slice(caretPos))
  856. .focus()
  857. .caret('pos', caretPos + emoji.length + 1);
  858. ghe.closePanels();
  859. },
  860.  
  861. removeSource : function(url) {
  862. var indx,
  863. list = [],
  864. collections = this.collections,
  865. sources = this.settings.sources,
  866. len = sources.length;
  867. // remove from source
  868. for (indx = 0; indx < len; indx++) {
  869. if (sources[indx] !== url) {
  870. list[list.length] = sources[indx];
  871. }
  872. }
  873. this.settings.sources = list;
  874. for (indx in collections) {
  875. if (collections.hasOwnProperty(indx) && collections[indx][0].url === url) {
  876. delete collections[indx];
  877. debug('Removing "' + indx + '" collection', collections);
  878. }
  879. }
  880. },
  881.  
  882. update : function() {
  883. this.isUpdating = true;
  884. this.addToolbarIcon();
  885. // checkPage clears isUpdating flag
  886. this.checkPage();
  887. },
  888.  
  889. addPanels : function() {
  890. /* https://github.com/ichord/At.js styles for autocomplete */
  891. GM_addStyle([
  892. // settings panel
  893. '#ghe-menu:hover { cursor:pointer }',
  894. '#ghe-settings { position:fixed; z-index:65535; top:0; bottom:0; left:0; right:0; opacity:0; visibility:hidden }',
  895. '#ghe-settings.in { opacity:1; visibility:visible; background:rgba(0,0,0,.5) }',
  896. '#ghe-settings-inner { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); width:25rem; box-shadow:0 .5rem 1rem #111; color:#c0c0c0 }',
  897. '#ghe-settings label { margin-left:.5rem; position:relative; top:-1px }',
  898. '#ghe-settings .ghe-remove { float:right; margin-top:2px; padding:4px; cursor:pointer }',
  899. '#ghe-settings .ghe-remove-icon { position:relative; top:3px }',
  900. '#ghe-settings-close { fill:#666; float:right; cursor:pointer }',
  901. '#ghe-settings-close:hover { fill:#ccc }',
  902. '#ghe-settings .ghe-settings-wrapper { max-height:60vh; overflow-y:auto; padding:1px 10px; margin-top:6px }',
  903. '#ghe-settings .ghe-right, #ghe-popup .ghe-right { float:right }',
  904. '#ghe-settings p { line-height:25px; }',
  905. '#ghe-settings .checkbox input { margin-top:.35em }',
  906. '#ghe-settings input[type="checkbox"] { width:16px !important; height:16px !important; border-radius:3px !important }',
  907. '#ghe-settings .boxed-group-inner { padding:0; }',
  908. '#ghe-settings .ghe-footer { padding: 10px; border-top: #555 solid 1px; }',
  909. '#ghe-settings .ghe-min-height, #ghe-settings .ghe-max-height, .ghe-zoom { width: 5em; }',
  910. '#ghe-settings .ghe-source-input { width: 90%; padding:3px; margin:3px 0 }',
  911. '#ghe-settings .ghe-slider-wrapper { height:40px; }',
  912. '#ghe-settings .ghe-slider-wrapper label { position:relative; top:22px }',
  913. '#ghe-settings .ghe-range-slider, #ghe-settings .ghe-zoom-slider { position:relative; height:40px; width:250px; float:right }',
  914.  
  915. // show emoji collections
  916. '#ghe-popup { display:none }',
  917. '#ghe-popup .ghe-content, #ghe-popup .ghe-content > div { max-height: 200px }',
  918. '#ghe-popup .octicon-gear { margin-left:4px }',
  919. '#ghe-popup .ghe-back svg { height:20px; padding:4px 14px 4px 4px }',
  920. '#ghe-popup .select-menu-item { font-size:1.1em; font-weight:bold; line-height:40px; padding:8px }',
  921. '#ghe-popup .select-menu-item.ghe-text-emoji { line-height:inherit; position:relative; padding-right:45px }',
  922. '#ghe-popup .select-menu-item.ghe-text-emoji .ghe-text { position:absolute; right:10px; top:0 }',
  923. '#ghe-popup .select-menu-item .ghe-text, .atwho-view .ghe-text { font-size:1.6em }',
  924. '.ghe-settings-icon, #ghe-popup.in { display:inline-block }',
  925.  
  926. // autocomplete popup in comment
  927. '.atwho-view { position:absolute; top:0; left:0; display:none; margin-top:18px; background:#fff; color:#000; border:1px solid #ddd; border-radius:3px; box-shadow:0 0 5px rgba(0,0,0,.1); min-width:300px; max-width:none!important; max-height:225px; overflow:auto; z-index:11110!important }',
  928. '.atwho-view .navigation-focus { background:#36f; color:#fff }',
  929. '.atwho-view .navigation-focus small { color:#fff }',
  930. '.atwho-view strong { color:#36F }',
  931. '.atwho-view .navigation-focus strong { color:#fff; font:700 }',
  932. '.atwho-view ul { list-style:none; padding:0; margin:auto }',
  933. '.atwho-view ul li { display:block; padding:5px 10px; border-bottom:1px solid #ddd; cursor:pointer }',
  934. '.atwho-view li span { display:inline-block; min-width:60px; padding-right:4px }',
  935. '.atwho-view small { font-size:smaller; color:#777; font-weight:400 }',
  936.  
  937. // rangeSlider
  938. '.irs{position:relative;display:block;-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}',
  939. '.irs-line{position:relative;display:block;overflow:hidden;outline:none !important}.irs-line-left,.irs-line-mid,.irs-line-right{position:absolute;display:block;top:0}',
  940. '.irs-line-left{left:0;width:9%}.irs-line-mid{left:9%;width:82%}.irs-line-right{right:0;width:9%}.irs-bar{position:absolute;display:block;left:0;width:0}.irs-bar-edge{position:absolute;display:block;top:0;left:0}',
  941. '.irs-shadow{position:absolute;display:none;left:0;width:0}.irs-slider{position:absolute;display:block;cursor:default;z-index:1}.irs-slider.type_last{z-index:2}.irs-min{position:absolute;display:block;left:0;cursor:default}',
  942. '.irs-max{position:absolute;display:block;right:0;cursor:default}.irs-from,.irs-to,.irs-single{position:absolute;display:block;top:0;left:0;cursor:default;white-space:nowrap}.irs-grid{position:absolute;display:none;bottom:0;left:0;width:100%;height:20px}',
  943. '.irs-with-grid .irs-grid{display:block}.irs-grid-pol{position:absolute;top:0;left:0;width:1px;height:8px;background:#000}.irs-grid-pol.small{height:4px}.irs-grid-text{position:absolute;bottom:0;left:0;white-space:nowrap;text-align:center;font-size:9px;line-height:9px;padding:0 3px;color:#000}',
  944. '.irs-disable-mask{position:absolute;display:block;top:0;left:-1%;width:102%;height:100%;cursor:default;background:rgba(0,0,0,0.0);z-index:2}.lt-ie9 .irs-disable-mask{background:#000;filter:alpha(opacity=0);cursor:not-allowed}.irs-disabled{opacity:0.4}',
  945. '.irs-hidden-input{position:absolute !important;display:block !important;top:0 !important;left:0 !important;width:0 !important;height:0 !important;font-size:0 !important;line-height:0 !important;padding:0 !important;margin:0 !important;outline:none !important;z-index:-9999 !important;background:none !important;border-style:solid !important;border-color:transparent !important}',
  946. '.irs-line-mid,.irs-line-left,.irs-line-right,.irs-bar,.irs-bar-edge,.irs-slider{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQQAAAC0BAMAAACAm0/4AAAAHlBMVEUAAADh5OlIPakuJnU8MZzh5Onh5Onlt8BIPamDg6ND+SBkAAAACnRSTlMAgMzMzHlXE4oe0nCEQQAAAMJJREFUeNrt1qENAkEQhtENkBDkCtCECiiBFjCgEXgMDVwJVEzGQ7KnZnJ5r4JP7E7+1tNJkCBBgoSqCQAAjNg+e6rbq717snt79GSHdu3J9hVGfE8nIVR4jgU+ZYHTVOBAAwAw4pROggQJEiRUTQAAYMRuSl9Rn/whN+UnFJizEiQUSijwKQucpgIHGgCAQatjy7a5tJkkBAlBQpAQJAQJQUJYYkKByQIA/6zPbSYJQUKQECQECUFCkBAkhCUmAMAvX+TSxQIIIKq9AAAAAElFTkSuQmCC") repeat-x}',
  947. '.irs{height:40px}.irs-with-grid{height:60px}.irs-line{height:12px;top:25px}.irs-line-left{height:12px;background-position:0 -30px}',
  948. '.irs-line-mid{height:12px;background-position:0 0}.irs-line-right{height:12px;background-position:100% -30px}.irs-bar{height:12px;top:25px;background-position:0 -60px}',
  949. '.irs-bar-edge{top:25px;height:12px;width:9px;background-position:0 -90px}.irs-shadow{height:3px;top:34px;background:#000;opacity:.25}',
  950. '.lt-ie9 .irs-shadow{filter:alpha(opacity=25)}.irs-slider{width:16px;height:18px;top:22px;background-position:0 -120px}',
  951. '.irs-slider.state_hover,.irs-slider:hover{background-position:0 -150px}.irs-min,.irs-max{color:#fff;font-size:10px;line-height:1.333;text-shadow:none;top:0;padding:1px 3px;background:#7D7E81;-moz-border-radius:4px;border-radius:4px}',
  952. '.irs-from,.irs-to,.irs-single{color:#fff;font-size:10px;line-height:1.333;text-shadow:none;padding:1px 5px;background:#534AA1;-moz-border-radius:4px;border-radius:4px}',
  953. '.irs-from:after,.irs-to:after,.irs-single:after{position:absolute;display:block;content:"";bottom:-6px;left:50%;width:0;height:0;margin-left:-3px;overflow:hidden;border:3px solid transparent;border-top-color:#534AA1}',
  954. '.irs-grid-pol{background:#e1e4e9}.irs-grid-text{color:#999}'
  955. ].join(''));
  956.  
  957. // Settings panel markup
  958. $('body').append([
  959. '<div id="ghe-wrapper">',
  960. '<div id="ghe-popup" class="select-menu-modal-holder js-menu-content js-navigation-container js-active-navigation-container">',
  961. '<div class="select-menu-modal">',
  962. '<div class="select-menu-header">',
  963. '<span class="select-menu-title">',
  964. '<text>Emoji Collections</text>',
  965. '<span class="octicon tooltipped tooltipped-w" aria-label="Change GitHub Custom Emoji Settings">',
  966. '<svg class="octicon-gear" viewBox="0 0 16 14" style="height: 16px; width: 14px;"><path d="M14 8.77V7.17l-1.94-0.64-0.45-1.09 0.88-1.84-1.13-1.13-1.81 0.91-1.09-0.45-0.69-1.92H6.17l-0.63 1.94-1.11 0.45-1.84-0.88-1.13 1.13 0.91 1.81-0.45 1.09L0 7.23v1.59l1.94 0.64 0.45 1.09-0.88 1.84 1.13 1.13 1.81-0.91 1.09 0.45 0.69 1.92h1.59l0.63-1.94 1.11-0.45 1.84 0.88 1.13-1.13-0.92-1.81 0.47-1.09 1.92-0.69zM7 11c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"/></svg>',
  967. '</span>',
  968. '<span class="octicon tooltipped tooltipped-w ghe-back" aria-label="Go back to see all collections">',
  969. '<svg xmlns="http://www.w3.org/2000/svg" width="6.5" height="10" viewBox="0 0 6.5 10"><path d="M5.008 0l1.497 1.504-3.76 3.49 3.743 3.51L4.984 10l-4.99-5.013L5.01 0z"/></svg>',
  970. '</span>',
  971. '</span>',
  972. '</div>',
  973. '<div class="js-select-menu-deferred-content ghe-content">',
  974. '<div class="select-menu-list ghe-all-collections"></div>',
  975. '<div class="select-menu-list ghe-single-collection"></div>',
  976. '</div>',
  977. '</div>',
  978. '</div>',
  979. '<div id="ghe-settings">',
  980. '<div id="ghe-settings-inner" class="boxed-group">',
  981. '<h3>GitHub Custom Emoji Settings',
  982. '<svg id="ghe-settings-close" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="160 160 608 608"><path d="M686.2 286.8L507.7 465.3l178.5 178.5-45 45-178.5-178.5-178.5 178.5-45-45 178.5-178.5-178.5-178.5 45-45 178.5 178.5 178.5-178.5z"/></svg>',
  983. '</h3>',
  984. '<div class="boxed-group-inner">',
  985. '<form>',
  986. '<div class="ghe-settings-wrapper">',
  987. '<p>',
  988. '<label>Insert as Image:',
  989. '<sup class="tooltipped tooltipped-e" aria-label="Or Shift + select the emoji">?</sup>',
  990. '<input class="ghe-image ghe-checkbox ghe-right" type="checkbox">',
  991. '</label>',
  992. '</p>',
  993. '<p class="checkbox">',
  994. '<label>Case Sensitive <input class="ghe-case ghe-checkbox ghe-right" type="checkbox"></label>',
  995. '</p>',
  996. '<div class="ghe-slider-wrapper">',
  997. '<div class="ghe-range-slider">',
  998. '<input type="text" class="ghe-height" value="" />',
  999. '</div>',
  1000. '<label>Emoji Height',
  1001. '<sup class="tooltipped tooltipped-e" aria-label="Set emoji minimum & maximum&#10;height in pixels">?</sup>',
  1002. '</label>',
  1003. '</div>',
  1004. '<div class="ghe-slider-wrapper">',
  1005. '<div class="ghe-zoom-slider">',
  1006. '<input class="ghe-zoom ghe-right" type="text">',
  1007. '</div>',
  1008. '<label>Emoji Zoom',
  1009. '<sup class="tooltipped tooltipped-e" aria-label="Set Emoji zoom factor&#10;while actively clicked">?</sup>',
  1010. '</label>',
  1011. '</div>',
  1012. '<p>',
  1013. '<hr>',
  1014. '<h3>Sources',
  1015. '<a href="https://github.com/StylishThemes/GitHub-Custom-Emojis/wiki/Add-Emojis" class="tooltipped tooltipped-e tooltipped-multiline" aria-label="Click to get more details on how to set up an Emoji source JSON file">',
  1016. '<sup>?</sup>',
  1017. '</a>',
  1018. '</h3>',
  1019. '<div class="ghe-sources"></div>',
  1020. '</p>',
  1021. '</div>',
  1022. '<div class="ghe-footer">',
  1023. '<div class="btn-group">',
  1024. '<a href="#" id="ghe-add-source" class="btn btn-sm">Add Source</a>',
  1025. '<a href="#" id="ghe-refresh-sources" class="btn btn-sm">Refresh Sources</a>&nbsp;',
  1026. '</div>',
  1027. '<a href="#" id="ghe-restore" class="btn btn-sm btn-danger tooltipped tooltipped-n ghe-right" aria-label="Default sources are restored;&#10;other source will remain">Restore Defaults</a>',
  1028. '</div>',
  1029. '</form>',
  1030. '</div>',
  1031. '</div>',
  1032. '</div>',
  1033. '</div>'
  1034. ].join(''));
  1035. },
  1036.  
  1037. // JSON source inputs
  1038. sourceHTML : [
  1039. '<div class="ghe-source">',
  1040. '<input class="ghe-source-input" type="text" value="" placeholder="Add JSON sources only">',
  1041. '<a href="#" class="ghe-remove btn btn-sm btn-danger">',
  1042. '<svg class="ghe-remove-icon" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="160 160 608 608" fill="currentColor"><path d="M686.2 286.8L507.7 465.3l178.5 178.5-45 45-178.5-178.5-178.5 178.5-45-45 178.5-178.5-178.5-178.5 45-45 178.5 178.5 178.5-178.5z"/></svg>',
  1043. '</a>',
  1044. '</div>'
  1045. ].join(''),
  1046.  
  1047. setRegex : function() {
  1048. var isCS = this.settings.caseSensitive,
  1049. // parts = [':_', ':']
  1050. imgParts = this.vars.emojiImgTemplate.split('${name}'),
  1051. txtParts = this.vars.emojiTxtTemplate.split('${name}');
  1052.  
  1053. // filter = /:_([a-zA-Z\u00c0-\u00ff0-9_,'.+-]*)$|:_([^\x00-\xff]*)$/gi
  1054. // used by atwho.js autocomplete
  1055. this.regex.emojiImgFilter = new RegExp(
  1056. imgParts[0] + '([a-zA-Z\u00c0-\u00ff0-9_,\'\.\+\-]*)$|' +
  1057. imgParts[0] + '([^\\x00-\\xff]*)$',
  1058. (isCS ? 'g' : 'gi')
  1059. );
  1060.  
  1061. this.regex.emojiTxtFilter = new RegExp(
  1062. txtParts[0] + '([a-zA-Z\u00c0-\u00ff0-9_,\'\.\+\-]*)$|' +
  1063. txtParts[0] + '([^\\x00-\\xff]*)$',
  1064. (isCS ? 'g' : 'gi')
  1065. );
  1066.  
  1067. // used by search & replace
  1068. this.regex.nameRegex = new RegExp(
  1069. imgParts[0] + '([\\w_]+)' + imgParts[1],
  1070. (isCS ? 'g' : 'gi')
  1071. );
  1072. },
  1073.  
  1074. init : function() {
  1075. debug('GitHub-Emoji Script initializing!');
  1076.  
  1077. // add style tag to head
  1078. this.$style = $('<style class="ghe-style">').appendTo('head');
  1079.  
  1080. this.getStoredValues();
  1081. this.loadEmojiJson();
  1082. this.updateStyleSheet();
  1083. this.isUpdating = true;
  1084. // regex based on case sensitive setting
  1085. this.setRegex();
  1086.  
  1087. var targets = document.querySelectorAll(this.containers.join(','));
  1088. Array.prototype.forEach.call(targets, function(target) {
  1089. new MutationObserver(function(mutations) {
  1090. mutations.forEach(function(mutation) {
  1091. // preform checks before adding code wrap to minimize function calls
  1092. if (mutation.target === target && !$.isEmptyObject(ghe.collections) &&
  1093. !(ghe.isUpdating || target.querySelector('.ghe-processed'))) {
  1094. ghe.update();
  1095. }
  1096. });
  1097. }).observe(target, {
  1098. childList : true,
  1099. subtree : true
  1100. });
  1101. });
  1102.  
  1103. this.addPanels();
  1104.  
  1105. // Add emoji autocomplete & watch for preview rendering
  1106. this.addToolbarIcon();
  1107. this.addBindings();
  1108. // update panel values after bindings (rangeslider)
  1109. this.setStoredValues();
  1110.  
  1111. // checkPage clears isUpdating flag
  1112. this.checkPage();
  1113. }
  1114. };
  1115.  
  1116. // add style at document-start
  1117. ghe.init();
  1118.  
  1119. // include a "?debug" anywhere in the browser URL to enable debugging
  1120. function debug() {
  1121. if (/\?debug/.test(window.location.href)) {
  1122. console.log.apply(console, arguments);
  1123. }
  1124. }
  1125. })(jQuery.noConflict(true));