editor.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 currentCard = Cards.findOne(Session.get('currentCard'));
  179. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  180. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  181. const insertImage = src => {
  182. const img = document.createElement('img');
  183. img.src = src;
  184. img.setAttribute('width', '100%');
  185. $summernote.summernote('insertNode', img);
  186. };
  187. const processData = function(fileObj) {
  188. Utils.processUploadedAttachment(
  189. currentCard,
  190. fileObj,
  191. attachment => {
  192. if (
  193. attachment &&
  194. attachment._id &&
  195. attachment.isImage()
  196. ) {
  197. attachment.one('uploaded', function() {
  198. const maxTry = 3;
  199. const checkItvl = 500;
  200. let retry = 0;
  201. const checkUrl = function() {
  202. // even though uploaded event fired, attachment.url() is still null somehow //TODO
  203. const url = attachment.url();
  204. if (url) {
  205. insertImage(url);
  206. } else {
  207. retry++;
  208. if (retry < maxTry) {
  209. setTimeout(checkUrl, checkItvl);
  210. }
  211. }
  212. };
  213. checkUrl();
  214. });
  215. }
  216. },
  217. );
  218. };
  219. if (MAX_IMAGE_PIXEL) {
  220. const reader = new FileReader();
  221. reader.onload = function(e) {
  222. const dataurl = e && e.target && e.target.result;
  223. if (dataurl !== undefined) {
  224. // need to shrink image
  225. Utils.shrinkImage({
  226. dataurl,
  227. maxSize: MAX_IMAGE_PIXEL,
  228. ratio: COMPRESS_RATIO,
  229. toBlob: true,
  230. callback(blob) {
  231. if (blob !== false) {
  232. blob.name = image.name;
  233. processData(blob);
  234. }
  235. },
  236. });
  237. }
  238. };
  239. reader.readAsDataURL(image);
  240. } else {
  241. processData(image);
  242. }
  243. }
  244. },
  245. onPaste() {
  246. // clear up unwanted tag info when user pasted in text
  247. const thisNote = this;
  248. const updatePastedText = function(object) {
  249. const someNote = getSummernote(object);
  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. // XXX I believe we should compute a HTML rendered field on the server that
  292. // would handle markdown and user mentions. We can simply have two
  293. // fields, one source, and one compiled version (in HTML) and send only the
  294. // compiled version to most users -- who don't need to edit.
  295. // In the meantime, all the transformation are done on the client using the
  296. // Blaze API.
  297. const at = HTML.CharRef({ html: '&commat;', str: '@' });
  298. Blaze.Template.registerHelper(
  299. 'mentions',
  300. new Template('mentions', function() {
  301. const view = this;
  302. let content = Blaze.toHTML(view.templateContentBlock);
  303. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  304. if (!currentBoard) return HTML.Raw(sanitizeXss(content));
  305. const knowedUsers = currentBoard.members.map(member => {
  306. const u = Users.findOne(member.userId);
  307. if (u) {
  308. member.username = u.username;
  309. }
  310. return member;
  311. });
  312. const mentionRegex = /\B@([\w.]*)/gi;
  313. let currentMention;
  314. while ((currentMention = mentionRegex.exec(content)) !== null) {
  315. const [fullMention, username] = currentMention;
  316. const knowedUser = _.findWhere(knowedUsers, { username });
  317. if (!knowedUser) {
  318. continue;
  319. }
  320. const linkValue = [' ', at, knowedUser.username];
  321. let linkClass = 'atMention js-open-member';
  322. if (knowedUser.userId === Meteor.userId()) {
  323. linkClass += ' me';
  324. }
  325. const link = HTML.A(
  326. {
  327. class: linkClass,
  328. // XXX Hack. Since we stringify this render function result below with
  329. // `Blaze.toHTML` we can't rely on blaze data contexts to pass the
  330. // `userId` to the popup as usual, and we need to store it in the DOM
  331. // using a data attribute.
  332. 'data-userId': knowedUser.userId,
  333. },
  334. linkValue,
  335. );
  336. content = content.replace(fullMention, Blaze.toHTML(link));
  337. }
  338. return HTML.Raw(sanitizeXss(content));
  339. }),
  340. );
  341. Template.viewer.events({
  342. // Viewer sometimes have click-able wrapper around them (for instance to edit
  343. // the corresponding text). Clicking a link shouldn't fire these actions, stop
  344. // we stop these event at the viewer component level.
  345. 'click a'(event, templateInstance) {
  346. let prevent = true;
  347. const userId = event.currentTarget.dataset.userid;
  348. if (userId) {
  349. Popup.open('member').call({ userId }, event, templateInstance);
  350. } else {
  351. const href = event.currentTarget.href;
  352. const child = event.currentTarget.firstElementChild;
  353. if (child && child.tagName === 'IMG') {
  354. prevent = false;
  355. } else if (href) {
  356. window.open(href, '_blank');
  357. }
  358. }
  359. if (prevent) {
  360. event.stopPropagation();
  361. // XXX We hijack the build-in browser action because we currently don't have
  362. // `_blank` attributes in viewer links, and the transformer function is
  363. // handled by a third party package that we can't configure easily. Fix that
  364. // by using directly `_blank` attribute in the rendered HTML.
  365. event.preventDefault();
  366. }
  367. },
  368. });