shortcut.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // shortcut suggest functionality
  2. // auto attaches to all [with-shortcuts] elements
  3. (function() {
  4. let input = null, menu = null, options = [], index = -1;
  5. let backtrackAfterApplying = false;
  6. let strPart = '';
  7. function getCaretPos(win) {
  8. win = win || window;
  9. let doc = win.document;
  10. let sel, range, rects, rect;
  11. let x = 0, y = 0;
  12. if (win.getSelection) { // won't work if getSelection() isn't available!
  13. sel = win.getSelection();
  14. if(sel.toString() !== '') return null; // won't work if there isa
  15. if (sel.rangeCount) {
  16. range = sel.getRangeAt(0).cloneRange();
  17. if (range.getClientRects) {
  18. range.collapse(true);
  19. let span = doc.createElement("span");
  20. if (span.getClientRects) {
  21. // Ensure span has dimensions and position by
  22. // adding a zero-width space character
  23. span.appendChild( doc.createTextNode("\u200bXX") );
  24. range.insertNode(span);
  25. rect = span.getClientRects()[0];
  26. x = rect.left;
  27. y = rect.top;
  28. let spanParent = span.parentNode;
  29. spanParent.removeChild(span);
  30. // Glue any broken text nodes back together
  31. spanParent.normalize();
  32. return [x, y];
  33. }
  34. return null
  35. }
  36. }
  37. }
  38. return { x: x, y: y };
  39. }
  40. function show(_initial = false, _options) {
  41. let pos = getCaretPos();
  42. // strPart = '';
  43. if(pos) {
  44. index = -1;
  45. options = _options;
  46. if(strPart.length > 1) {
  47. options = _options.filter(function(_x) {
  48. return _x.name.toLowerCase().indexOf(strPart.substr(1).toLowerCase()) !== -1;
  49. });
  50. }
  51. menu.empty();
  52. for(let i = 0; i < options.length; i++) {
  53. menu.append(
  54. $('<div/>')
  55. .addClass('sc')
  56. .text(options[i].name)
  57. .attr('title', options[i].value)
  58. );
  59. }
  60. if(_initial) {
  61. menu
  62. .css({
  63. left: pos[0] + 'px',
  64. top: (pos[1] + $(window).scrollTop()) + 'px',
  65. })
  66. .show();
  67. document.execCommand("insertText", true, '@');
  68. document.execCommand("delete", true, null);
  69. }
  70. }
  71. }
  72. function discard() {
  73. if($('.stag-shortcuts:visible').length) {
  74. $('.stag-shortcuts').hide();
  75. return false;
  76. }
  77. }
  78. function highlightOption() {
  79. menu.find('.sc').removeClass('active');
  80. if(options && options.length && index >= 0 && index < options.length) {
  81. menu.find('.sc:eq(' + index + ')').addClass('active');
  82. }
  83. }
  84. function apply(_clearReturn = false) {
  85. if(input && options && options.length && index >= 0 && index < options.length) {
  86. // $(input).focus();
  87. if(backtrackAfterApplying) {
  88. for (let i = 0; i < strPart.length; i++) {
  89. document.execCommand("delete", true, null);
  90. }
  91. }
  92. // if(_clearReturn) document.execCommand("delete", true, null);
  93. document.execCommand("insertText", true, options[index].value);
  94. discard();
  95. }
  96. }
  97. function isVisible() {
  98. return !!$('.stag-shortcuts:visible').length;
  99. }
  100. function init() {
  101. var selectedText = '';
  102. $('.stag-shortcuts').remove();
  103. options = [];
  104. menu = $('<div/>')
  105. .addClass('stag-shortcuts')
  106. .appendTo('body');
  107. let refreshOptions = false;
  108. $(document)
  109. .off('mousedown.outside-shortcuts')
  110. .on('mousedown.outside-shortcuts', function(_e) {
  111. if($(_e.target).closest('.stag-shortcuts').length) return;
  112. return discard();
  113. });
  114. $(document)
  115. .off('keypress.shortcuts', '[with-shortcuts]')
  116. .on('keypress.shortcuts', '[with-shortcuts]', function(_e) {
  117. input = this;
  118. switch(_e.which) {
  119. case 64:
  120. backtrackAfterApplying = true;
  121. strPart = '@';
  122. let options = [], noteRTE = $(input).closest('[note-rte]');
  123. let scSets = noteRTE.attr('use-shortcuts') ? noteRTE.attr('use-shortcuts').split(',') : ['user']
  124. for (let i = 0; i < scSets.length; i++) {
  125. if(window[$.trim(scSets[i]) + 'Shortcuts']) {
  126. options = options.concat(window[$.trim(scSets[i]) + 'Shortcuts']);
  127. }
  128. }
  129. show(true, options);
  130. break;
  131. default:
  132. if(!isVisible()) return;
  133. let char = String.fromCharCode(_e.which);
  134. if(_e.ctrlKey || _e.metaKey || !char.match(/[a-z0-9 ]/i)) {
  135. return false;
  136. }
  137. break;
  138. }
  139. })
  140. .off('keydown.shortcuts', '[with-shortcuts]')
  141. .on('keydown.shortcuts', '[with-shortcuts]', function(_e) {
  142. input = this;
  143. let consumed = false;
  144. refreshOptions = false;
  145. switch(_e.which) {
  146. /*
  147. case 32:
  148. if(_e.ctrlKey && !isVisible()) {
  149. backtrackAfterApplying = false;
  150. show(this);
  151. return false;
  152. }
  153. else {
  154. if(!isVisible()) return;
  155. _e.preventDefault();
  156. apply();
  157. consumed = true;
  158. }
  159. break;
  160. */
  161. case 27:
  162. if(!isVisible()) return;
  163. consumed = !discard();
  164. if(consumed) markEventAsConsumed(_e);
  165. break;
  166. case 38:
  167. if(!isVisible()) return;
  168. if(index > 0) index--;
  169. highlightOption();
  170. consumed = true;
  171. break;
  172. case 40:
  173. if(!isVisible()) return;
  174. if(index < options.length - 1) index++;
  175. highlightOption();
  176. consumed = true;
  177. break;
  178. case 13:
  179. if(!isVisible()) return;
  180. apply(true);
  181. consumed = true;
  182. break;
  183. case 8:
  184. if(!isVisible()) break;
  185. if(strPart.length === 1) {
  186. strPart = '';
  187. discard();
  188. }
  189. else {
  190. strPart = strPart.substr(0, strPart.length - 1);
  191. refreshOptions = true;
  192. }
  193. consumed = false;
  194. break;
  195. default:
  196. if(!isVisible()) break;
  197. let char = String.fromCharCode(_e.which);
  198. if(!_e.ctrlKey && !_e.metaKey && char.match(/[a-z0-9 ]/i)) {
  199. strPart += char;
  200. refreshOptions = true;
  201. consumed = false;
  202. }
  203. else {
  204. consumed = true;
  205. }
  206. break;
  207. }
  208. if(consumed) {
  209. _e.stopImmediatePropagation();
  210. _e.preventDefault();
  211. return false;
  212. }
  213. })
  214. .off('keyup.shortcuts', '[with-shortcuts]')
  215. .on('keyup.shortcuts', '[with-shortcuts]', function(_e) {
  216. let input = this;
  217. let options = window.userShortcuts, noteRTE = $(input).closest('[note-rte]');
  218. if(noteRTE.length && noteRTE.is('[use-shortcuts]') && noteRTE.attr('use-shortcuts') && noteRTE.attr('use-shortcuts') !== 'user') {
  219. if(window[noteRTE.attr('use-shortcuts') + 'Shortcuts']) {
  220. options = window[noteRTE.attr('use-shortcuts') + 'Shortcuts'];
  221. }
  222. }
  223. if(isVisible() && refreshOptions) {
  224. show(false, options);
  225. }
  226. })
  227. .off('paste.shortcuts', '[with-shortcuts]')
  228. .on('paste.shortcuts', '[with-shortcuts]', function(_e) {
  229. if(isVisible()) return false;
  230. });
  231. $(document)
  232. .off('mousedown.apply-shortcuts', '.stag-shortcuts>.sc')
  233. .on('mousedown.apply-shortcuts', '.stag-shortcuts>.sc', function(_e) {
  234. index = $(this).index();
  235. apply();
  236. return false;
  237. });
  238. $(document)
  239. .off('mousedown.add-shortcuts', '.add-shortcut')
  240. .on('mousedown.add-shortcuts', '.add-shortcut', function(_e) {
  241. let hasFocus = $(document.activeElement).closest('.note-content, .rte-holder').length;
  242. if(hasFocus) {
  243. selectedText = window.getSelection().toString();
  244. if(selectedText !== '') return;
  245. }
  246. return false;
  247. })
  248. .off('click.add-shortcuts', '.add-shortcut')
  249. .on('click.add-shortcuts', '.add-shortcut', function(_e) {
  250. // if(selectedText === '') return;
  251. $('#selected-sc-text').val(selectedText);
  252. $('#create-shortcut-form')
  253. .attr('data-editor-id', $(this).attr('data-editor-id'))
  254. .css({
  255. left: $(this).offset().left + 'px',
  256. top: ($(this).offset().top + $(this).outerHeight()) + 'px'
  257. })
  258. .show();
  259. showMoeFormMask();
  260. return false;
  261. })
  262. .off('submit.add-shortcut', '#create-shortcut-form')
  263. .on('submit.add-shortcut', '#create-shortcut-form', function(_e) {
  264. if(!input) input = $('.note-content [contenteditable][data-editor-id="' + $(this).attr('data-editor-id') + '"]').first();
  265. if(!input) return false;
  266. var label = $(this).find('[name="shortcut"]').val(),
  267. content = $(this).find('[name="text"]').val();
  268. if(!this.checkValidity()) return false;
  269. $.post('/api/proTextShortcut/create', $(this).serialize(), function(_data) {
  270. if(_data && _data.success && input) {
  271. window.userShortcuts.push({
  272. name: label,
  273. value: content
  274. });
  275. toastr.success('Shortcut saved');
  276. hideMoeFormMask();
  277. $('#create-shortcut-form').hide();
  278. $(input).focus();
  279. }
  280. }, 'json');
  281. return false;
  282. })
  283. .off('reset.add-shortcut', '#create-shortcut-form')
  284. .on('reset.add-shortcut', '#create-shortcut-form', function(_e) {
  285. if(!input) input = $('.note-content [contenteditable][data-editor-id="' + $(this).attr('data-editor-id') + '"]').first();
  286. if(!input) return false;
  287. hideMoeFormMask();
  288. $('#create-shortcut-form').hide();
  289. $(input).focus();
  290. });
  291. }
  292. addMCInitializer('shortcut-suggest', init);
  293. })();