editor.js 14 KB

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