GitHub Custom Emojis

Add custom emojis from json source

目前為 2016-03-30 提交的版本,檢視 最新版本

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