2
0

editor.js 15 KB

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