2
0

editor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 user = Users.findOne(member.userId);
  97. if (user._id === Meteor.userId()) {
  98. return null;
  99. }
  100. const value = user.username;
  101. const username =
  102. value && value.match(/\s+/) ? `"${value}"` : value;
  103. return username.includes(term) ? username : null;
  104. })
  105. .filter(Boolean),
  106. );
  107. },
  108. template(value) {
  109. return value;
  110. },
  111. replace(username) {
  112. return `@${username} `;
  113. },
  114. index: 1,
  115. },
  116. ];
  117. const enableTextarea = function() {
  118. const $textarea = this.$(textareaSelector);
  119. autosize($textarea);
  120. $textarea.escapeableTextComplete(mentions);
  121. };
  122. if (Meteor.settings.public.RICHER_CARD_COMMENT_EDITOR !== false) {
  123. const isSmall = Utils.isMiniScreen();
  124. const toolbar = isSmall
  125. ? [
  126. ['view', ['fullscreen']],
  127. ['table', ['table']],
  128. ['font', ['bold']],
  129. ['color', ['color']],
  130. ['insert', ['video']], // iframe tag will be sanitized TODO if iframe[class=note-video-clip] can be added into safe list, insert video can be enabled
  131. //['fontsize', ['fontsize']],
  132. ]
  133. : [
  134. ['style', ['style']],
  135. ['font', ['bold', 'underline', 'clear']],
  136. ['fontsize', ['fontsize']],
  137. ['fontname', ['fontname']],
  138. ['color', ['color']],
  139. ['para', ['ul', 'ol', 'paragraph']],
  140. ['table', ['table']],
  141. ['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
  142. //['insert', ['link', 'picture']], // modal popup has issue somehow :(
  143. ['view', ['fullscreen', 'help']],
  144. ];
  145. const cleanPastedHTML = sanitizeXss;
  146. const editor = '.editor';
  147. const selectors = [
  148. `.js-new-comment-form ${editor}`,
  149. `.js-edit-comment ${editor}`,
  150. ].join(','); // only new comment and edit comment
  151. const inputs = $(selectors);
  152. if (inputs.length === 0) {
  153. // only enable richereditor to new comment or edit comment no others
  154. enableTextarea();
  155. } else {
  156. const placeholder = inputs.attr('placeholder') || '';
  157. const mSummernotes = [];
  158. const getSummernote = function(input) {
  159. const idx = inputs.index(input);
  160. if (idx > -1) {
  161. return mSummernotes[idx];
  162. }
  163. return undefined;
  164. };
  165. let popupShown = false;
  166. inputs.each(function(idx, input) {
  167. mSummernotes[idx] = $(input).summernote({
  168. placeholder,
  169. callbacks: {
  170. onKeydown(e) {
  171. if (popupShown) {
  172. e.preventDefault();
  173. }
  174. },
  175. onKeyup(e) {
  176. if (popupShown) {
  177. e.preventDefault();
  178. }
  179. },
  180. onInit(object) {
  181. const originalInput = this;
  182. const setAutocomplete = function(jEditor) {
  183. if (jEditor !== undefined) {
  184. jEditor.escapeableTextComplete(mentions).on({
  185. 'textComplete:show'() {
  186. popupShown = true;
  187. },
  188. 'textComplete:hide'() {
  189. popupShown = false;
  190. },
  191. });
  192. }
  193. };
  194. $(originalInput).on('submitted', function() {
  195. // resetCommentInput has been called
  196. if (!this.value) {
  197. const sn = getSummernote(this);
  198. sn && sn.summernote('code', '');
  199. }
  200. });
  201. const jEditor = object && object.editable;
  202. const toolbar = object && object.toolbar;
  203. setAutocomplete(jEditor);
  204. if (toolbar !== undefined) {
  205. const fBtn = toolbar.find('.btn-fullscreen');
  206. fBtn.on('click', function() {
  207. const $this = $(this),
  208. isActive = $this.hasClass('active');
  209. $('.minicards,#header-quick-access').toggle(!isActive); // mini card is still showing when editor is in fullscreen mode, we hide here manually
  210. });
  211. }
  212. },
  213. onImageUpload(files) {
  214. const $summernote = getSummernote(this);
  215. if (files && files.length > 0) {
  216. const image = files[0];
  217. const currentCard = Cards.findOne(Session.get('currentCard'));
  218. const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL;
  219. const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO;
  220. const insertImage = src => {
  221. const img = document.createElement('img');
  222. img.src = src;
  223. img.setAttribute('width', '100%');
  224. $summernote.summernote('insertNode', img);
  225. };
  226. const processData = function(fileObj) {
  227. Utils.processUploadedAttachment(
  228. currentCard,
  229. fileObj,
  230. attachment => {
  231. if (
  232. attachment &&
  233. attachment._id &&
  234. attachment.isImage()
  235. ) {
  236. attachment.one('uploaded', function() {
  237. const maxTry = 3;
  238. const checkItvl = 500;
  239. let retry = 0;
  240. const checkUrl = function() {
  241. // even though uploaded event fired, attachment.url() is still null somehow //TODO
  242. const url = attachment.url();
  243. if (url) {
  244. insertImage(
  245. `${location.protocol}//${location.host}${url}`,
  246. );
  247. } else {
  248. retry++;
  249. if (retry < maxTry) {
  250. setTimeout(checkUrl, checkItvl);
  251. }
  252. }
  253. };
  254. checkUrl();
  255. });
  256. }
  257. },
  258. );
  259. };
  260. if (MAX_IMAGE_PIXEL) {
  261. const reader = new FileReader();
  262. reader.onload = function(e) {
  263. const dataurl = e && e.target && e.target.result;
  264. if (dataurl !== undefined) {
  265. // need to shrink image
  266. Utils.shrinkImage({
  267. dataurl,
  268. maxSize: MAX_IMAGE_PIXEL,
  269. ratio: COMPRESS_RATIO,
  270. toBlob: true,
  271. callback(blob) {
  272. if (blob !== false) {
  273. blob.name = image.name;
  274. processData(blob);
  275. }
  276. },
  277. });
  278. }
  279. };
  280. reader.readAsDataURL(image);
  281. } else {
  282. processData(image);
  283. }
  284. }
  285. },
  286. onPaste() {
  287. // clear up unwanted tag info when user pasted in text
  288. const thisNote = this;
  289. const updatePastedText = function(object) {
  290. const someNote = getSummernote(object);
  291. const original = someNote.summernote('code');
  292. const cleaned = cleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
  293. someNote.summernote('code', ''); //clear original
  294. someNote.summernote('pasteHTML', cleaned); //this sets the displayed content editor to the cleaned pasted code.
  295. };
  296. setTimeout(function() {
  297. //this kinda sucks, but if you don't do a setTimeout,
  298. //the function is called before the text is really pasted.
  299. updatePastedText(thisNote);
  300. }, 10);
  301. },
  302. },
  303. dialogsInBody: true,
  304. disableDragAndDrop: true,
  305. toolbar,
  306. popover: {
  307. image: [
  308. [
  309. 'image',
  310. ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone'],
  311. ],
  312. ['float', ['floatLeft', 'floatRight', 'floatNone']],
  313. ['remove', ['removeMedia']],
  314. ],
  315. table: [
  316. ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']],
  317. ['delete', ['deleteRow', 'deleteCol', 'deleteTable']],
  318. ],
  319. air: [
  320. ['color', ['color']],
  321. ['font', ['bold', 'underline', 'clear']],
  322. ],
  323. },
  324. height: 200,
  325. });
  326. });
  327. }
  328. } else {
  329. enableTextarea();
  330. }
  331. });
  332. // XXX I believe we should compute a HTML rendered field on the server that
  333. // would handle markdown and user mentions. We can simply have two
  334. // fields, one source, and one compiled version (in HTML) and send only the
  335. // compiled version to most users -- who don't need to edit.
  336. // In the meantime, all the transformation are done on the client using the
  337. // Blaze API.
  338. const at = HTML.CharRef({ html: '&commat;', str: '@' });
  339. Blaze.Template.registerHelper(
  340. 'mentions',
  341. new Template('mentions', function() {
  342. const view = this;
  343. let content = Blaze.toHTML(view.templateContentBlock);
  344. const currentBoard = Boards.findOne(Session.get('currentBoard'));
  345. if (!currentBoard) return HTML.Raw(sanitizeXss(content));
  346. const knowedUsers = currentBoard.members.map(member => {
  347. const u = Users.findOne(member.userId);
  348. if (u) {
  349. member.username = u.username;
  350. }
  351. return member;
  352. });
  353. const mentionRegex = /\B@(?:(?:"([\w.\s]*)")|([\w.]+))/gi; // including space in username
  354. let currentMention;
  355. while ((currentMention = mentionRegex.exec(content)) !== null) {
  356. const [fullMention, quoteduser, simple] = currentMention;
  357. const username = quoteduser || simple;
  358. const knowedUser = _.findWhere(knowedUsers, { username });
  359. if (!knowedUser) {
  360. continue;
  361. }
  362. const linkValue = [' ', at, knowedUser.username];
  363. let linkClass = 'atMention js-open-member';
  364. if (knowedUser.userId === Meteor.userId()) {
  365. linkClass += ' me';
  366. }
  367. const link = HTML.A(
  368. {
  369. class: linkClass,
  370. // XXX Hack. Since we stringify this render function result below with
  371. // `Blaze.toHTML` we can't rely on blaze data contexts to pass the
  372. // `userId` to the popup as usual, and we need to store it in the DOM
  373. // using a data attribute.
  374. 'data-userId': knowedUser.userId,
  375. [ASIS]: 'true',
  376. },
  377. linkValue,
  378. );
  379. content = content.replace(fullMention, Blaze.toHTML(link));
  380. }
  381. return HTML.Raw(sanitizeXss(content));
  382. }),
  383. );
  384. Template.viewer.events({
  385. // Viewer sometimes have click-able wrapper around them (for instance to edit
  386. // the corresponding text). Clicking a link shouldn't fire these actions, stop
  387. // we stop these event at the viewer component level.
  388. 'click a'(event, templateInstance) {
  389. let prevent = true;
  390. const userId = event.currentTarget.dataset.userid;
  391. if (userId) {
  392. Popup.open('member').call({ userId }, event, templateInstance);
  393. } else {
  394. const href = event.currentTarget.href;
  395. const child = event.currentTarget.firstElementChild;
  396. if (child && child.tagName === 'IMG') {
  397. prevent = false;
  398. } else if (href) {
  399. window.open(href, '_blank');
  400. }
  401. }
  402. if (prevent) {
  403. event.stopPropagation();
  404. // XXX We hijack the build-in browser action because we currently don't have
  405. // `_blank` attributes in viewer links, and the transformer function is
  406. // handled by a third party package that we can't configure easily. Fix that
  407. // by using directly `_blank` attribute in the rendered HTML.
  408. event.preventDefault();
  409. }
  410. },
  411. });