editor.js 15 KB

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