editor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 = Utils.getCurrentBoard();
  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 processUpload = function(file) {
  162. const uploader = Attachments.insert(
  163. {
  164. file,
  165. meta: Utils.getCommonAttachmentMetaFrom(card),
  166. chunkSize: 'dynamic',
  167. },
  168. false,
  169. );
  170. uploader.on('uploaded', (error, fileRef) => {
  171. if (!error) {
  172. if (fileRef.isImage) {
  173. const img = document.createElement('img');
  174. img.src = fileRef.link();
  175. img.setAttribute('width', '100%');
  176. $summernote.summernote('insertNode', img);
  177. }
  178. }
  179. });
  180. uploader.start();
  181. };
  182. if (MAX_IMAGE_PIXEL) {
  183. const reader = new FileReader();
  184. reader.onload = function(e) {
  185. const dataurl = e && e.target && e.target.result;
  186. if (dataurl !== undefined) {
  187. // need to shrink image
  188. Utils.shrinkImage({
  189. dataurl,
  190. maxSize: MAX_IMAGE_PIXEL,
  191. ratio: COMPRESS_RATIO,
  192. toBlob: true,
  193. callback(blob) {
  194. if (blob !== false) {
  195. blob.name = image.name;
  196. processUpload(blob);
  197. }
  198. },
  199. });
  200. }
  201. };
  202. reader.readAsDataURL(image);
  203. } else {
  204. processUpload(image);
  205. }
  206. }
  207. },
  208. onPaste(e) {
  209. var clipboardData = e.clipboardData;
  210. var pastedData = clipboardData.getData('Text');
  211. //if pasted data is an image, exit
  212. if (!pastedData.length) {
  213. e.preventDefault();
  214. return;
  215. }
  216. // clear up unwanted tag info when user pasted in text
  217. const thisNote = this;
  218. const updatePastedText = function(object) {
  219. const someNote = getSummernote(object);
  220. // Fix Pasting text into a card is adding a line before and after
  221. // (and multiplies by pasting more) by changing paste "p" to "br".
  222. // Fixes https://github.com/wekan/wekan/2890 .
  223. // == Fix Start ==
  224. someNote.execCommand('defaultParagraphSeparator', false, 'br');
  225. // == Fix End ==
  226. const original = someNote.summernote('code');
  227. const cleaned = cleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
  228. someNote.summernote('code', ''); //clear original
  229. someNote.summernote('pasteHTML', cleaned); //this sets the displayed content editor to the cleaned pasted code.
  230. };
  231. setTimeout(function() {
  232. //this kinda sucks, but if you don't do a setTimeout,
  233. //the function is called before the text is really pasted.
  234. updatePastedText(thisNote);
  235. }, 10);
  236. },
  237. },
  238. dialogsInBody: true,
  239. spellCheck: true,
  240. disableGrammar: false,
  241. disableDragAndDrop: false,
  242. toolbar,
  243. popover: {
  244. image: [
  245. ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
  246. ['float', ['floatLeft', 'floatRight', 'floatNone']],
  247. ['remove', ['removeMedia']],
  248. ],
  249. link: [['link', ['linkDialogShow', 'unlink']]],
  250. table: [
  251. ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']],
  252. ['delete', ['deleteRow', 'deleteCol', 'deleteTable']],
  253. ],
  254. air: [
  255. ['color', ['color']],
  256. ['font', ['bold', 'underline', 'clear']],
  257. ],
  258. },
  259. height: 200,
  260. });
  261. });
  262. }
  263. } else {
  264. enableTextarea();
  265. }
  266. },
  267. events() {
  268. return [
  269. {
  270. 'click a.fa.fa-copy'(event) {
  271. const $editor = this.$('textarea.editor');
  272. const promise = Utils.copyTextToClipboard($editor[0].value);
  273. const $tooltip = this.$('.copied-tooltip');
  274. Utils.showCopied(promise, $tooltip);
  275. },
  276. }
  277. ]
  278. }
  279. }).register('editor');
  280. import DOMPurify from 'dompurify';
  281. // Additional safeAttrValue function to allow for other specific protocols
  282. // See https://github.com/leizongmin/js-xss/issues/52#issuecomment-241354114
  283. /*
  284. function mySafeAttrValue(tag, name, value, cssFilter) {
  285. // only when the tag is 'a' and attribute is 'href'
  286. // then use your custom function
  287. if (tag === 'a' && name === 'href') {
  288. // only filter the value if starts with 'cbthunderlink:' or 'aodroplink'
  289. if (
  290. /^thunderlink:/gi.test(value) ||
  291. /^cbthunderlink:/gi.test(value) ||
  292. /^aodroplink:/gi.test(value) ||
  293. /^onenote:/gi.test(value) ||
  294. /^file:/gi.test(value) ||
  295. /^abasurl:/gi.test(value) ||
  296. /^conisio:/gi.test(value) ||
  297. /^mailspring:/gi.test(value)
  298. ) {
  299. return value;
  300. } else {
  301. // use the default safeAttrValue function to process all non cbthunderlinks
  302. return sanitizeXss.safeAttrValue(tag, name, value, cssFilter);
  303. }
  304. } else {
  305. // use the default safeAttrValue function to process it
  306. return sanitizeXss.safeAttrValue(tag, name, value, cssFilter);
  307. }
  308. }
  309. */
  310. // XXX I believe we should compute a HTML rendered field on the server that
  311. // would handle markdown and user mentions. We can simply have two
  312. // fields, one source, and one compiled version (in HTML) and send only the
  313. // compiled version to most users -- who don't need to edit.
  314. // In the meantime, all the transformation are done on the client using the
  315. // Blaze API.
  316. const at = HTML.CharRef({ html: '&commat;', str: '@' });
  317. Blaze.Template.registerHelper(
  318. 'mentions',
  319. new Template('mentions', function() {
  320. const view = this;
  321. let content = Blaze.toHTML(view.templateContentBlock);
  322. const currentBoard = Utils.getCurrentBoard();
  323. if (!currentBoard)
  324. return HTML.Raw(
  325. DOMPurify.sanitize(content, { ALLOW_UNKNOWN_PROTOCOLS: true }),
  326. );
  327. const knowedUsers = _.union(currentBoard.members.map(member => {
  328. const u = Users.findOne(member.userId);
  329. if (u) {
  330. member.username = u.username;
  331. }
  332. return member;
  333. }), [...specialHandles]);
  334. const mentionRegex = /\B@([\w.-]*)/gi;
  335. let currentMention;
  336. while ((currentMention = mentionRegex.exec(content)) !== null) {
  337. const [fullMention, quoteduser, simple] = currentMention;
  338. const username = quoteduser || simple;
  339. const knowedUser = _.findWhere(knowedUsers, { username });
  340. if (!knowedUser) {
  341. continue;
  342. }
  343. const linkValue = [' ', at, knowedUser.username];
  344. let linkClass = 'atMention js-open-member';
  345. if (knowedUser.userId === Meteor.userId()) {
  346. linkClass += ' me';
  347. }
  348. // This @user mention link generation did open same Wekan
  349. // window in new tab, so now A is changed to U so it's
  350. // underlined and there is no link popup. This way also
  351. // text can be selected more easily.
  352. //const link = HTML.A(
  353. const link = HTML.U(
  354. {
  355. class: linkClass,
  356. // XXX Hack. Since we stringify this render function result below with
  357. // `Blaze.toHTML` we can't rely on blaze data contexts to pass the
  358. // `userId` to the popup as usual, and we need to store it in the DOM
  359. // using a data attribute.
  360. 'data-userId': knowedUser.userId,
  361. },
  362. linkValue,
  363. );
  364. content = content.replace(fullMention, Blaze.toHTML(link));
  365. }
  366. return HTML.Raw(
  367. DOMPurify.sanitize(content, { ALLOW_UNKNOWN_PROTOCOLS: true }),
  368. );
  369. }),
  370. );
  371. Template.viewer.events({
  372. // Viewer sometimes have click-able wrapper around them (for instance to edit
  373. // the corresponding text). Clicking a link shouldn't fire these actions, stop
  374. // we stop these event at the viewer component level.
  375. 'click a'(event, templateInstance) {
  376. const prevent = true;
  377. const userId = event.currentTarget.dataset.userid;
  378. if (userId) {
  379. Popup.open('member').call({ userId }, event, templateInstance);
  380. } else {
  381. const href = event.currentTarget.href;
  382. if (href) {
  383. // Open links in current browser tab, changed from _blank to _self, and back to _blank:
  384. // https://github.com/wekan/wekan/discussions/3534
  385. //window.open(href, '_self');
  386. window.open(href, '_blank');
  387. }
  388. }
  389. if (prevent) {
  390. event.stopPropagation();
  391. // XXX We hijack the build-in browser action because we currently don't have
  392. // `_blank` attributes in viewer links, and the transformer function is
  393. // handled by a third party package that we can't configure easily. Fix that
  394. // by using directly `_blank` attribute in the rendered HTML.
  395. event.preventDefault();
  396. }
  397. },
  398. });