editor.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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,#header-quick-access').toggle(!isActive); // mini card is still showing when editor is in fullscreen mode, we hide here manually
  138. });
  139. }
  140. },
  141. onImageUpload(files) {
  142. const $summernote = getSummernote(this);
  143. if (files && files.length > 0) {
  144. const image = files[0];
  145. const currentCard = Cards.findOne(Session.get('currentCard'));
  146. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  147. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  148. const insertImage = src => {
  149. const img = document.createElement('img');
  150. img.src = src;
  151. img.setAttribute('width', '100%');
  152. $summernote.summernote('insertNode', img);
  153. };
  154. const processData = function(fileObj) {
  155. Utils.processUploadedAttachment(
  156. currentCard,
  157. fileObj,
  158. attachment => {
  159. if (
  160. attachment &&
  161. attachment._id &&
  162. attachment.isImage()
  163. ) {
  164. attachment.one('uploaded', function() {
  165. const maxTry = 3;
  166. const checkItvl = 500;
  167. let retry = 0;
  168. const checkUrl = function() {
  169. // even though uploaded event fired, attachment.url() is still null somehow //TODO
  170. const url = attachment.url();
  171. if (url) {
  172. insertImage(
  173. `${location.protocol}//${location.host}${url}`,
  174. );
  175. } else {
  176. retry++;
  177. if (retry < maxTry) {
  178. setTimeout(checkUrl, checkItvl);
  179. }
  180. }
  181. };
  182. checkUrl();
  183. });
  184. }
  185. },
  186. );
  187. };
  188. if (MAX_IMAGE_PIXEL) {
  189. const reader = new FileReader();
  190. reader.onload = function(e) {
  191. const dataurl = e && e.target && e.target.result;
  192. if (dataurl !== undefined) {
  193. // need to shrink image
  194. Utils.shrinkImage({
  195. dataurl,
  196. maxSize: MAX_IMAGE_PIXEL,
  197. ratio: COMPRESS_RATIO,
  198. toBlob: true,
  199. callback(blob) {
  200. if (blob !== false) {
  201. blob.name = image.name;
  202. processData(blob);
  203. }
  204. },
  205. });
  206. }
  207. };
  208. reader.readAsDataURL(image);
  209. } else {
  210. processData(image);
  211. }
  212. }
  213. },
  214. onPaste() {
  215. // clear up unwanted tag info when user pasted in text
  216. const thisNote = this;
  217. const updatePastedText = function(object) {
  218. const someNote = getSummernote(object);
  219. const original = someNote.summernote('code');
  220. const cleaned = cleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
  221. someNote.summernote('reset'); //clear original
  222. someNote.summernote('pasteHTML', cleaned); //this sets the displayed content editor to the cleaned pasted code.
  223. };
  224. setTimeout(function() {
  225. //this kinda sucks, but if you don't do a setTimeout,
  226. //the function is called before the text is really pasted.
  227. updatePastedText(thisNote);
  228. }, 10);
  229. },
  230. },
  231. dialogsInBody: true,
  232. disableDragAndDrop: true,
  233. toolbar,
  234. popover: {
  235. image: [
  236. [
  237. 'image',
  238. ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone'],
  239. ],
  240. ['float', ['floatLeft', 'floatRight', 'floatNone']],
  241. ['remove', ['removeMedia']],
  242. ],
  243. table: [
  244. ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']],
  245. ['delete', ['deleteRow', 'deleteCol', 'deleteTable']],
  246. ],
  247. air: [
  248. ['color', ['color']],
  249. ['font', ['bold', 'underline', 'clear']],
  250. ],
  251. },
  252. height: 200,
  253. });
  254. });
  255. }
  256. } else {
  257. enableTextarea();
  258. }
  259. });
  260. import sanitizeXss from 'xss';
  261. // XXX I believe we should compute a HTML rendered field on the server that
  262. // would handle markdown and user mentions. We can simply have two
  263. // fields, one source, and one compiled version (in HTML) and send only the
  264. // compiled version to most users -- who don't need to edit.
  265. // In the meantime, all the transformation are done on the client using the
  266. // Blaze API.
  267. const at = HTML.CharRef({ html: '&commat;', str: '@' });
  268. Blaze.Template.registerHelper(
  269. 'mentions',
  270. new Template('mentions', function() {
  271. const view = this;
  272. let content = Blaze.toHTML(view.templateContentBlock);
  273. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  274. if (!currentBoard) return HTML.Raw(sanitizeXss(content));
  275. const knowedUsers = currentBoard.members.map(member => {
  276. const u = Users.findOne(member.userId);
  277. if (u) {
  278. member.username = u.username;
  279. }
  280. return member;
  281. });
  282. const mentionRegex = /\B@([\w.]*)/gi;
  283. let currentMention;
  284. while ((currentMention = mentionRegex.exec(content)) !== null) {
  285. const [fullMention, username] = currentMention;
  286. const knowedUser = _.findWhere(knowedUsers, { username });
  287. if (!knowedUser) {
  288. continue;
  289. }
  290. const linkValue = [' ', at, knowedUser.username];
  291. let linkClass = 'atMention js-open-member';
  292. if (knowedUser.userId === Meteor.userId()) {
  293. linkClass += ' me';
  294. }
  295. const link = HTML.A(
  296. {
  297. class: linkClass,
  298. // XXX Hack. Since we stringify this render function result below with
  299. // `Blaze.toHTML` we can't rely on blaze data contexts to pass the
  300. // `userId` to the popup as usual, and we need to store it in the DOM
  301. // using a data attribute.
  302. 'data-userId': knowedUser.userId,
  303. },
  304. linkValue,
  305. );
  306. content = content.replace(fullMention, Blaze.toHTML(link));
  307. }
  308. return HTML.Raw(sanitizeXss(content));
  309. }),
  310. );
  311. Template.viewer.events({
  312. // Viewer sometimes have click-able wrapper around them (for instance to edit
  313. // the corresponding text). Clicking a link shouldn't fire these actions, stop
  314. // we stop these event at the viewer component level.
  315. 'click a'(event, templateInstance) {
  316. event.stopPropagation();
  317. // XXX We hijack the build-in browser action because we currently don't have
  318. // `_blank` attributes in viewer links, and the transformer function is
  319. // handled by a third party package that we can't configure easily. Fix that
  320. // by using directly `_blank` attribute in the rendered HTML.
  321. event.preventDefault();
  322. const userId = event.currentTarget.dataset.userid;
  323. if (userId) {
  324. Popup.open('member').call({ userId }, event, templateInstance);
  325. } else {
  326. const href = event.currentTarget.href;
  327. if (href) {
  328. window.open(href, '_blank');
  329. }
  330. }
  331. },
  332. });