PageEditor.jsx 10 KB

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