PageEditor.jsx 11 KB

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