PageEditor.jsx 10 KB

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