editor.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. Template.editor.onRendered(() => {
  2. const textareaSelector = 'textarea';
  3. const enableRicherEditor = Meteor.settings.public.RICHER_EDITOR || true;
  4. const mentions = [
  5. // User mentions
  6. {
  7. match: /\B@([\w.]*)$/,
  8. search(term, callback) {
  9. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  10. callback(
  11. currentBoard
  12. .activeMembers()
  13. .map(member => {
  14. const username = Users.findOne(member.userId).username;
  15. return username.includes(term) ? username : null;
  16. })
  17. .filter(Boolean),
  18. );
  19. },
  20. template(value) {
  21. return value;
  22. },
  23. replace(username) {
  24. return `@${username} `;
  25. },
  26. index: 1,
  27. },
  28. ];
  29. const enableTextarea = function() {
  30. const $textarea = this.$(textareaSelector);
  31. autosize($textarea);
  32. $textarea.escapeableTextComplete(mentions);
  33. };
  34. if (enableRicherEditor) {
  35. const isSmall = Utils.isMiniScreen();
  36. const toolbar = isSmall
  37. ? [
  38. ['view', ['fullscreen']],
  39. ['table', ['table']],
  40. ['font', ['bold', 'underline']],
  41. //['fontsize', ['fontsize']],
  42. ['color', ['color']],
  43. ]
  44. : [
  45. ['style', ['style']],
  46. ['font', ['bold', 'underline', 'clear']],
  47. ['fontsize', ['fontsize']],
  48. ['fontname', ['fontname']],
  49. ['color', ['color']],
  50. ['para', ['ul', 'ol', 'paragraph']],
  51. ['table', ['table']],
  52. //['insert', ['link', 'picture', 'video']], // iframe tag will be sanitized TODO if iframe[class=note-video-clip] can be added into safe list, insert video can be enabled
  53. //['insert', ['link', 'picture']], // modal popup has issue somehow :(
  54. ['view', ['fullscreen', 'help']],
  55. ];
  56. const cleanPastedHTML = function(input) {
  57. const badTags = [
  58. 'style',
  59. 'script',
  60. 'applet',
  61. 'embed',
  62. 'noframes',
  63. 'noscript',
  64. 'meta',
  65. 'link',
  66. 'button',
  67. 'form',
  68. ].join('|');
  69. const badPatterns = new RegExp(
  70. `(?:${[
  71. `<(${badTags})s*[^>][\\s\\S]*?<\\/\\1>`,
  72. `<(${badTags})[^>]*?\\/>`,
  73. ].join('|')})`,
  74. 'gi',
  75. );
  76. let output = input;
  77. // remove bad Tags
  78. output = output.replace(badPatterns, '');
  79. // remove attributes ' style="..."'
  80. const badAttributes = new RegExp(
  81. `(?:${[
  82. 'on\\S+=([\'"]?).*?\\1',
  83. 'href=([\'"]?)javascript:.*?\\2',
  84. 'style=([\'"]?).*?\\3',
  85. 'target=\\S+',
  86. ].join('|')})`,
  87. 'gi',
  88. );
  89. output = output.replace(badAttributes, '');
  90. output = output.replace(/(<a )/gi, '$1target=_ '); // always to new target
  91. return output;
  92. };
  93. const editor = '.editor';
  94. const selectors = [
  95. `.js-new-comment-form ${editor}`,
  96. `.js-edit-comment ${editor}`,
  97. ].join(','); // only new comment and edit comment
  98. const inputs = $(selectors);
  99. if (inputs.length === 0) {
  100. // only enable richereditor to new comment or edit comment no others
  101. enableTextarea();
  102. } else {
  103. const placeholder = inputs.attr('placeholder') || '';
  104. const mSummernotes = [];
  105. const getSummernote = function(input) {
  106. const idx = inputs.index(input);
  107. if (idx > -1) {
  108. return mSummernotes[idx];
  109. }
  110. return undefined;
  111. };
  112. inputs.each(function(idx, input) {
  113. mSummernotes[idx] = $(input).summernote({
  114. placeholder,
  115. callbacks: {
  116. onInit(object) {
  117. const originalInput = this;
  118. $(originalInput).on('input', function() {
  119. // when comment is submitted, the original textarea will be set to '', so shall we
  120. if (!this.value) {
  121. const sn = getSummernote(this);
  122. sn && sn.summernote('reset');
  123. object && object.editingArea.find('.note-placeholder').show();
  124. }
  125. });
  126. const jEditor = object && object.editable;
  127. const toolbar = object && object.toolbar;
  128. if (jEditor !== undefined) {
  129. jEditor.escapeableTextComplete(mentions);
  130. }
  131. if (toolbar !== undefined) {
  132. const fBtn = toolbar.find('.btn-fullscreen');
  133. fBtn.on('click', function() {
  134. const $this = $(this),
  135. isActive = $this.hasClass('active');
  136. $('.minicards').toggle(!isActive); // mini card is still showing when editor is in fullscreen mode, we hide here manually
  137. });
  138. }
  139. },
  140. onPaste() {
  141. // clear up unwanted tag info when user pasted in text
  142. const thisNote = this;
  143. const updatePastedText = function(object) {
  144. const someNote = getSummernote(object);
  145. const original = someNote.summernote('code');
  146. const cleaned = cleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
  147. someNote.summernote('reset'); //clear original
  148. someNote.summernote('pasteHTML', cleaned); //this sets the displayed content editor to the cleaned pasted code.
  149. };
  150. setTimeout(function() {
  151. //this kinda sucks, but if you don't do a setTimeout,
  152. //the function is called before the text is really pasted.
  153. updatePastedText(thisNote);
  154. }, 10);
  155. },
  156. },
  157. dialogsInBody: true,
  158. disableDragAndDrop: true,
  159. toolbar,
  160. popover: {
  161. image: [
  162. [
  163. 'image',
  164. ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone'],
  165. ],
  166. ['float', ['floatLeft', 'floatRight', 'floatNone']],
  167. ['remove', ['removeMedia']],
  168. ],
  169. table: [
  170. ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']],
  171. ['delete', ['deleteRow', 'deleteCol', 'deleteTable']],
  172. ],
  173. air: [
  174. ['color', ['color']],
  175. ['font', ['bold', 'underline', 'clear']],
  176. ],
  177. },
  178. height: 200,
  179. });
  180. });
  181. }
  182. } else {
  183. enableTextarea();
  184. }
  185. });
  186. import sanitizeXss from 'xss';
  187. // XXX I believe we should compute a HTML rendered field on the server that
  188. // would handle markdown and user mentions. We can simply have two
  189. // fields, one source, and one compiled version (in HTML) and send only the
  190. // compiled version to most users -- who don't need to edit.
  191. // In the meantime, all the transformation are done on the client using the
  192. // Blaze API.
  193. const at = HTML.CharRef({ html: '&commat;', str: '@' });
  194. Blaze.Template.registerHelper(
  195. 'mentions',
  196. new Template('mentions', function() {
  197. const view = this;
  198. let content = Blaze.toHTML(view.templateContentBlock);
  199. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  200. if (!currentBoard) return HTML.Raw(sanitizeXss(content));
  201. const knowedUsers = currentBoard.members.map(member => {
  202. const u = Users.findOne(member.userId);
  203. if (u) {
  204. member.username = u.username;
  205. }
  206. return member;
  207. });
  208. const mentionRegex = /\B@([\w.]*)/gi;
  209. let currentMention;
  210. while ((currentMention = mentionRegex.exec(content)) !== null) {
  211. const [fullMention, username] = currentMention;
  212. const knowedUser = _.findWhere(knowedUsers, { username });
  213. if (!knowedUser) {
  214. continue;
  215. }
  216. const linkValue = [' ', at, knowedUser.username];
  217. let linkClass = 'atMention js-open-member';
  218. if (knowedUser.userId === Meteor.userId()) {
  219. linkClass += ' me';
  220. }
  221. const link = HTML.A(
  222. {
  223. class: linkClass,
  224. // XXX Hack. Since we stringify this render function result below with
  225. // `Blaze.toHTML` we can't rely on blaze data contexts to pass the
  226. // `userId` to the popup as usual, and we need to store it in the DOM
  227. // using a data attribute.
  228. 'data-userId': knowedUser.userId,
  229. },
  230. linkValue,
  231. );
  232. content = content.replace(fullMention, Blaze.toHTML(link));
  233. }
  234. return HTML.Raw(sanitizeXss(content));
  235. }),
  236. );
  237. Template.viewer.events({
  238. // Viewer sometimes have click-able wrapper around them (for instance to edit
  239. // the corresponding text). Clicking a link shouldn't fire these actions, stop
  240. // we stop these event at the viewer component level.
  241. 'click a'(event, templateInstance) {
  242. event.stopPropagation();
  243. // XXX We hijack the build-in browser action because we currently don't have
  244. // `_blank` attributes in viewer links, and the transformer function is
  245. // handled by a third party package that we can't configure easily. Fix that
  246. // by using directly `_blank` attribute in the rendered HTML.
  247. event.preventDefault();
  248. const userId = event.currentTarget.dataset.userid;
  249. if (userId) {
  250. Popup.open('member').call({ userId }, event, templateInstance);
  251. } else {
  252. const href = event.currentTarget.href;
  253. if (href) {
  254. window.open(href, '_blank');
  255. }
  256. }
  257. },
  258. });