PageEditor.jsx 14 KB

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