2
0

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