PageEditor.jsx 13 KB

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