editor.js 16 KB

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