editor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 user = Users.findOne(member.userId);
  20. const username = user.username;
  21. const fullName = user.profile && user.profile !== undefined ? user.profile.fullname : "";
  22. return username.includes(term) || fullName.includes(term) ? fullName + "(" + username + ")" : null;
  23. })
  24. .filter(Boolean), [...specialHandleNames])
  25. );
  26. },
  27. template(value) {
  28. return value;
  29. },
  30. replace(username) {
  31. return `@${username} `;
  32. },
  33. index: 1,
  34. },
  35. ];
  36. const enableTextarea = function() {
  37. const $textarea = this.$(textareaSelector);
  38. autosize($textarea);
  39. $textarea.escapeableTextComplete(mentions);
  40. };
  41. if (Meteor.settings.public.RICHER_CARD_COMMENT_EDITOR !== false) {
  42. const isSmall = Utils.isMiniScreen();
  43. const toolbar = isSmall
  44. ? [
  45. ['view', ['fullscreen']],
  46. ['table', ['table']],
  47. ['font', ['bold', 'underline']],
  48. //['fontsize', ['fontsize']],
  49. ['color', ['color']],
  50. ]
  51. : [
  52. ['style', ['style']],
  53. ['font', ['bold', 'underline', 'clear']],
  54. ['fontsize', ['fontsize']],
  55. ['fontname', ['fontname']],
  56. ['color', ['color']],
  57. ['para', ['ul', 'ol', 'paragraph']],
  58. ['table', ['table']],
  59. //['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
  60. ['insert', ['link']], //, 'picture']], // modal popup has issue somehow :(
  61. ['view', ['fullscreen', 'codeview', 'help']],
  62. ];
  63. const cleanPastedHTML = function(input) {
  64. const badTags = [
  65. 'style',
  66. 'script',
  67. 'applet',
  68. 'embed',
  69. 'noframes',
  70. 'noscript',
  71. 'meta',
  72. 'link',
  73. 'button',
  74. 'form',
  75. ].join('|');
  76. const badPatterns = new RegExp(
  77. `(?:${[
  78. `<(${badTags})s*[^>][\\s\\S]*?<\\/\\1>`,
  79. `<(${badTags})[^>]*?\\/>`,
  80. ].join('|')})`,
  81. 'gi',
  82. );
  83. let output = input;
  84. // remove bad Tags
  85. output = output.replace(badPatterns, '');
  86. // remove attributes ' style="..."'
  87. const badAttributes = new RegExp(
  88. `(?:${[
  89. 'on\\S+=([\'"]?).*?\\1',
  90. 'href=([\'"]?)javascript:.*?\\2',
  91. 'style=([\'"]?).*?\\3',
  92. 'target=\\S+',
  93. ].join('|')})`,
  94. 'gi',
  95. );
  96. output = output.replace(badAttributes, '');
  97. output = output.replace(/(<a )/gi, '$1target=_ '); // always to new target
  98. return output;
  99. };
  100. const editor = '.editor';
  101. const selectors = [
  102. `.js-new-description-form ${editor}`,
  103. `.js-new-comment-form ${editor}`,
  104. `.js-edit-comment ${editor}`,
  105. ].join(','); // only new comment and edit comment
  106. const inputs = $(selectors);
  107. if (inputs.length === 0) {
  108. // only enable richereditor to new comment or edit comment no others
  109. enableTextarea();
  110. } else {
  111. const placeholder = inputs.attr('placeholder') || '';
  112. const mSummernotes = [];
  113. const getSummernote = function(input) {
  114. const idx = inputs.index(input);
  115. if (idx > -1) {
  116. return mSummernotes[idx];
  117. }
  118. return undefined;
  119. };
  120. inputs.each(function(idx, input) {
  121. mSummernotes[idx] = $(input).summernote({
  122. placeholder,
  123. callbacks: {
  124. onInit(object) {
  125. const originalInput = this;
  126. $(originalInput).on('submitted', function() {
  127. // when comment is submitted, the original textarea will be set to '', so shall we
  128. if (!this.value) {
  129. const sn = getSummernote(this);
  130. sn && sn.summernote('code', '');
  131. }
  132. });
  133. const jEditor = object && object.editable;
  134. const toolbar = object && object.toolbar;
  135. if (jEditor !== undefined) {
  136. jEditor.escapeableTextComplete(mentions);
  137. }
  138. if (toolbar !== undefined) {
  139. const fBtn = toolbar.find('.btn-fullscreen');
  140. fBtn.on('click', function() {
  141. const $this = $(this),
  142. isActive = $this.hasClass('active');
  143. $('.minicards,#header-quick-access').toggle(!isActive); // mini card is still showing when editor is in fullscreen mode, we hide here manually
  144. });
  145. }
  146. },
  147. onImageUpload(files) {
  148. const $summernote = getSummernote(this);
  149. if (files && files.length > 0) {
  150. const image = files[0];
  151. const currentCard = Utils.getCurrentCard();
  152. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  153. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  154. const insertImage = src => {
  155. // process all image upload types to the description/comment window
  156. const img = document.createElement('img');
  157. img.src = src;
  158. img.setAttribute('width', '100%');
  159. $summernote.summernote('insertNode', img);
  160. };
  161. const processData = function(fileObj) {
  162. Utils.processUploadedAttachment(
  163. currentCard,
  164. fileObj,
  165. attachment => {
  166. if (
  167. attachment &&
  168. attachment._id &&
  169. attachment.isImage()
  170. ) {
  171. attachment.one('uploaded', function() {
  172. const maxTry = 3;
  173. const checkItvl = 500;
  174. let retry = 0;
  175. const checkUrl = function() {
  176. // even though uploaded event fired, attachment.url() is still null somehow //TODO
  177. const url = attachment.url();
  178. if (url) {
  179. insertImage(
  180. `${location.protocol}//${location.host}${url}`,
  181. );
  182. } else {
  183. retry++;
  184. if (retry < maxTry) {
  185. setTimeout(checkUrl, checkItvl);
  186. }
  187. }
  188. };
  189. checkUrl();
  190. });
  191. }
  192. },
  193. );
  194. };
  195. if (MAX_IMAGE_PIXEL) {
  196. const reader = new FileReader();
  197. reader.onload = function(e) {
  198. const dataurl = e && e.target && e.target.result;
  199. if (dataurl !== undefined) {
  200. // need to shrink image
  201. Utils.shrinkImage({
  202. dataurl,
  203. maxSize: MAX_IMAGE_PIXEL,
  204. ratio: COMPRESS_RATIO,
  205. toBlob: true,
  206. callback(blob) {
  207. if (blob !== false) {
  208. blob.name = image.name;
  209. processData(blob);
  210. }
  211. },
  212. });
  213. }
  214. };
  215. reader.readAsDataURL(image);
  216. } else {
  217. processData(image);
  218. }
  219. }
  220. },
  221. onPaste(e) {
  222. var clipboardData = e.clipboardData;
  223. var pastedData = clipboardData.getData('Text');
  224. //if pasted data is an image, exit
  225. if (!pastedData.length) {
  226. e.preventDefault();
  227. return;
  228. }
  229. // clear up unwanted tag info when user pasted in text
  230. const thisNote = this;
  231. const updatePastedText = function(object) {
  232. const someNote = getSummernote(object);
  233. // Fix Pasting text into a card is adding a line before and after
  234. // (and multiplies by pasting more) by changing paste "p" to "br".
  235. // Fixes https://github.com/wekan/wekan/2890 .
  236. // == Fix Start ==
  237. someNote.execCommand('defaultParagraphSeparator', false, 'br');
  238. // == Fix End ==
  239. const original = someNote.summernote('code');
  240. const cleaned = cleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
  241. someNote.summernote('code', ''); //clear original
  242. someNote.summernote('pasteHTML', cleaned); //this sets the displayed content editor to the cleaned pasted code.
  243. };
  244. setTimeout(function() {
  245. //this kinda sucks, but if you don't do a setTimeout,
  246. //the function is called before the text is really pasted.
  247. updatePastedText(thisNote);
  248. }, 10);
  249. },
  250. },
  251. dialogsInBody: true,
  252. spellCheck: true,
  253. disableGrammar: false,
  254. disableDragAndDrop: false,
  255. toolbar,
  256. popover: {
  257. image: [
  258. ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
  259. ['float', ['floatLeft', 'floatRight', 'floatNone']],
  260. ['remove', ['removeMedia']],
  261. ],
  262. link: [['link', ['linkDialogShow', 'unlink']]],
  263. table: [
  264. ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']],
  265. ['delete', ['deleteRow', 'deleteCol', 'deleteTable']],
  266. ],
  267. air: [
  268. ['color', ['color']],
  269. ['font', ['bold', 'underline', 'clear']],
  270. ],
  271. },
  272. height: 200,
  273. });
  274. });
  275. }
  276. } else {
  277. enableTextarea();
  278. }
  279. });
  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 = Boards.findOne(Session.get('currentBoard'));
  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. window.open(href, '_blank');
  384. }
  385. }
  386. if (prevent) {
  387. event.stopPropagation();
  388. // XXX We hijack the build-in browser action because we currently don't have
  389. // `_blank` attributes in viewer links, and the transformer function is
  390. // handled by a third party package that we can't configure easily. Fix that
  391. // by using directly `_blank` attribute in the rendered HTML.
  392. event.preventDefault();
  393. }
  394. },
  395. });