GitHub Custom Emojis

Add custom emojis from json source

当前为 2016-03-14 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Custom Emojis
  3. // @version 0.2.0
  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'
  77. ],
  78.  
  79. // mutant observers to disconnect after ajax load
  80. previewObserver : [],
  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. setupPreviews : function() {
  518. // Add mutant observer to previews
  519. var previews = document.querySelectorAll('.preview-content .comment-body');
  520. if (ghe.previewObserver.length) {
  521. // disconnect previous observers
  522. $.each(ghe.previewObserver, function() {
  523. this.disconnect();
  524. });
  525. ghe.previewObserver = [];
  526. }
  527. Array.prototype.forEach.call(previews, function(target) {
  528. var obs = new MutationObserver(function(mutations) {
  529. mutations.forEach(function(mutation) {
  530. // preform checks before adding code wrap to minimize function calls
  531. if (mutation.target === target && !ghe.isUpdating) {
  532. ghe.checkPage();
  533. }
  534. });
  535. });
  536. obs.observe(target, {
  537. childList : true,
  538. subtree : false
  539. });
  540. ghe.previewObserver[ghe.previewObserver.length] = obs;
  541. });
  542. },
  543.  
  544. addToolbarIcon : function() {
  545. // add Emoji setting icons
  546. var indx, $el,
  547. $toolbars = $('.toolbar-commenting'),
  548. len = $toolbars.length;
  549. for (indx = 0; indx < len; indx++) {
  550. $el = $toolbars.eq(indx);
  551. if (!$el.find('.ghe-settings-icon').length) {
  552. $el.prepend([
  553. '<button type="button" class="ghe-settings-open toolbar-item tooltipped tooltipped-n tooltipped-multiline" aria-label="Browse collections & Set Emojis Options" tabindex="-1">',
  554. '<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">',
  555. '<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"/>',
  556. '<path d="M.878 8.777s3.167 1.893 8.002 1.92c4.365.02 8.135-1.92 8.135-1.92"/>',
  557. '</svg>',
  558. '</button>'
  559. ].join(''));
  560. }
  561. }
  562. },
  563.  
  564. // dynamic stylesheet
  565. updateStyleSheet : function() {
  566. var range = this.settings.rangeHeight.split(';');
  567. ghe.$style.text([
  568. // img styling - vertically center with set height range
  569. '.atwho-view li img, #ghe-popup .select-menu-item img, img[alt="ghe-emoji"], .' +
  570. this.vars.emojiClass + ' { ' +
  571. 'margin-bottom:.25em; vertical-align:middle; ' +
  572. 'min-height: ' + (range[0] || 'none') + 'px;' +
  573. 'max-height: ' + (range[1] || 'none') + 'px }',
  574. // click (make active) on image to zoom
  575. '.' + this.vars.emojiClass + ':active, a:active img[alt="ghe-emoji"] { zoom:' +
  576. this.settings.activeZoom + ' }'
  577. ].join(''));
  578. },
  579.  
  580. addBindings : function() {
  581. var lastKey,
  582. $popup = $('#ghe-popup'),
  583. $settings = $('#ghe-settings');
  584. // Delegated bindings
  585. $('body')
  586. .on('click', '.ghe-settings-open', function() {
  587. // open all collections panel
  588. ghe.openCollections($(this));
  589. return false;
  590. })
  591. .on('click', '.ghe-collection', function() {
  592. // open targeted collection
  593. var name = $(this).attr('data-group');
  594. ghe.showCollection(name);
  595. })
  596. .on('click', '.ghe-emoji', function(e) {
  597. // click on emoji in collection to add to textarea
  598. ghe.addEmoji(e, $(this));
  599. })
  600. .on('click keypress keydown', function(e) {
  601. clearTimeout(ghe.timer);
  602. var panelVisible = $popup.hasClass('in') || $settings.hasClass('in'),
  603. openPanel = ghe.vars.keyboardOpen.split('+'),
  604. key = String.fromCharCode(e.which).toLowerCase();
  605. // press escape or click outside to close the panel
  606. if (panelVisible && e.which === 27 || e.type === 'click' && !$(e.target).closest('#ghe-wrapper').length) {
  607. ghe.closePanels();
  608. return;
  609. }
  610. // keydown is only needed for escape key detection
  611. if (e.type === 'keydown' || /(input|textarea)/i.test(document.activeElement.nodeName)) {
  612. return;
  613. }
  614. // shortcut keys need keypress
  615. if (lastKey === openPanel[0] && key === openPanel[1]) {
  616. if ($settings.hasClass('in')) {
  617. ghe.closePanels();
  618. } else {
  619. ghe.openSettings();
  620. }
  621. }
  622. lastKey = key;
  623. ghe.timer = setTimeout(function() {
  624. lastKey = null;
  625. }, ghe.vars.keyboardDelay);
  626.  
  627. // add shortcut to help menu
  628. if (key === '?') {
  629. // table doesn't exist until user presses "?"
  630. setTimeout(function() {
  631. if (!$('.ghe-shortcut').length) {
  632. $('.keyboard-mappings:eq(0) tbody:eq(0)').append([
  633. '<tr class="ghe-shortcut">',
  634. '<td class="keys">',
  635. '<kbd>' + openPanel[0] + '</kbd> <kbd>' + openPanel[1] + '</kbd>',
  636. '</td>',
  637. '<td>GitHub Emojis: open settings</td>',
  638. '</tr>'
  639. ].join(''));
  640. }
  641. }, 300);
  642. }
  643. });
  644.  
  645. // popup & settings interactions
  646. $('#ghe-popup .octicon-gear').on('click keyup', function(e) {
  647. if (e.type === 'keyup' && e.which !== 13) {
  648. return;
  649. }
  650. ghe.openSettings();
  651. });
  652. $('#ghe-settings, #ghe-settings-close, #ghe-settings-inner').on('click', function(e) {
  653. if (this.id === 'ghe-settings-inner') {
  654. e.stopPropagation();
  655. } else {
  656. ghe.closePanels();
  657. }
  658. });
  659. // ghe-checkbox added to checkboxes
  660. $('.ghe-checkbox').on('change', function() {
  661. ghe.updateSettings();
  662. });
  663. // go back - switch from single collection to showing all collections
  664. $('#ghe-popup .ghe-back').on('click', function(){
  665. $('.ghe-single-collection, .ghe-back').hide();
  666. $('.ghe-all-collections').show();
  667. });
  668.  
  669. // add new source input
  670. $('#ghe-add-source').on('click', function() {
  671. var $panel = $('#ghe-settings-inner');
  672. // lets not get crazy!
  673. if ($panel.find('.ghe-source').length < 20) {
  674. $(ghe.sourceHTML).appendTo($panel.find('.ghe-sources'));
  675. }
  676. return false;
  677. });
  678. $('#ghe-refresh-sources, #ghe-restore').on('click', function() {
  679. // update sources from settings panel
  680. ghe.setStoredValues(this.id === 'ghe-restore');
  681. // load json files
  682. ghe.loadEmojiJson(true);
  683. return false;
  684. });
  685.  
  686. // Init range slider
  687. $('.ghe-height')
  688. .val(ghe.settings.rangeHeight)
  689. .ionRangeSlider({
  690. type : 'double',
  691. min : 0,
  692. max : ghe.vars.maxEmojiHeight,
  693. onChange : function() {
  694. ghe.updateSettings();
  695. },
  696. force_edges : true,
  697. hide_min_max : true
  698. });
  699. $('.ghe-zoom')
  700. .val(ghe.settings.activeZoom)
  701. .ionRangeSlider({
  702. min : 0,
  703. max : ghe.vars.maxEmojiZoom,
  704. step : 0.1,
  705. onChange : function() {
  706. ghe.updateSettings();
  707. },
  708. force_edges : true,
  709. hide_min_max : true
  710. });
  711.  
  712. // Remove source input - delegated binding
  713. $('.ghe-settings-wrapper')
  714. .on('click', '.ghe-remove', function(e) {
  715. var $wrapper = $(this).closest('.ghe-source'),
  716. url = $wrapper.find('.ghe-source-input').attr('data-url');
  717. ghe.removeSource(url);
  718. $wrapper.remove();
  719. ghe.setStoredValues();
  720. return false;
  721. })
  722. .on('focus blur input change', '.ghe-source-input', function(e) {
  723. if (ghe.busy) { return; }
  724. ghe.busy = true;
  725. var val,
  726. $this = $(this);
  727. switch (e.type) {
  728. case 'focus':
  729. case 'focusin':
  730. // show entire url when focused
  731. $this.val( $this.attr('data-url') );
  732. break;
  733. case 'blur':
  734. case 'focusout':
  735. ghe.showFileName($this);
  736. break;
  737. default:
  738. $this.attr('data-url', $this.val());
  739. }
  740. if (e.type === 'change' || e.which === 13) {
  741. val = $this.val();
  742. $this.attr('data-url', val);
  743. ghe.fetchCustomEmojis(val);
  744. }
  745. ghe.busy = false;
  746. });
  747.  
  748. // initialize autocomplete that add emojis, but only on focus
  749. // since every comment has a hidden textarea
  750. $('body').on('focus', '.comment-form-textarea', function() {
  751. ghe.initAutocomplete($(this));
  752. });
  753. },
  754.  
  755. showFileName : function($el) {
  756. var str = $el.attr('data-url'),
  757. v = str.substring( str.lastIndexOf('/') + 1, str.length );
  758. // show only the file name in the input when blurred
  759. // unless there is no file name
  760. $el.val(v === '' ? str : '...' + v);
  761. },
  762.  
  763. closePanels : function() {
  764. $('#ghe-popup').removeClass('in');
  765. $('#ghe-settings').removeClass('in');
  766. ghe.$currentInput = null;
  767. },
  768.  
  769. openSettings : function() {
  770. $('.modal-backdrop').click();
  771. $('#ghe-settings').addClass('in');
  772. },
  773.  
  774. openCollections : function($el) {
  775. ghe.addCollections();
  776. var pos = $el.offset();
  777. $('#ghe-settings').removeClass('in');
  778. $('#ghe-popup')
  779. .addClass('in')
  780. .css({
  781. left: pos.left + 25,
  782. top: pos.top
  783. });
  784. ghe.$currentInput = $el.closest('.previewable-comment-form').find('.comment-form-textarea');
  785. },
  786.  
  787. addCollections : function() {
  788. var indx, len, key, group, item, emoji,
  789. collections = ghe.collections,
  790. range = ghe.settings.rangeHeight.split(';'),
  791. list = [],
  792. items = [];
  793. // build collections list -
  794. for (key in collections) {
  795. if (collections.hasOwnProperty(key)) {
  796. list[list.length] = key;
  797. }
  798. }
  799. list = list.sort(function(a, b) {
  800. return a > b ? 1 : (a < b ? -1 : 0);
  801. });
  802. len = list.length;
  803. // add random image from group
  804. for (indx = 0; indx < len; indx++) {
  805. group = collections[list[indx]];
  806. // random image (skip first entry)
  807. item = Math.round(Math.random() * (group.length - 2)) + 1;
  808. emoji = group[item];
  809. items[items.length] = '<div class="select-menu-item js-navigation-item ghe-collection' +
  810. (emoji.url ? '' : ' ghe-text-collection') +
  811. '" data-group="' + list[indx] + '">' +
  812. // collection info stored in first entry
  813. group[0].name + ' <span class="ghe-right' +
  814. (emoji.url ?
  815. // images
  816. '"><img src="' + emoji.url + '" title="' +
  817. ghe.vars.emojiImgTemplate.replace(ghe.regex.template, emoji.name) + '" style="' +
  818. 'min-height:' + (range[0] || 'none') + 'px;' +
  819. 'max-height:' + (range[1] || 'none') + 'px;">' :
  820. // text
  821. ' ghe-text" title="' + emoji.name + '" style="font-size:' + group[0].previewSize +
  822. '">' + emoji.text
  823. ) + '</span></div>';
  824. }
  825. $('.ghe-single-collection, .ghe-back').hide();
  826. $('.ghe-all-collections').html(items.join('')).show();
  827. },
  828.  
  829. showCollection : function(name) {
  830. var indx, emoji,
  831. range = ghe.settings.rangeHeight.split(';'),
  832. group = ghe.collections[name].slice(1).sort(function(a, b) {
  833. return a.name > b.name ? 1 : ( a.name < b.name ? -1 : 0 );
  834. }),
  835. list = [],
  836. len = group.length;
  837. for (indx = 1; indx < len; indx++) {
  838. emoji = group[indx];
  839. list[indx - 1] = '<div class="select-menu-item js-navigation-item ghe-emoji' +
  840. (emoji.url ? '' : ' ghe-text-emoji') +
  841. '" data-name="' + emoji.name + '">' +
  842. emoji.name + '<span class="ghe-right' +
  843. (emoji.url ?
  844. // images
  845. '"><img src="' + emoji.url + '" style="' +
  846. 'min-height:' + (range[0] || 'none') + 'px;' +
  847. 'max-height:' + (range[1] || 'none') + 'px">' :
  848. // text type
  849. ' ghe-text" style="font-size:' + ghe.collections[name][0].previewSize +
  850. // data-emoji needed because Chrome emoji-one extension adds hidden
  851. // text inside the span when it replaces the text with an svg
  852. '" data-emoji="' + emoji.text + '">' + emoji.text
  853. ) + '</span></div>';
  854. }
  855. $('.ghe-all-collections').hide();
  856. $('.ghe-single-collection').html(list.join('')).show();
  857. $('.ghe-back').show();
  858. },
  859.  
  860. // add emoji from collection
  861. addEmoji : function(e, $el) {
  862. var val, emoji,
  863. $img = $el.find('img'),
  864. name = $el.attr('data-name'),
  865. caretPos = ghe.$currentInput.caret('pos');
  866. if ($img.length) {
  867. // insert into textarea
  868. if (e.shiftKey || ghe.settings.insertAsImage) {
  869. // add image tag directly if shift is held;
  870. // GitHub does NOT allow class names so we are forced to use alt
  871. emoji = '<img alt="ghe-emoji" title="' +
  872. ghe.vars.emojiImgTemplate.replace(ghe.regex.template, name) +
  873. '" src="' + $el.find('img').attr('src') + '">';
  874. } else {
  875. emoji = ghe.vars.emojiImgTemplate.replace(ghe.regex.template, name);
  876. }
  877. } else {
  878. // insert text emoji
  879. emoji = $el.find('span').attr('data-emoji');
  880. }
  881. val = ghe.$currentInput.val();
  882. ghe.$currentInput
  883. .val(val.slice(0, caretPos) + emoji + ' ' + val.slice(caretPos))
  884. .focus()
  885. .caret('pos', caretPos + emoji.length + 1);
  886. ghe.closePanels();
  887. },
  888.  
  889. removeSource : function(url) {
  890. var indx,
  891. list = [],
  892. collections = this.collections,
  893. sources = this.settings.sources,
  894. len = sources.length;
  895. // remove from source
  896. for (indx = 0; indx < len; indx++) {
  897. if (sources[indx] !== url) {
  898. list[list.length] = sources[indx];
  899. }
  900. }
  901. this.settings.sources = list;
  902. for (indx in collections) {
  903. if (collections.hasOwnProperty(indx) && collections[indx][0].url === url) {
  904. delete collections[indx];
  905. debug('Removing "' + indx + '" collection', collections);
  906. }
  907. }
  908. },
  909.  
  910. update : function() {
  911. this.isUpdating = true;
  912. this.setupPreviews();
  913. this.addToolbarIcon();
  914. // checkPage clears isUpdating flag
  915. this.checkPage();
  916. },
  917.  
  918. addPanels : function() {
  919. /* https://github.com/ichord/At.js styles for autocomplete */
  920. GM_addStyle([
  921. // settings panel
  922. '#ghe-menu:hover { cursor:pointer }',
  923. '#ghe-settings { position:fixed; z-index:65535; top:0; bottom:0; left:0; right:0; opacity:0; visibility:hidden }',
  924. '#ghe-settings.in { opacity:1; visibility:visible; background:rgba(0,0,0,.5) }',
  925. '#ghe-settings-inner { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); width:25rem; box-shadow:0 .5rem 1rem #111; color:#c0c0c0 }',
  926. '#ghe-settings label { margin-left:.5rem; position:relative; top:-1px }',
  927. '#ghe-settings .ghe-remove { float:right; margin-top:2px; padding:4px; cursor:pointer }',
  928. '#ghe-settings .ghe-remove-icon { position:relative; top:3px }',
  929. '#ghe-settings-close { fill:#666; float:right; cursor:pointer }',
  930. '#ghe-settings-close:hover { fill:#ccc }',
  931. '#ghe-settings .ghe-settings-wrapper { max-height:60vh; overflow-y:auto; padding: 1px 10px }',
  932. '#ghe-settings .ghe-right, #ghe-popup .ghe-right { float:right }',
  933. '#ghe-settings p { line-height:25px; }',
  934. '#ghe-settings .checkbox input { margin-top:.35em }',
  935. '#ghe-settings input[type="checkbox"] { width:16px !important; height:16px !important; border-radius:3px !important }',
  936. '#ghe-settings .boxed-group-inner { padding:0; }',
  937. '#ghe-settings .ghe-footer { padding: 10px; border-top: #555 solid 1px; }',
  938. '#ghe-settings .ghe-min-height, #ghe-settings .ghe-max-height, .ghe-zoom { width: 5em; }',
  939. '#ghe-settings .ghe-source-input { width: 90%; }',
  940. '#ghe-settings .ghe-slider-wrapper { height:40px; }',
  941. '#ghe-settings .ghe-slider-wrapper label { position:relative; top:22px }',
  942. '#ghe-settings .ghe-range-slider, #ghe-settings .ghe-zoom-slider { position:relative; height:40px; width:250px; float:right }',
  943.  
  944. // show emoji collections
  945. '#ghe-popup { display:none }',
  946. '#ghe-popup .ghe-content, #ghe-popup .ghe-content > div { max-height: 200px }',
  947. '#ghe-popup .octicon-gear { margin-left:4px }',
  948. '#ghe-popup .ghe-back svg { height:20px; padding:4px 14px 4px 4px }',
  949. '#ghe-popup .select-menu-item { font-size:1.1em; font-weight:bold; line-height:40px; padding:8px }',
  950. '#ghe-popup .select-menu-item.ghe-text-emoji { line-height:inherit; position:relative; padding-right:45px }',
  951. '#ghe-popup .select-menu-item.ghe-text-emoji .ghe-text { position:absolute; right:10px; top:0 }',
  952. '#ghe-popup .select-menu-item .ghe-text, .atwho-view .ghe-text { font-size:1.6em }',
  953. '.ghe-settings-icon, #ghe-popup.in { display:inline-block }',
  954.  
  955. // autocomplete popup in comment
  956. '.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 }',
  957. '.atwho-view .navigation-focus { background:#36f; color:#fff }',
  958. '.atwho-view .navigation-focus small { color:#fff }',
  959. '.atwho-view strong { color:#36F }',
  960. '.atwho-view .navigation-focus strong { color:#fff; font:700 }',
  961. '.atwho-view ul { list-style:none; padding:0; margin:auto }',
  962. '.atwho-view ul li { display:block; padding:5px 10px; border-bottom:1px solid #ddd; cursor:pointer }',
  963. '.atwho-view li span { display:inline-block; min-width:60px; padding-right:4px }',
  964. '.atwho-view small { font-size:smaller; color:#777; font-weight:400 }',
  965.  
  966. // rangeSlider
  967. '.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}',
  968. '.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}',
  969. '.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}',
  970. '.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}',
  971. '.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}',
  972. '.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}',
  973. '.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}',
  974. '.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}',
  975. '.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}',
  976. '.irs{height:40px}.irs-with-grid{height:60px}.irs-line{height:12px;top:25px}.irs-line-left{height:12px;background-position:0 -30px}',
  977. '.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}',
  978. '.irs-bar-edge{top:25px;height:12px;width:9px;background-position:0 -90px}.irs-shadow{height:3px;top:34px;background:#000;opacity:.25}',
  979. '.lt-ie9 .irs-shadow{filter:alpha(opacity=25)}.irs-slider{width:16px;height:18px;top:22px;background-position:0 -120px}',
  980. '.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}',
  981. '.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}',
  982. '.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}',
  983. '.irs-grid-pol{background:#e1e4e9}.irs-grid-text{color:#999}'
  984. ].join(''));
  985.  
  986. // Settings panel markup
  987. $('body').append([
  988. '<div id="ghe-wrapper">',
  989. '<div id="ghe-popup" class="select-menu-modal-holder js-menu-content js-navigation-container js-active-navigation-container">',
  990. '<div class="select-menu-modal">',
  991. '<div class="select-menu-header">',
  992. '<span class="select-menu-title">',
  993. '<text>Emoji Collections</text>',
  994. '<span class="octicon tooltipped tooltipped-w" aria-label="Change GitHub Custom Emoji Settings">',
  995. '<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>',
  996. '</span>',
  997. '<span class="octicon tooltipped tooltipped-w ghe-back" aria-label="Go back to see all collections">',
  998. '<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>',
  999. '</span>',
  1000. '</span>',
  1001. '</div>',
  1002. '<div class="js-select-menu-deferred-content ghe-content">',
  1003. '<div class="select-menu-list ghe-all-collections"></div>',
  1004. '<div class="select-menu-list ghe-single-collection"></div>',
  1005. '</div>',
  1006. '</div>',
  1007. '</div>',
  1008. '<div id="ghe-settings">',
  1009. '<div id="ghe-settings-inner" class="boxed-group">',
  1010. '<h3>GitHub Custom Emoji Settings',
  1011. '<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>',
  1012. '</h3>',
  1013. '<div class="boxed-group-inner">',
  1014. '<form>',
  1015. '<div class="ghe-settings-wrapper">',
  1016. '<p>',
  1017. '<label>Insert as Image:',
  1018. '<sup class="tooltipped tooltipped-e" aria-label="Or Shift + select the emoji">?</sup>',
  1019. '<input class="ghe-image ghe-checkbox ghe-right" type="checkbox">',
  1020. '</label>',
  1021. '</p>',
  1022. '<p class="checkbox">',
  1023. '<label>Case Sensitive <input class="ghe-case ghe-checkbox ghe-right" type="checkbox"></label>',
  1024. '</p>',
  1025. '<div class="ghe-slider-wrapper">',
  1026. '<div class="ghe-range-slider">',
  1027. '<input type="text" class="ghe-height" value="" />',
  1028. '</div>',
  1029. '<label>Emoji Height',
  1030. '<sup class="tooltipped tooltipped-e" aria-label="Set emoji minimum & maximum&#10;height in pixels">?</sup>',
  1031. '</label>',
  1032. '</div>',
  1033. '<div class="ghe-slider-wrapper">',
  1034. '<div class="ghe-zoom-slider">',
  1035. '<input class="ghe-zoom ghe-right" type="text">',
  1036. '</div>',
  1037. '<label>Emoji Zoom',
  1038. '<sup class="tooltipped tooltipped-e" aria-label="Set Emoji zoom factor&#10;while actively clicked">?</sup>',
  1039. '</label>',
  1040. '</div>',
  1041. '<p>',
  1042. '<hr>',
  1043. '<h3>Sources',
  1044. '<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">',
  1045. '<sup>?</sup>',
  1046. '</a>',
  1047. '</h3>',
  1048. '<div class="ghe-sources"></div>',
  1049. '</p>',
  1050. '</div>',
  1051. '<div class="ghe-footer">',
  1052. '<div class="btn-group">',
  1053. '<a href="#" id="ghe-add-source" class="btn btn-sm">Add Source</a>',
  1054. '<a href="#" id="ghe-refresh-sources" class="btn btn-sm">Refresh Sources</a>&nbsp;',
  1055. '</div>',
  1056. '<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>',
  1057. '</div>',
  1058. '</form>',
  1059. '</div>',
  1060. '</div>',
  1061. '</div>',
  1062. '</div>'
  1063. ].join(''));
  1064. },
  1065.  
  1066. // JSON source inputs
  1067. sourceHTML : [
  1068. '<div class="ghe-source">',
  1069. '<input class="ghe-source-input" type="text" value="" placeholder="Add JSON sources only">',
  1070. '<a href="#" class="ghe-remove btn btn-sm btn-danger">',
  1071. '<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>',
  1072. '</a>',
  1073. '</div>'
  1074. ].join(''),
  1075.  
  1076. setRegex : function() {
  1077. var isCS = this.settings.caseSensitive,
  1078. // parts = [':_', ':']
  1079. imgParts = this.vars.emojiImgTemplate.split('${name}'),
  1080. txtParts = this.vars.emojiTxtTemplate.split('${name}');
  1081.  
  1082. // filter = /:_([a-zA-Z\u00c0-\u00ff0-9_,'.+-]*)$|:_([^\x00-\xff]*)$/gi
  1083. // used by atwho.js autocomplete
  1084. this.regex.emojiImgFilter = new RegExp(
  1085. imgParts[0] + '([a-zA-Z\u00c0-\u00ff0-9_,\'\.\+\-]*)$|' +
  1086. imgParts[0] + '([^\\x00-\\xff]*)$',
  1087. (isCS ? 'g' : 'gi')
  1088. );
  1089.  
  1090. this.regex.emojiTxtFilter = new RegExp(
  1091. txtParts[0] + '([a-zA-Z\u00c0-\u00ff0-9_,\'\.\+\-]*)$|' +
  1092. txtParts[0] + '([^\\x00-\\xff]*)$',
  1093. (isCS ? 'g' : 'gi')
  1094. );
  1095.  
  1096. // used by search & replace
  1097. this.regex.nameRegex = new RegExp(
  1098. imgParts[0] + '([\\w_]+)' + imgParts[1],
  1099. (isCS ? 'g' : 'gi')
  1100. );
  1101. },
  1102.  
  1103. init : function() {
  1104. debug('GitHub-Emoji Script initializing!');
  1105.  
  1106. // add style tag to head
  1107. this.$style = $('<style class="ghe-style">').appendTo('head');
  1108.  
  1109. this.getStoredValues();
  1110. this.loadEmojiJson();
  1111. this.updateStyleSheet();
  1112. this.isUpdating = true;
  1113. // regex based on case sensitive setting
  1114. this.setRegex();
  1115.  
  1116. var targets = document.querySelectorAll(this.containers.join(','));
  1117. Array.prototype.forEach.call(targets, function(target) {
  1118. new MutationObserver(function(mutations) {
  1119. mutations.forEach(function(mutation) {
  1120. // preform checks before adding code wrap to minimize function calls
  1121. if (mutation.target === target && !$.isEmptyObject(ghe.collections) &&
  1122. !(ghe.isUpdating || target.querySelector('.ghe-processed'))) {
  1123. ghe.update();
  1124. }
  1125. });
  1126. }).observe(target, {
  1127. childList : true,
  1128. subtree : true
  1129. });
  1130. });
  1131.  
  1132. this.addPanels();
  1133.  
  1134. // Add emoji autocomplete & watch for preview rendering
  1135. this.setupPreviews();
  1136. this.addToolbarIcon();
  1137. this.addBindings();
  1138. // update panel values after bindings (rangeslider)
  1139. this.setStoredValues();
  1140.  
  1141. // checkPage clears isUpdating flag
  1142. this.checkPage();
  1143. }
  1144. };
  1145.  
  1146. // add style at document-start
  1147. ghe.init();
  1148.  
  1149. // include a "?debug" anywhere in the browser URL to enable debugging
  1150. function debug() {
  1151. if (/\?debug/.test(window.location.href)) {
  1152. console.log.apply(console, arguments);
  1153. }
  1154. }
  1155. })(jQuery.noConflict(true));