editor.js 15 KB

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