PageEditor.jsx 13 KB

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