editor.js 16 KB

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