PageEditor.jsx 11 KB

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