editor.js 9.3 KB

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