PageEditor.tsx 14 KB

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