PageEditor.jsx 12 KB

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