GitHub Custom Emojis

Add custom emojis from json source

目前为 2016-03-18 提交的版本。查看 最新版本

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