editor.js 14 KB

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