PageEditor.jsx 14 KB

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