PageEditor.tsx 14 KB

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