editor.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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-comment-form ${editor}`,
  95. `.js-edit-comment ${editor}`,
  96. ].join(','); // only new comment and edit comment
  97. const inputs = $(selectors);
  98. if (inputs.length === 0) {
  99. // only enable richereditor to new comment or edit comment no others
  100. enableTextarea();
  101. } else {
  102. const placeholder = inputs.attr('placeholder') || '';
  103. const mSummernotes = [];
  104. const getSummernote = function(input) {
  105. const idx = inputs.index(input);
  106. if (idx > -1) {
  107. return mSummernotes[idx];
  108. }
  109. return undefined;
  110. };
  111. inputs.each(function(idx, input) {
  112. mSummernotes[idx] = $(input).summernote({
  113. placeholder,
  114. callbacks: {
  115. onInit(object) {
  116. const originalInput = this;
  117. $(originalInput).on('submitted', function() {
  118. // when comment is submitted, the original textarea will be set to '', so shall we
  119. if (!this.value) {
  120. const sn = getSummernote(this);
  121. sn && sn.summernote('code', '');
  122. }
  123. });
  124. const jEditor = object && object.editable;
  125. const toolbar = object && object.toolbar;
  126. if (jEditor !== undefined) {
  127. jEditor.escapeableTextComplete(mentions);
  128. }
  129. if (toolbar !== undefined) {
  130. const fBtn = toolbar.find('.btn-fullscreen');
  131. fBtn.on('click', function() {
  132. const $this = $(this),
  133. isActive = $this.hasClass('active');
  134. $('.minicards,#header-quick-access').toggle(!isActive); // mini card is still showing when editor is in fullscreen mode, we hide here manually
  135. });
  136. }
  137. },
  138. onImageUpload(files) {
  139. const $summernote = getSummernote(this);
  140. if (files && files.length > 0) {
  141. const image = files[0];
  142. const currentCard = Cards.findOne(Session.get('currentCard'));
  143. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  144. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  145. const insertImage = src => {
  146. const img = document.createElement('img');
  147. img.src = src;
  148. img.setAttribute('width', '100%');
  149. $summernote.summernote('insertNode', img);
  150. };
  151. const processData = function(fileObj) {
  152. Utils.processUploadedAttachment(
  153. currentCard,
  154. fileObj,
  155. { onUploaded:
  156. attachment => {
  157. if (attachment && attachment._id && attachment.isImage) {
  158. attachment.one('uploaded', function() {
  159. const maxTry = 3;
  160. const checkItvl = 500;
  161. let retry = 0;
  162. const checkUrl = function() {
  163. // even though uploaded event fired, attachment.url() is still null somehow //TODO
  164. const url = Attachments.link(attachment, 'original', '/');
  165. if (url) {
  166. insertImage(
  167. `${location.protocol}//${location.host}${url}`,
  168. );
  169. } else {
  170. retry++;
  171. if (retry < maxTry) {
  172. setTimeout(checkUrl, checkItvl);
  173. }
  174. }
  175. };
  176. checkUrl();
  177. });
  178. }
  179. }
  180. },
  181. );
  182. };
  183. if (MAX_IMAGE_PIXEL) {
  184. const reader = new FileReader();
  185. reader.onload = function(e) {
  186. const dataurl = e && e.target && e.target.result;
  187. if (dataurl !== undefined) {
  188. // need to shrink image
  189. Utils.shrinkImage({
  190. dataurl,
  191. maxSize: MAX_IMAGE_PIXEL,
  192. ratio: COMPRESS_RATIO,
  193. toBlob: true,
  194. callback(blob) {
  195. if (blob !== false) {
  196. blob.name = image.name;
  197. processData(blob);
  198. }
  199. },
  200. });
  201. }
  202. };
  203. reader.readAsDataURL(image);
  204. } else {
  205. processData(image);
  206. }
  207. }
  208. },
  209. onPaste() {
  210. // clear up unwanted tag info when user pasted in text
  211. const thisNote = this;
  212. const updatePastedText = function(object) {
  213. const someNote = getSummernote(object);
  214. // Fix Pasting text into a card is adding a line before and after
  215. // (and multiplies by pasting more) by changing paste "p" to "br".
  216. // Fixes https://github.com/wekan/wekan/2890 .
  217. // == Fix Start ==
  218. someNote.execCommand('defaultParagraphSeparator', false, 'br');
  219. // == Fix End ==
  220. const original = someNote.summernote('code');
  221. const cleaned = cleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
  222. someNote.summernote('code', ''); //clear original
  223. someNote.summernote('pasteHTML', cleaned); //this sets the displayed content editor to the cleaned pasted code.
  224. };
  225. setTimeout(function() {
  226. //this kinda sucks, but if you don't do a setTimeout,
  227. //the function is called before the text is really pasted.
  228. updatePastedText(thisNote);
  229. }, 10);
  230. },
  231. },
  232. dialogsInBody: true,
  233. disableDragAndDrop: true,
  234. toolbar,
  235. popover: {
  236. image: [
  237. [
  238. 'image',
  239. ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone'],
  240. ],
  241. ['float', ['floatLeft', 'floatRight', 'floatNone']],
  242. ['remove', ['removeMedia']],
  243. ],
  244. table: [
  245. ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']],
  246. ['delete', ['deleteRow', 'deleteCol', 'deleteTable']],
  247. ],
  248. air: [
  249. ['color', ['color']],
  250. ['font', ['bold', 'underline', 'clear']],
  251. ],
  252. },
  253. height: 200,
  254. });
  255. });
  256. }
  257. } else {
  258. enableTextarea();
  259. }
  260. });
  261. import sanitizeXss from 'xss';
  262. // XXX I believe we should compute a HTML rendered field on the server that
  263. // would handle markdown and user mentions. We can simply have two
  264. // fields, one source, and one compiled version (in HTML) and send only the
  265. // compiled version to most users -- who don't need to edit.
  266. // In the meantime, all the transformation are done on the client using the
  267. // Blaze API.
  268. const at = HTML.CharRef({ html: '&commat;', str: '@' });
  269. Blaze.Template.registerHelper(
  270. 'mentions',
  271. new Template('mentions', function() {
  272. const view = this;
  273. let content = Blaze.toHTML(view.templateContentBlock);
  274. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  275. if (!currentBoard) return HTML.Raw(sanitizeXss(content));
  276. const knowedUsers = currentBoard.members.map(member => {
  277. const u = Users.findOne(member.userId);
  278. if (u) {
  279. member.username = u.username;
  280. }
  281. return member;
  282. });
  283. const mentionRegex = /\B@([\w.]*)/gi;
  284. let currentMention;
  285. while ((currentMention = mentionRegex.exec(content)) !== null) {
  286. const [fullMention, quoteduser, simple] = currentMention;
  287. const username = quoteduser || simple;
  288. const knowedUser = _.findWhere(knowedUsers, { username });
  289. if (!knowedUser) {
  290. continue;
  291. }
  292. const linkValue = [' ', at, knowedUser.username];
  293. let linkClass = 'atMention js-open-member';
  294. if (knowedUser.userId === Meteor.userId()) {
  295. linkClass += ' me';
  296. }
  297. // This @user mention link generation did open same Wekan
  298. // window in new tab, so now A is changed to U so it's
  299. // underlined and there is no link popup. This way also
  300. // text can be selected more easily.
  301. //const link = HTML.A(
  302. const link = HTML.U(
  303. {
  304. class: linkClass,
  305. // XXX Hack. Since we stringify this render function result below with
  306. // `Blaze.toHTML` we can't rely on blaze data contexts to pass the
  307. // `userId` to the popup as usual, and we need to store it in the DOM
  308. // using a data attribute.
  309. 'data-userId': knowedUser.userId,
  310. },
  311. linkValue,
  312. );
  313. content = content.replace(fullMention, Blaze.toHTML(link));
  314. }
  315. return HTML.Raw(sanitizeXss(content));
  316. }),
  317. );
  318. Template.viewer.events({
  319. // Viewer sometimes have click-able wrapper around them (for instance to edit
  320. // the corresponding text). Clicking a link shouldn't fire these actions, stop
  321. // we stop these event at the viewer component level.
  322. 'click a'(event, templateInstance) {
  323. const prevent = true;
  324. const userId = event.currentTarget.dataset.userid;
  325. if (userId) {
  326. Popup.open('member').call({ userId }, event, templateInstance);
  327. } else {
  328. const href = event.currentTarget.href;
  329. if (href) {
  330. window.open(href, '_blank');
  331. }
  332. }
  333. if (prevent) {
  334. event.stopPropagation();
  335. // XXX We hijack the build-in browser action because we currently don't have
  336. // `_blank` attributes in viewer links, and the transformer function is
  337. // handled by a third party package that we can't configure easily. Fix that
  338. // by using directly `_blank` attribute in the rendered HTML.
  339. event.preventDefault();
  340. }
  341. },
  342. });