editor.js 14 KB

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