PageEditor.jsx 11 KB

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