PageEditor.tsx 15 KB

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