GitHub Custom Emojis

Add custom emojis from json source

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