editor.js 17 KB

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