editor.js 14 KB

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