editor.js 15 KB

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