PageEditor.jsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import loggerFactory from '@alias/logger';
  4. import { throttle, debounce } from 'throttle-debounce';
  5. import { envUtils } from 'growi-commons';
  6. import AppContainer from '../services/AppContainer';
  7. import PageContainer from '../services/PageContainer';
  8. import { createSubscribedElement } from './UnstatedUtils';
  9. import Editor from './PageEditor/Editor';
  10. import Preview from './PageEditor/Preview';
  11. import scrollSyncHelper from './PageEditor/ScrollSyncHelper';
  12. import EditorContainer from '../services/EditorContainer';
  13. const logger = loggerFactory('growi:PageEditor');
  14. class PageEditor extends React.Component {
  15. constructor(props) {
  16. super(props);
  17. const config = this.props.appContainer.getConfig();
  18. const isUploadable = config.upload.image || config.upload.file;
  19. const isUploadableFile = config.upload.file;
  20. const isMathJaxEnabled = !!config.env.MATHJAX;
  21. this.state = {
  22. markdown: this.props.pageContainer.state.markdown,
  23. isUploadable,
  24. isUploadableFile,
  25. isMathJaxEnabled,
  26. };
  27. this.setCaretLine = this.setCaretLine.bind(this);
  28. this.focusToEditor = this.focusToEditor.bind(this);
  29. this.onMarkdownChanged = this.onMarkdownChanged.bind(this);
  30. this.onSaveWithShortcut = this.onSaveWithShortcut.bind(this);
  31. this.onUpload = this.onUpload.bind(this);
  32. this.onEditorScroll = this.onEditorScroll.bind(this);
  33. this.onEditorScrollCursorIntoView = this.onEditorScrollCursorIntoView.bind(this);
  34. this.onPreviewScroll = this.onPreviewScroll.bind(this);
  35. this.saveDraft = this.saveDraft.bind(this);
  36. this.clearDraft = this.clearDraft.bind(this);
  37. // get renderer
  38. this.growiRenderer = this.props.appContainer.getRenderer('editor');
  39. // for scrolling
  40. this.lastScrolledDateWithCursor = null;
  41. this.isOriginOfScrollSyncEditor = false;
  42. this.isOriginOfScrollSyncEditor = false;
  43. // create throttled function
  44. this.scrollPreviewByEditorLineWithThrottle = throttle(20, this.scrollPreviewByEditorLine);
  45. this.scrollPreviewByCursorMovingWithThrottle = throttle(20, this.scrollPreviewByCursorMoving);
  46. this.scrollEditorByPreviewScrollWithThrottle = throttle(20, this.scrollEditorByPreviewScroll);
  47. this.renderPreviewWithDebounce = debounce(50, throttle(100, this.renderPreview));
  48. this.saveDraftWithDebounce = debounce(800, this.saveDraft);
  49. }
  50. componentWillMount() {
  51. this.props.appContainer.registerComponentInstance('PageEditor', this);
  52. // initial rendering
  53. this.renderPreview(this.state.markdown);
  54. }
  55. getMarkdown() {
  56. return this.state.markdown;
  57. }
  58. updateEditorValue(markdown) {
  59. this.editor.setValue(markdown);
  60. }
  61. focusToEditor() {
  62. this.editor.forceToFocus();
  63. }
  64. /**
  65. * set caret position of editor
  66. * @param {number} line
  67. */
  68. setCaretLine(line) {
  69. this.editor.setCaretLine(line);
  70. scrollSyncHelper.scrollPreview(this.previewElement, line);
  71. }
  72. /**
  73. * the change event handler for `markdown` state
  74. * @param {string} value
  75. */
  76. onMarkdownChanged(value) {
  77. this.renderPreviewWithDebounce(value);
  78. this.saveDraftWithDebounce();
  79. }
  80. /**
  81. * save and update state of containers
  82. */
  83. async onSaveWithShortcut() {
  84. const { pageContainer, editorContainer } = this.props;
  85. const optionsToSave = editorContainer.getCurrentOptionsToSave();
  86. try {
  87. // disable unsaved warning
  88. editorContainer.disableUnsavedWarning();
  89. // eslint-disable-next-line no-unused-vars
  90. const { page, tags } = await pageContainer.save(this.state.markdown, optionsToSave);
  91. logger.debug('success to save');
  92. pageContainer.showSuccessToastr();
  93. // update state of EditorContainer
  94. editorContainer.setState({ tags });
  95. }
  96. catch (error) {
  97. logger.error('failed to save', error);
  98. pageContainer.showErrorToastr(error);
  99. }
  100. }
  101. /**
  102. * the upload event handler
  103. * @param {any} file
  104. */
  105. async onUpload(file) {
  106. const { appContainer, pageContainer } = this.props;
  107. try {
  108. let res = await appContainer.apiGet('/attachments.limit', {
  109. fileSize: file.size,
  110. });
  111. if (!res.isUploadable) {
  112. throw new Error(res.errorMessage);
  113. }
  114. const formData = new FormData();
  115. const { pageId, path } = pageContainer.state;
  116. formData.append('_csrf', appContainer.csrfToken);
  117. formData.append('file', file);
  118. formData.append('path', path);
  119. if (pageId != null) {
  120. formData.append('page_id', pageContainer.state.pageId);
  121. }
  122. res = await appContainer.apiPost('/attachments.add', formData);
  123. const attachment = res.attachment;
  124. const fileName = attachment.originalName;
  125. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  126. // when image
  127. if (attachment.fileFormat.startsWith('image/')) {
  128. // modify to "![fileName](url)" syntax
  129. insertText = `!${insertText}`;
  130. }
  131. this.editor.insertText(insertText);
  132. // when if created newly
  133. if (res.pageCreated) {
  134. logger.info('Page is created', res.page._id);
  135. pageContainer.updateStateAfterSave(res.page);
  136. }
  137. }
  138. catch (e) {
  139. logger.error('failed to upload', e);
  140. pageContainer.showErrorToastr(e);
  141. }
  142. finally {
  143. this.editor.terminateUploadingState();
  144. }
  145. }
  146. /**
  147. * the scroll event handler from codemirror
  148. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  149. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  150. * And data.line is also available that is added by Editor component
  151. * @see https://codemirror.net/doc/manual.html#events
  152. */
  153. onEditorScroll(data) {
  154. // prevent scrolling
  155. // if the elapsed time from last scroll with cursor is shorter than 40ms
  156. const now = new Date();
  157. if (now - this.lastScrolledDateWithCursor < 40) {
  158. return;
  159. }
  160. this.scrollPreviewByEditorLineWithThrottle(data.line);
  161. }
  162. /**
  163. * the scroll event handler from codemirror
  164. * @param {number} line
  165. * @see https://codemirror.net/doc/manual.html#events
  166. */
  167. onEditorScrollCursorIntoView(line) {
  168. // record date
  169. this.lastScrolledDateWithCursor = new Date();
  170. this.scrollPreviewByCursorMovingWithThrottle(line);
  171. }
  172. /**
  173. * scroll Preview element by scroll event
  174. * @param {number} line
  175. */
  176. scrollPreviewByEditorLine(line) {
  177. if (this.previewElement == null) {
  178. return;
  179. }
  180. // prevent circular invocation
  181. if (this.isOriginOfScrollSyncPreview) {
  182. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  183. return;
  184. }
  185. // turn on the flag
  186. this.isOriginOfScrollSyncEditor = true;
  187. scrollSyncHelper.scrollPreview(this.previewElement, line);
  188. }
  189. /**
  190. * scroll Preview element by cursor moving
  191. * @param {number} line
  192. */
  193. scrollPreviewByCursorMoving(line) {
  194. if (this.previewElement == null) {
  195. return;
  196. }
  197. // prevent circular invocation
  198. if (this.isOriginOfScrollSyncPreview) {
  199. this.isOriginOfScrollSyncPreview = false; // turn off the flag
  200. return;
  201. }
  202. // turn on the flag
  203. this.isOriginOfScrollSyncEditor = true;
  204. scrollSyncHelper.scrollPreviewToRevealOverflowing(this.previewElement, line);
  205. }
  206. /**
  207. * the scroll event handler from Preview component
  208. * @param {number} offset
  209. */
  210. onPreviewScroll(offset) {
  211. this.scrollEditorByPreviewScrollWithThrottle(offset);
  212. }
  213. /**
  214. * scroll Editor component by scroll event of Preview component
  215. * @param {number} offset
  216. */
  217. scrollEditorByPreviewScroll(offset) {
  218. if (this.previewElement == null) {
  219. return;
  220. }
  221. // prevent circular invocation
  222. if (this.isOriginOfScrollSyncEditor) {
  223. this.isOriginOfScrollSyncEditor = false; // turn off the flag
  224. return;
  225. }
  226. // turn on the flag
  227. this.isOriginOfScrollSyncPreview = true;
  228. scrollSyncHelper.scrollEditor(this.editor, this.previewElement, offset);
  229. }
  230. saveDraft() {
  231. const { pageContainer, editorContainer } = this.props;
  232. // only when the first time to edit
  233. if (!pageContainer.state.revisionId) {
  234. editorContainer.saveDraft(pageContainer.state.path, this.state.markdown);
  235. }
  236. editorContainer.enableUnsavedWarning();
  237. }
  238. clearDraft() {
  239. this.props.editorContainer.clearDraft(this.props.pageContainer.state.path);
  240. }
  241. renderPreview(value) {
  242. this.setState({ markdown: value });
  243. // render html
  244. const context = {
  245. markdown: this.state.markdown,
  246. currentPagePath: decodeURIComponent(window.location.pathname),
  247. };
  248. const growiRenderer = this.growiRenderer;
  249. const interceptorManager = this.props.appContainer.interceptorManager;
  250. interceptorManager.process('preRenderPreview', context)
  251. .then(() => { return interceptorManager.process('prePreProcess', context) })
  252. .then(() => {
  253. context.markdown = growiRenderer.preProcess(context.markdown);
  254. })
  255. .then(() => { return interceptorManager.process('postPreProcess', context) })
  256. .then(() => {
  257. const parsedHTML = growiRenderer.process(context.markdown);
  258. context.parsedHTML = parsedHTML;
  259. })
  260. .then(() => { return interceptorManager.process('prePostProcess', context) })
  261. .then(() => {
  262. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
  263. })
  264. .then(() => { return interceptorManager.process('postPostProcess', context) })
  265. .then(() => { return interceptorManager.process('preRenderPreviewHtml', context) })
  266. .then(() => {
  267. this.setState({ html: context.parsedHTML });
  268. })
  269. // process interceptors for post rendering
  270. .then(() => { return interceptorManager.process('postRenderPreviewHtml', context) });
  271. }
  272. render() {
  273. const config = this.props.appContainer.getConfig();
  274. const noCdn = envUtils.toBoolean(config.env.NO_CDN);
  275. const emojiStrategy = this.props.appContainer.getEmojiStrategy();
  276. return (
  277. <div className="row">
  278. <div className="col-md-6 col-sm-12 page-editor-editor-container">
  279. <Editor
  280. ref={(c) => { this.editor = c }}
  281. value={this.state.markdown}
  282. noCdn={noCdn}
  283. isMobile={this.props.appContainer.isMobile}
  284. isUploadable={this.state.isUploadable}
  285. isUploadableFile={this.state.isUploadableFile}
  286. emojiStrategy={emojiStrategy}
  287. onScroll={this.onEditorScroll}
  288. onScrollCursorIntoView={this.onEditorScrollCursorIntoView}
  289. onChange={this.onMarkdownChanged}
  290. onUpload={this.onUpload}
  291. onSave={this.onSaveWithShortcut}
  292. />
  293. </div>
  294. <div className="col-md-6 hidden-sm hidden-xs page-editor-preview-container">
  295. <Preview
  296. html={this.state.html}
  297. // eslint-disable-next-line no-return-assign
  298. inputRef={(el) => { return this.previewElement = el }}
  299. isMathJaxEnabled={this.state.isMathJaxEnabled}
  300. renderMathJaxOnInit={false}
  301. onScroll={this.onPreviewScroll}
  302. />
  303. </div>
  304. </div>
  305. );
  306. }
  307. }
  308. /**
  309. * Wrapper component for using unstated
  310. */
  311. const PageEditorWrapper = (props) => {
  312. return createSubscribedElement(PageEditor, props, [AppContainer, PageContainer, EditorContainer]);
  313. };
  314. PageEditor.propTypes = {
  315. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  316. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  317. editorContainer: PropTypes.instanceOf(EditorContainer).isRequired,
  318. };
  319. export default PageEditorWrapper;