editor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. const specialHandles = [
  2. {userId: 'board_members', username: 'board_members'},
  3. {userId: 'card_members', username: 'card_members'}
  4. ];
  5. const specialHandleNames = specialHandles.map(m => m.username);
  6. BlazeComponent.extendComponent({
  7. onRendered() {
  8. const textareaSelector = 'textarea';
  9. const mentions = [
  10. // User mentions
  11. {
  12. match: /\B@([\w.-]*)$/,
  13. search(term, callback) {
  14. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  15. callback(
  16. _.union(
  17. currentBoard
  18. .activeMembers()
  19. .map(member => {
  20. const user = Users.findOne(member.userId);
  21. const username = user.username;
  22. const fullName = user.profile && user.profile !== undefined && user.profile.fullname ? user.profile.fullname : "";
  23. return username.includes(term) || fullName.includes(term) ? user : null;
  24. })
  25. .filter(Boolean), [...specialHandles])
  26. );
  27. },
  28. template(user) {
  29. if (user.profile && user.profile.fullname) {
  30. return (user.profile.fullname + " (" + user.username + ")");
  31. }
  32. return user.username;
  33. },
  34. replace(user) {
  35. if (user.profile && user.profile.fullname) {
  36. return `@${user.username} (${user.profile.fullname}) `;
  37. }
  38. return `@${user.username} `;
  39. },
  40. index: 1,
  41. },
  42. ];
  43. const enableTextarea = function() {
  44. const $textarea = this.$(textareaSelector);
  45. autosize($textarea);
  46. $textarea.escapeableTextComplete(mentions);
  47. };
  48. if (Meteor.settings.public.RICHER_CARD_COMMENT_EDITOR !== false) {
  49. const isSmall = Utils.isMiniScreen();
  50. const toolbar = isSmall
  51. ? [
  52. ['view', ['fullscreen']],
  53. ['table', ['table']],
  54. ['font', ['bold', 'underline']],
  55. //['fontsize', ['fontsize']],
  56. ['color', ['color']],
  57. ]
  58. : [
  59. ['style', ['style']],
  60. ['font', ['bold', 'underline', 'clear']],
  61. ['fontsize', ['fontsize']],
  62. ['fontname', ['fontname']],
  63. ['color', ['color']],
  64. ['para', ['ul', 'ol', 'paragraph']],
  65. ['table', ['table']],
  66. //['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
  67. ['insert', ['link']], //, 'picture']], // modal popup has issue somehow :(
  68. ['view', ['fullscreen', 'codeview', 'help']],
  69. ];
  70. const cleanPastedHTML = function(input) {
  71. const badTags = [
  72. 'style',
  73. 'script',
  74. 'applet',
  75. 'embed',
  76. 'noframes',
  77. 'noscript',
  78. 'meta',
  79. 'link',
  80. 'button',
  81. 'form',
  82. ].join('|');
  83. const badPatterns = new RegExp(
  84. `(?:${[
  85. `<(${badTags})s*[^>][\\s\\S]*?<\\/\\1>`,
  86. `<(${badTags})[^>]*?\\/>`,
  87. ].join('|')})`,
  88. 'gi',
  89. );
  90. let output = input;
  91. // remove bad Tags
  92. output = output.replace(badPatterns, '');
  93. // remove attributes ' style="..."'
  94. const badAttributes = new RegExp(
  95. `(?:${[
  96. 'on\\S+=([\'"]?).*?\\1',
  97. 'href=([\'"]?)javascript:.*?\\2',
  98. 'style=([\'"]?).*?\\3',
  99. 'target=\\S+',
  100. ].join('|')})`,
  101. 'gi',
  102. );
  103. output = output.replace(badAttributes, '');
  104. output = output.replace(/(<a )/gi, '$1target=_ '); // always to new target
  105. return output;
  106. };
  107. const editor = '.editor';
  108. const selectors = [
  109. `.js-new-description-form ${editor}`,
  110. `.js-new-comment-form ${editor}`,
  111. `.js-edit-comment ${editor}`,
  112. ].join(','); // only new comment and edit comment
  113. const inputs = $(selectors);
  114. if (inputs.length === 0) {
  115. // only enable richereditor to new comment or edit comment no others
  116. enableTextarea();
  117. } else {
  118. const placeholder = inputs.attr('placeholder') || '';
  119. const mSummernotes = [];
  120. const getSummernote = function(input) {
  121. const idx = inputs.index(input);
  122. if (idx > -1) {
  123. return mSummernotes[idx];
  124. }
  125. return undefined;
  126. };
  127. inputs.each(function(idx, input) {
  128. mSummernotes[idx] = $(input).summernote({
  129. placeholder,
  130. callbacks: {
  131. onInit(object) {
  132. const originalInput = this;
  133. $(originalInput).on('submitted', function() {
  134. // when comment is submitted, the original textarea will be set to '', so shall we
  135. if (!this.value) {
  136. const sn = getSummernote(this);
  137. sn && sn.summernote('code', '');
  138. }
  139. });
  140. const jEditor = object && object.editable;
  141. const toolbar = object && object.toolbar;
  142. if (jEditor !== undefined) {
  143. jEditor.escapeableTextComplete(mentions);
  144. }
  145. if (toolbar !== undefined) {
  146. const fBtn = toolbar.find('.btn-fullscreen');
  147. fBtn.on('click', function() {
  148. const $this = $(this),
  149. isActive = $this.hasClass('active');
  150. $('.minicards,#header-quick-access').toggle(!isActive); // mini card is still showing when editor is in fullscreen mode, we hide here manually
  151. });
  152. }
  153. },
  154. onImageUpload(files) {
  155. const $summernote = getSummernote(this);
  156. if (files && files.length > 0) {
  157. const image = files[0];
  158. const currentCard = Utils.getCurrentCard();
  159. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  160. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  161. const insertImage = src => {
  162. const img = document.createElement('img');
  163. img.src = src;
  164. img.setAttribute('width', '100%');
  165. $summernote.summernote('insertNode', img);
  166. };
  167. const processUpload = function(file) {
  168. const uploader = Attachments.insert(
  169. {
  170. file,
  171. chunkSize: 'dynamic',
  172. },
  173. false,
  174. );
  175. uploader.on('uploaded', (error, fileObj) => {
  176. if (!error) {
  177. if (fileObj.isImage) {
  178. insertImage(
  179. `${location.protocol}//${location.host}${fileObj.path}`,
  180. );
  181. }
  182. Utils.addCommonMetaToAttachment(currentCard, fileObj);
  183. }
  184. });
  185. uploader.start();
  186. };
  187. if (MAX_IMAGE_PIXEL) {
  188. const reader = new FileReader();
  189. reader.onload = function(e) {
  190. const dataurl = e && e.target && e.target.result;
  191. if (dataurl !== undefined) {
  192. // need to shrink image
  193. Utils.shrinkImage({
  194. dataurl,
  195. maxSize: MAX_IMAGE_PIXEL,
  196. ratio: COMPRESS_RATIO,
  197. toBlob: true,
  198. callback(blob) {
  199. if (blob !== false) {
  200. blob.name = image.name;
  201. processUpload(blob);
  202. }
  203. },
  204. });
  205. }
  206. };
  207. reader.readAsDataURL(image);
  208. } else {
  209. processUpload(image);
  210. }
  211. }
  212. },
  213. onPaste(e) {
  214. var clipboardData = e.clipboardData;
  215. var pastedData = clipboardData.getData('Text');
  216. //if pasted data is an image, exit
  217. if (!pastedData.length) {
  218. e.preventDefault();
  219. return;
  220. }
  221. // clear up unwanted tag info when user pasted in text
  222. const thisNote = this;
  223. const updatePastedText = function(object) {
  224. const someNote = getSummernote(object);
  225. // Fix Pasting text into a card is adding a line before and after
  226. // (and multiplies by pasting more) by changing paste "p" to "br".
  227. // Fixes https://github.com/wekan/wekan/2890 .
  228. // == Fix Start ==
  229. someNote.execCommand('defaultParagraphSeparator', false, 'br');
  230. // == Fix End ==
  231. const original = someNote.summernote('code');
  232. const cleaned = cleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
  233. someNote.summernote('code', ''); //clear original
  234. someNote.summernote('pasteHTML', cleaned); //this sets the displayed content editor to the cleaned pasted code.
  235. };
  236. setTimeout(function() {
  237. //this kinda sucks, but if you don't do a setTimeout,
  238. //the function is called before the text is really pasted.
  239. updatePastedText(thisNote);
  240. }, 10);
  241. },
  242. },
  243. dialogsInBody: true,
  244. spellCheck: true,
  245. disableGrammar: false,
  246. disableDragAndDrop: false,
  247. toolbar,
  248. popover: {
  249. image: [
  250. ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
  251. ['float', ['floatLeft', 'floatRight', 'floatNone']],
  252. ['remove', ['removeMedia']],
  253. ],
  254. link: [['link', ['linkDialogShow', 'unlink']]],
  255. table: [
  256. ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']],
  257. ['delete', ['deleteRow', 'deleteCol', 'deleteTable']],
  258. ],
  259. air: [
  260. ['color', ['color']],
  261. ['font', ['bold', 'underline', 'clear']],
  262. ],
  263. },
  264. height: 200,
  265. });
  266. });
  267. }
  268. } else {
  269. enableTextarea();
  270. }
  271. },
  272. events() {
  273. return [
  274. {
  275. 'click a.fa.fa-copy'(event) {
  276. const $editor = this.$('textarea.editor');
  277. const promise = Utils.copyTextToClipboard($editor[0].value);
  278. const $tooltip = this.$('.copied-tooltip');
  279. Utils.showCopied(promise, $tooltip);
  280. },
  281. }
  282. ]
  283. }
  284. }).register('editor');
  285. import DOMPurify from 'dompurify';
  286. // Additional safeAttrValue function to allow for other specific protocols
  287. // See https://github.com/leizongmin/js-xss/issues/52#issuecomment-241354114
  288. /*
  289. function mySafeAttrValue(tag, name, value, cssFilter) {
  290. // only when the tag is 'a' and attribute is 'href'
  291. // then use your custom function
  292. if (tag === 'a' && name === 'href') {
  293. // only filter the value if starts with 'cbthunderlink:' or 'aodroplink'
  294. if (
  295. /^thunderlink:/gi.test(value) ||
  296. /^cbthunderlink:/gi.test(value) ||
  297. /^aodroplink:/gi.test(value) ||
  298. /^onenote:/gi.test(value) ||
  299. /^file:/gi.test(value) ||
  300. /^abasurl:/gi.test(value) ||
  301. /^conisio:/gi.test(value) ||
  302. /^mailspring:/gi.test(value)
  303. ) {
  304. return value;
  305. } else {
  306. // use the default safeAttrValue function to process all non cbthunderlinks
  307. return sanitizeXss.safeAttrValue(tag, name, value, cssFilter);
  308. }
  309. } else {
  310. // use the default safeAttrValue function to process it
  311. return sanitizeXss.safeAttrValue(tag, name, value, cssFilter);
  312. }
  313. }
  314. */
  315. // XXX I believe we should compute a HTML rendered field on the server that
  316. // would handle markdown and user mentions. We can simply have two
  317. // fields, one source, and one compiled version (in HTML) and send only the
  318. // compiled version to most users -- who don't need to edit.
  319. // In the meantime, all the transformation are done on the client using the
  320. // Blaze API.
  321. const at = HTML.CharRef({ html: '&commat;', str: '@' });
  322. Blaze.Template.registerHelper(
  323. 'mentions',
  324. new Template('mentions', function() {
  325. const view = this;
  326. let content = Blaze.toHTML(view.templateContentBlock);
  327. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  328. if (!currentBoard)
  329. return HTML.Raw(
  330. DOMPurify.sanitize(content, { ALLOW_UNKNOWN_PROTOCOLS: true }),
  331. );
  332. const knowedUsers = _.union(currentBoard.members.map(member => {
  333. const u = Users.findOne(member.userId);
  334. if (u) {
  335. member.username = u.username;
  336. }
  337. return member;
  338. }), [...specialHandles]);
  339. const mentionRegex = /\B@([\w.-]*)/gi;
  340. let currentMention;
  341. while ((currentMention = mentionRegex.exec(content)) !== null) {
  342. const [fullMention, quoteduser, simple] = currentMention;
  343. const username = quoteduser || simple;
  344. const knowedUser = _.findWhere(knowedUsers, { username });
  345. if (!knowedUser) {
  346. continue;
  347. }
  348. const linkValue = [' ', at, knowedUser.username];
  349. let linkClass = 'atMention js-open-member';
  350. if (knowedUser.userId === Meteor.userId()) {
  351. linkClass += ' me';
  352. }
  353. // This @user mention link generation did open same Wekan
  354. // window in new tab, so now A is changed to U so it's
  355. // underlined and there is no link popup. This way also
  356. // text can be selected more easily.
  357. //const link = HTML.A(
  358. const link = HTML.U(
  359. {
  360. class: linkClass,
  361. // XXX Hack. Since we stringify this render function result below with
  362. // `Blaze.toHTML` we can't rely on blaze data contexts to pass the
  363. // `userId` to the popup as usual, and we need to store it in the DOM
  364. // using a data attribute.
  365. 'data-userId': knowedUser.userId,
  366. },
  367. linkValue,
  368. );
  369. content = content.replace(fullMention, Blaze.toHTML(link));
  370. }
  371. return HTML.Raw(
  372. DOMPurify.sanitize(content, { ALLOW_UNKNOWN_PROTOCOLS: true }),
  373. );
  374. }),
  375. );
  376. Template.viewer.events({
  377. // Viewer sometimes have click-able wrapper around them (for instance to edit
  378. // the corresponding text). Clicking a link shouldn't fire these actions, stop
  379. // we stop these event at the viewer component level.
  380. 'click a'(event, templateInstance) {
  381. const prevent = true;
  382. const userId = event.currentTarget.dataset.userid;
  383. if (userId) {
  384. Popup.open('member').call({ userId }, event, templateInstance);
  385. } else {
  386. const href = event.currentTarget.href;
  387. if (href) {
  388. window.open(href, '_blank');
  389. }
  390. }
  391. if (prevent) {
  392. event.stopPropagation();
  393. // XXX We hijack the build-in browser action because we currently don't have
  394. // `_blank` attributes in viewer links, and the transformer function is
  395. // handled by a third party package that we can't configure easily. Fix that
  396. // by using directly `_blank` attribute in the rendered HTML.
  397. event.preventDefault();
  398. }
  399. },
  400. });