PageEditor.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import React, {
  2. useCallback, useEffect, useMemo, useRef, useState,
  3. } from 'react';
  4. import EventEmitter from 'events';
  5. import { envUtils, PageGrant } from '@growi/core';
  6. import detectIndent from 'detect-indent';
  7. import { throttle, debounce } from 'throttle-debounce';
  8. import { saveAndReload } from '~/client/services/page-operation';
  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, useCurrentPathname, 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. // pageContainer: PageContainer,
  44. // editorContainer: EditorContainer,
  45. // isEditable: boolean,
  46. // editorMode: string,
  47. // isSlackEnabled: boolean,
  48. // slackChannels: string,
  49. // isMobile?: boolean,
  50. // grant: number,
  51. // grantGroupId?: string,
  52. // grantGroupName?: string,
  53. // mutateGrant: (grant: number) => void,
  54. // isTextlintEnabled?: boolean,
  55. // isIndentSizeForced?: boolean,
  56. // indentSize?: number,
  57. // mutateCurrentIndentSize: (indent: number) => void,
  58. };
  59. // for scrolling
  60. let lastScrolledDateWithCursor: Date | null = null;
  61. let isOriginOfScrollSyncEditor = false;
  62. let isOriginOfScrollSyncPreview = false;
  63. const PageEditor = React.memo((props: Props): JSX.Element => {
  64. // const {
  65. // pageContainer, editorContainer,
  66. // } = props;
  67. const { data: isEditable } = useIsEditable();
  68. const { data: editorMode } = useEditorMode();
  69. const { data: isMobile } = useIsMobile();
  70. const { data: isSlackEnabled } = useIsSlackEnabled();
  71. const { data: pageId } = useCurrentPageId();
  72. const { data: pageTags } = usePageTagsForEditors(pageId);
  73. const { data: currentPagePath } = useCurrentPagePath();
  74. const { data: currentPathname } = useCurrentPathname();
  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 slackChannels = useMemo(() => (slackChannelsData ? slackChannelsData.toString() : ''), []);
  92. const editorRef = useRef<EditorRef>(null);
  93. const previewRef = useRef<HTMLDivElement>(null);
  94. const setMarkdownWithDebounce = useMemo(() => debounce(50, throttle(100, value => setMarkdown(value))), []);
  95. // const saveDraftWithDebounce = useMemo(() => debounce(800, () => {
  96. // editorContainer.saveDraft(pageContainer.state.path, markdown);
  97. // }), [editorContainer, markdown, pageContainer.state.path]);
  98. const markdownChangedHandler = useCallback((value: string): void => {
  99. setMarkdownWithDebounce(value);
  100. // only when the first time to edit
  101. // if (!pageContainer.state.revisionId) {
  102. // saveDraftWithDebounce();
  103. // }
  104. // }, [pageContainer.state.revisionId, saveDraftWithDebounce, setMarkdownWithDebounce]);
  105. }, [setMarkdownWithDebounce]);
  106. const saveWithShortcut = useCallback(async() => {
  107. if (grantData == null) {
  108. return;
  109. }
  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. }, [currentPagePath, mutateGrant, pageId]);
  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. // initial caret line
  261. useEffect(() => {
  262. if (editorRef.current != null) {
  263. editorRef.current.setCaretLine(0);
  264. }
  265. }, []);
  266. // set handler to set caret line
  267. useEffect(() => {
  268. const handler = (line) => {
  269. if (editorRef.current != null) {
  270. editorRef.current.setCaretLine(line);
  271. }
  272. if (previewRef.current != null) {
  273. scrollSyncHelper.scrollPreview(previewRef.current, line);
  274. }
  275. };
  276. globalEmitter.on('setCaretLine', handler);
  277. return function cleanup() {
  278. globalEmitter.removeListener('setCaretLine', handler);
  279. };
  280. }, []);
  281. const saveAndReloadHandler = useCallback(async(opts?: {overwriteScopesOfDescendants: boolean}) => {
  282. if (editorMode !== EditorMode.Editor) {
  283. return;
  284. }
  285. const grant = grantData?.grant || PageGrant.GRANT_PUBLIC;
  286. const grantedGroup = grantData?.grantedGroup;
  287. if (isSlackEnabled == null || currentPathname == null) {
  288. return;
  289. }
  290. let optionsToSave;
  291. const currentOptionsToSave = getOptionsToSave(isSlackEnabled, slackChannels, grant || 1, grantedGroup?.id, grantedGroup?.name, pageTags || []);
  292. if (opts != null) {
  293. optionsToSave = Object.assign(currentOptionsToSave, {
  294. ...opts,
  295. });
  296. }
  297. else {
  298. optionsToSave = currentOptionsToSave;
  299. }
  300. await saveAndReload(optionsToSave, { pageId, path: currentPagePath || currentPathname, revisionId: currentPage?.revision?._id }, markdown);
  301. }, [currentPage?.revision?._id,
  302. currentPagePath,
  303. currentPathname,
  304. editorMode,
  305. grantData?.grant,
  306. grantData?.grantedGroup,
  307. isSlackEnabled,
  308. markdown,
  309. pageId,
  310. pageTags,
  311. slackChannels,
  312. ]);
  313. // set handler to save and reload Page
  314. useEffect(() => {
  315. globalEmitter.on('saveAndReload', saveAndReloadHandler);
  316. return function cleanup() {
  317. globalEmitter.removeListener('saveAndReload', saveAndReloadHandler);
  318. };
  319. }, [saveAndReloadHandler]);
  320. // set handler to focus
  321. useEffect(() => {
  322. if (editorRef.current != null && editorMode === EditorMode.Editor) {
  323. editorRef.current.forceToFocus();
  324. }
  325. }, [editorMode]);
  326. // set handler to update editor value
  327. useEffect(() => {
  328. const handler = (markdown) => {
  329. if (editorRef.current != null) {
  330. editorRef.current.setValue(markdown);
  331. }
  332. };
  333. globalEmitter.on('updateEditorValue', handler);
  334. return function cleanup() {
  335. globalEmitter.removeListener('updateEditorValue', handler);
  336. };
  337. }, []);
  338. // Displays an alert if there is a difference with pageContainer's markdown
  339. // useEffect(() => {
  340. // // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  341. // if (pageContainer.state.markdown! !== markdown) {
  342. // mutateIsEnabledUnsavedWarning(true);
  343. // }
  344. // }, [editorContainer, markdown, mutateIsEnabledUnsavedWarning, pageContainer.state.markdown]);
  345. // Detect indent size from contents (only when users are allowed to change it)
  346. // useEffect(() => {
  347. // const currentPageMarkdown = pageContainer.state.markdown;
  348. // if (!isIndentSizeForced && currentPageMarkdown != null) {
  349. // const detectedIndent = detectIndent(currentPageMarkdown);
  350. // if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  351. // mutateCurrentIndentSize(detectedIndent.amount);
  352. // }
  353. // }
  354. // }, [isIndentSizeForced, mutateCurrentIndentSize, pageContainer.state.markdown]);
  355. if (!isEditable) {
  356. return <></>;
  357. }
  358. if (rendererOptions == null) {
  359. return <></>;
  360. }
  361. const isUploadable = isUploadableImage || isUploadableFile;
  362. return (
  363. <div className="d-flex flex-wrap">
  364. <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
  365. <Editor
  366. ref={editorRef}
  367. value={markdown}
  368. isUploadable={isUploadable}
  369. isUploadableFile={isUploadableFile}
  370. isTextlintEnabled={isTextlintEnabled}
  371. indentSize={indentSize}
  372. onScroll={editorScrolledHandler}
  373. onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
  374. onChange={markdownChangedHandler}
  375. onUpload={uploadHandler}
  376. onSave={() => saveWithShortcut()}
  377. />
  378. </div>
  379. <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
  380. <Preview
  381. ref={previewRef}
  382. rendererOptions={rendererOptions}
  383. markdown={markdown}
  384. pagePath={currentPagePath}
  385. renderMathJaxOnInit={false}
  386. onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)}
  387. />
  388. </div>
  389. {/* <ConflictDiffModal
  390. isOpen={pageContainer.state.isConflictDiffModalOpen}
  391. onClose={() => pageContainer.setState({ isConflictDiffModalOpen: false })}
  392. pageContainer={pageContainer}
  393. markdownOnEdit={markdown}
  394. /> */}
  395. </div>
  396. );
  397. });
  398. PageEditor.displayName = 'PageEditor';
  399. /**
  400. * Wrapper component for using unstated
  401. */
  402. // const PageEditorWrapper = withUnstatedContainers(PageEditor, [PageContainer, EditorContainer]);
  403. // export default PageEditorWrapper;
  404. export default PageEditor;