editor.js 17 KB

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