PageEditor.jsx 12 KB

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