editor.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import _sanitizeXss from 'xss';
  2. const sanitizeXss = (input, options) => {
  3. const defaultAllowedIframeSrc = /^(https:){0,1}\/\/.*?(youtube|vimeo|dailymotion|youku)/i;
  4. const allowedIframeSrcRegex = (function() {
  5. let reg = defaultAllowedIframeSrc;
  6. const SAFE_IFRAME_SRC_PATTERN =
  7. Meteor.settings.public.SAFE_IFRAME_SRC_PATTERN;
  8. try {
  9. if (SAFE_IFRAME_SRC_PATTERN !== undefined) {
  10. reg = new RegExp(SAFE_IFRAME_SRC_PATTERN, 'i');
  11. }
  12. } catch (e) {
  13. /*eslint no-console: ["error", { allow: ["warn", "error"] }] */
  14. console.error('Wrong pattern specified', SAFE_IFRAM_SRC_PATTERN, e);
  15. }
  16. return reg;
  17. })();
  18. const targetWindow = '_blank';
  19. options = {
  20. onTag(tag, html, options) {
  21. if (tag === 'iframe') {
  22. const clipCls = 'note-vide-clip';
  23. if (!options.isClosing) {
  24. const srcp = /src=(['"]{0,1})(\S*)(\1)/;
  25. let safe = html.indexOf(`class="${clipCls}"`) > -1;
  26. if (srcp.exec(html)) {
  27. const src = RegExp.$2;
  28. if (allowedIframeSrcRegex.exec(src)) {
  29. safe = true;
  30. }
  31. if (safe)
  32. return `<iframe src='${src}' class="${clipCls}" width=100% height=auto allowfullscreen></iframe>`;
  33. }
  34. } else {
  35. return '';
  36. }
  37. } else if (tag === 'a') {
  38. if (!options.isClosing) {
  39. if (/href=(['"]{0,1})(\S*)(\1)/.exec(html)) {
  40. const href = RegExp.$2;
  41. if (href.match(/^((http(s){0,1}:){0,1}\/\/|\/)/)) {
  42. // a valid url
  43. return `<a href=${href} target=${targetWindow}>`;
  44. }
  45. }
  46. }
  47. } else if (tag === 'img') {
  48. if (!options.isClosing) {
  49. if (new RegExp('src=([\'"]{0,1})(\\S*)(\\1)').exec(html)) {
  50. const src = RegExp.$2;
  51. return `<a href='${src}' class='swipebox'><img src='${src}' class="attachment-image-preview mCS_img_loaded"></a>`;
  52. }
  53. }
  54. }
  55. return undefined;
  56. },
  57. onTagAttr(tag, name, value) {
  58. if (tag === 'img' && name === 'src') {
  59. if (value && value.substr(0, 5) === 'data:') {
  60. // allow image with dataURI src
  61. return `${name}='${value}'`;
  62. }
  63. } else if (tag === 'a' && name === 'target') {
  64. return `${name}='${targetWindow}'`; // always change a href target to a new window
  65. }
  66. return undefined;
  67. },
  68. ...options,
  69. };
  70. return _sanitizeXss(input, options);
  71. };
  72. Template.editor.onRendered(() => {
  73. const textareaSelector = 'textarea';
  74. const mentions = [
  75. // User mentions
  76. {
  77. match: /\B@([\w.]*)$/,
  78. search(term, callback) {
  79. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  80. callback(
  81. currentBoard
  82. .activeMembers()
  83. .map(member => {
  84. const username = Users.findOne(member.userId).username;
  85. return username.includes(term) ? username : null;
  86. })
  87. .filter(Boolean),
  88. );
  89. },
  90. template(value) {
  91. return value;
  92. },
  93. replace(username) {
  94. return `@${username} `;
  95. },
  96. index: 1,
  97. },
  98. ];
  99. const enableTextarea = function() {
  100. const $textarea = this.$(textareaSelector);
  101. autosize($textarea);
  102. $textarea.escapeableTextComplete(mentions);
  103. };
  104. if (Meteor.settings.public.RICHER_CARD_COMMENT_EDITOR !== false) {
  105. const isSmall = Utils.isMiniScreen();
  106. const toolbar = isSmall
  107. ? [
  108. ['view', ['fullscreen']],
  109. ['table', ['table']],
  110. ['font', ['bold', 'underline']],
  111. //['fontsize', ['fontsize']],
  112. ['color', ['color']],
  113. ]
  114. : [
  115. ['style', ['style']],
  116. ['font', ['bold', 'underline', 'clear']],
  117. ['fontsize', ['fontsize']],
  118. ['fontname', ['fontname']],
  119. ['color', ['color']],
  120. ['para', ['ul', 'ol', 'paragraph']],
  121. ['table', ['table']],
  122. ['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
  123. //['insert', ['link', 'picture']], // modal popup has issue somehow :(
  124. ['view', ['fullscreen', 'help']],
  125. ];
  126. const cleanPastedHTML = sanitizeXss;
  127. const editor = '.editor';
  128. const selectors = [
  129. `.js-new-comment-form ${editor}`,
  130. `.js-edit-comment ${editor}`,
  131. ].join(','); // only new comment and edit comment
  132. const inputs = $(selectors);
  133. if (inputs.length === 0) {
  134. // only enable richereditor to new comment or edit comment no others
  135. enableTextarea();
  136. } else {
  137. const placeholder = inputs.attr('placeholder') || '';
  138. const mSummernotes = [];
  139. const getSummernote = function(input) {
  140. const idx = inputs.index(input);
  141. if (idx > -1) {
  142. return mSummernotes[idx];
  143. }
  144. return undefined;
  145. };
  146. inputs.each(function(idx, input) {
  147. mSummernotes[idx] = $(input).summernote({
  148. placeholder,
  149. callbacks: {
  150. onInit(object) {
  151. const originalInput = this;
  152. $(originalInput).on('submitted', function() {
  153. // resetCommentInput has been called
  154. if (!this.value) {
  155. const sn = getSummernote(this);
  156. sn && sn.summernote('reset');
  157. object && object.editingArea.find('.note-placeholder').show();
  158. }
  159. });
  160. const jEditor = object && object.editable;
  161. const toolbar = object && object.toolbar;
  162. if (jEditor !== undefined) {
  163. jEditor.escapeableTextComplete(mentions);
  164. }
  165. if (toolbar !== undefined) {
  166. const fBtn = toolbar.find('.btn-fullscreen');
  167. fBtn.on('click', function() {
  168. const $this = $(this),
  169. isActive = $this.hasClass('active');
  170. $('.minicards').toggle(!isActive); // mini card is still showing when editor is in fullscreen mode, we hide here manually
  171. });
  172. }
  173. },
  174. onImageUpload(files) {
  175. const $summernote = getSummernote(this);
  176. if (files && files.length > 0) {
  177. const image = files[0];
  178. const reader = new FileReader();
  179. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  180. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  181. const processData = function(dataURL) {
  182. const img = document.createElement('img');
  183. img.src = dataURL;
  184. img.setAttribute('width', '100%');
  185. $summernote.summernote('insertNode', img);
  186. };
  187. reader.onload = function(e) {
  188. const dataurl = e && e.target && e.target.result;
  189. if (dataurl !== undefined) {
  190. if (MAX_IMAGE_PIXEL) {
  191. // need to shrink image
  192. Utils.shrinkImage({
  193. dataurl,
  194. maxSize: MAX_IMAGE_PIXEL,
  195. ratio: COMPRESS_RATIO,
  196. callback(changed) {
  197. if (changed !== false && !!changed) {
  198. processData(changed);
  199. }
  200. },
  201. });
  202. } else {
  203. processData(dataurl);
  204. }
  205. }
  206. };
  207. reader.readAsDataURL(image);
  208. }
  209. },
  210. onPaste() {
  211. // clear up unwanted tag info when user pasted in text
  212. const thisNote = this;
  213. const updatePastedText = function(object) {
  214. const someNote = getSummernote(object);
  215. const original = someNote.summernote('code');
  216. const cleaned = cleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
  217. someNote.summernote('reset'); //clear original
  218. someNote.summernote('pasteHTML', cleaned); //this sets the displayed content editor to the cleaned pasted code.
  219. };
  220. setTimeout(function() {
  221. //this kinda sucks, but if you don't do a setTimeout,
  222. //the function is called before the text is really pasted.
  223. updatePastedText(thisNote);
  224. }, 10);
  225. },
  226. },
  227. dialogsInBody: true,
  228. disableDragAndDrop: true,
  229. toolbar,
  230. popover: {
  231. image: [
  232. [
  233. 'image',
  234. ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone'],
  235. ],
  236. ['float', ['floatLeft', 'floatRight', 'floatNone']],
  237. ['remove', ['removeMedia']],
  238. ],
  239. table: [
  240. ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']],
  241. ['delete', ['deleteRow', 'deleteCol', 'deleteTable']],
  242. ],
  243. air: [
  244. ['color', ['color']],
  245. ['font', ['bold', 'underline', 'clear']],
  246. ],
  247. },
  248. height: 200,
  249. });
  250. });
  251. }
  252. } else {
  253. enableTextarea();
  254. }
  255. });
  256. // XXX I believe we should compute a HTML rendered field on the server that
  257. // would handle markdown and user mentions. We can simply have two
  258. // fields, one source, and one compiled version (in HTML) and send only the
  259. // compiled version to most users -- who don't need to edit.
  260. // In the meantime, all the transformation are done on the client using the
  261. // Blaze API.
  262. const at = HTML.CharRef({ html: '&commat;', str: '@' });
  263. Blaze.Template.registerHelper(
  264. 'mentions',
  265. new Template('mentions', function() {
  266. const view = this;
  267. let content = Blaze.toHTML(view.templateContentBlock);
  268. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  269. if (!currentBoard) return HTML.Raw(sanitizeXss(content));
  270. const knowedUsers = currentBoard.members.map(member => {
  271. const u = Users.findOne(member.userId);
  272. if (u) {
  273. member.username = u.username;
  274. }
  275. return member;
  276. });
  277. const mentionRegex = /\B@([\w.]*)/gi;
  278. let currentMention;
  279. while ((currentMention = mentionRegex.exec(content)) !== null) {
  280. const [fullMention, username] = currentMention;
  281. const knowedUser = _.findWhere(knowedUsers, { username });
  282. if (!knowedUser) {
  283. continue;
  284. }
  285. const linkValue = [' ', at, knowedUser.username];
  286. let linkClass = 'atMention js-open-member';
  287. if (knowedUser.userId === Meteor.userId()) {
  288. linkClass += ' me';
  289. }
  290. const link = HTML.A(
  291. {
  292. class: linkClass,
  293. // XXX Hack. Since we stringify this render function result below with
  294. // `Blaze.toHTML` we can't rely on blaze data contexts to pass the
  295. // `userId` to the popup as usual, and we need to store it in the DOM
  296. // using a data attribute.
  297. 'data-userId': knowedUser.userId,
  298. },
  299. linkValue,
  300. );
  301. content = content.replace(fullMention, Blaze.toHTML(link));
  302. }
  303. return HTML.Raw(sanitizeXss(content));
  304. }),
  305. );
  306. Template.viewer.events({
  307. // Viewer sometimes have click-able wrapper around them (for instance to edit
  308. // the corresponding text). Clicking a link shouldn't fire these actions, stop
  309. // we stop these event at the viewer component level.
  310. 'click a'(event, templateInstance) {
  311. let prevent = true;
  312. const userId = event.currentTarget.dataset.userid;
  313. if (userId) {
  314. Popup.open('member').call({ userId }, event, templateInstance);
  315. } else {
  316. const href = event.currentTarget.href;
  317. const child = event.currentTarget.firstElementChild;
  318. if (child && child.tagName === 'IMG') {
  319. prevent = false;
  320. } else if (href) {
  321. window.open(href, '_blank');
  322. }
  323. }
  324. if (prevent) {
  325. event.stopPropagation();
  326. // XXX We hijack the build-in browser action because we currently don't have
  327. // `_blank` attributes in viewer links, and the transformer function is
  328. // handled by a third party package that we can't configure easily. Fix that
  329. // by using directly `_blank` attribute in the rendered HTML.
  330. event.preventDefault();
  331. }
  332. },
  333. });