PageEditor.jsx 11 KB

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