PageEditor.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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: pageId } = useCurrentPageId();
  68. const { data: currentPagePath } = useCurrentPagePath();
  69. const { data: currentPathname } = useCurrentPathname();
  70. const { data: currentPage } = useSWRxCurrentPage();
  71. const { data: grantData, mutate: mutateGrant } = useSelectedGrant();
  72. const { data: pageTags } = usePageTagsForEditors(pageId);
  73. const { data: isEditable } = useIsEditable();
  74. const { data: editorMode } = useEditorMode();
  75. const { data: isMobile } = useIsMobile();
  76. const { data: isSlackEnabled } = useIsSlackEnabled();
  77. const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
  78. const { data: isTextlintEnabled } = useIsTextlintEnabled();
  79. const { data: isIndentSizeForced } = useIsIndentSizeForced();
  80. const { data: indentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  81. const { data: isEnabledUnsavedWarning, mutate: mutateIsEnabledUnsavedWarning } = useIsEnabledUnsavedWarning();
  82. const { data: isUploadableFile } = useIsUploadableFile();
  83. const { data: isUploadableImage } = useIsUploadableImage();
  84. const { data: rendererOptions } = usePreviewOptions();
  85. const initialValue = currentPage?.revision?.body;
  86. const [markdown, setMarkdown] = useState<string>(initialValue ?? '');
  87. const slackChannels = useMemo(() => (slackChannelsData ? slackChannelsData.toString() : ''), []);
  88. const editorRef = useRef<EditorRef>(null);
  89. const previewRef = useRef<HTMLDivElement>(null);
  90. const setMarkdownWithDebounce = useMemo(() => debounce(50, throttle(100, value => setMarkdown(value))), []);
  91. // const saveDraftWithDebounce = useMemo(() => debounce(800, () => {
  92. // editorContainer.saveDraft(pageContainer.state.path, markdown);
  93. // }), [editorContainer, markdown, pageContainer.state.path]);
  94. const markdownChangedHandler = useCallback((value: string): void => {
  95. setMarkdownWithDebounce(value);
  96. // only when the first time to edit
  97. // if (!pageContainer.state.revisionId) {
  98. // saveDraftWithDebounce();
  99. // }
  100. // }, [pageContainer.state.revisionId, saveDraftWithDebounce, setMarkdownWithDebounce]);
  101. }, [setMarkdownWithDebounce]);
  102. const saveWithShortcut = useCallback(async() => {
  103. if (grantData == null) {
  104. return;
  105. }
  106. const optionsToSave = getOptionsToSave(
  107. isSlackEnabled ?? false, slackChannels,
  108. grantData.grant, grantData.grantedGroup?.id, grantData.grantedGroup?.name,
  109. pageTags || [],
  110. );
  111. try {
  112. // disable unsaved warning
  113. mutateIsEnabledUnsavedWarning(false);
  114. // eslint-disable-next-line no-unused-vars
  115. // const { tags } = await pageContainer.save(markdown, editorMode, optionsToSave);
  116. logger.debug('success to save');
  117. // pageContainer.showSuccessToastr();
  118. // update state of EditorContainer
  119. // editorContainer.setState({ tags });
  120. }
  121. catch (error) {
  122. logger.error('failed to save', error);
  123. // pageContainer.showErrorToastr(error);
  124. }
  125. }, [grantData, isSlackEnabled, slackChannels, pageTags, mutateIsEnabledUnsavedWarning]);
  126. /**
  127. * the upload event handler
  128. * @param {any} file
  129. */
  130. const uploadHandler = useCallback(async(file) => {
  131. if (editorRef.current == null) {
  132. return;
  133. }
  134. try {
  135. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  136. let res: any = await apiGet('/attachments.limit', {
  137. fileSize: file.size,
  138. });
  139. if (!res.isUploadable) {
  140. throw new Error(res.errorMessage);
  141. }
  142. const formData = new FormData();
  143. // const { pageId, path } = pageContainer.state;
  144. formData.append('file', file);
  145. if (currentPagePath != null) {
  146. formData.append('path', currentPagePath);
  147. }
  148. if (pageId != null) {
  149. formData.append('page_id', pageId);
  150. }
  151. res = await apiPostForm('/attachments.add', formData);
  152. const attachment = res.attachment;
  153. const fileName = attachment.originalName;
  154. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  155. // when image
  156. if (attachment.fileFormat.startsWith('image/')) {
  157. // modify to "![fileName](url)" syntax
  158. insertText = `!${insertText}`;
  159. }
  160. editorRef.current.insertText(insertText);
  161. // when if created newly
  162. if (res.pageCreated) {
  163. logger.info('Page is created', res.page._id);
  164. // pageContainer.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  165. mutateGrant(res.page.grant);
  166. }
  167. }
  168. catch (e) {
  169. logger.error('failed to upload', e);
  170. // pageContainer.showErrorToastr(e);
  171. }
  172. finally {
  173. editorRef.current.terminateUploadingState();
  174. }
  175. // }, [editorMode, mutateGrant, pageContainer]);
  176. }, [currentPagePath, mutateGrant, pageId]);
  177. const scrollPreviewByEditorLine = useCallback((line: number) => {
  178. if (previewRef.current == null) {
  179. return;
  180. }
  181. // prevent circular invocation
  182. if (isOriginOfScrollSyncPreview) {
  183. isOriginOfScrollSyncPreview = false; // turn off the flag
  184. return;
  185. }
  186. // turn on the flag
  187. isOriginOfScrollSyncEditor = true;
  188. scrollSyncHelper.scrollPreview(previewRef.current, line);
  189. }, []);
  190. const scrollPreviewByEditorLineWithThrottle = useMemo(() => throttle(20, scrollPreviewByEditorLine), [scrollPreviewByEditorLine]);
  191. /**
  192. * the scroll event handler from codemirror
  193. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  194. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  195. * And data.line is also available that is added by Editor component
  196. * @see https://codemirror.net/doc/manual.html#events
  197. */
  198. const editorScrolledHandler = useCallback(({ line }: { line: number }) => {
  199. // prevent scrolling
  200. // if the elapsed time from last scroll with cursor is shorter than 40ms
  201. const now = new Date();
  202. if (lastScrolledDateWithCursor != null && now.getTime() - lastScrolledDateWithCursor.getTime() < 40) {
  203. return;
  204. }
  205. scrollPreviewByEditorLineWithThrottle(line);
  206. }, [scrollPreviewByEditorLineWithThrottle]);
  207. /**
  208. * scroll Preview element by cursor moving
  209. * @param {number} line
  210. */
  211. const scrollPreviewByCursorMoving = useCallback((line: number) => {
  212. if (previewRef.current == null) {
  213. return;
  214. }
  215. // prevent circular invocation
  216. if (isOriginOfScrollSyncPreview) {
  217. isOriginOfScrollSyncPreview = false; // turn off the flag
  218. return;
  219. }
  220. // turn on the flag
  221. isOriginOfScrollSyncEditor = true;
  222. if (previewRef.current != null) {
  223. scrollSyncHelper.scrollPreviewToRevealOverflowing(previewRef.current, line);
  224. }
  225. }, []);
  226. const scrollPreviewByCursorMovingWithThrottle = useMemo(() => throttle(20, scrollPreviewByCursorMoving), [scrollPreviewByCursorMoving]);
  227. /**
  228. * the scroll event handler from codemirror
  229. * @param {number} line
  230. * @see https://codemirror.net/doc/manual.html#events
  231. */
  232. const editorScrollCursorIntoViewHandler = useCallback((line: number) => {
  233. // record date
  234. lastScrolledDateWithCursor = new Date();
  235. scrollPreviewByCursorMovingWithThrottle(line);
  236. }, [scrollPreviewByCursorMovingWithThrottle]);
  237. /**
  238. * scroll Editor component by scroll event of Preview component
  239. * @param {number} offset
  240. */
  241. const scrollEditorByPreviewScroll = useCallback((offset: number) => {
  242. if (editorRef.current == null || previewRef.current == null) {
  243. return;
  244. }
  245. // prevent circular invocation
  246. if (isOriginOfScrollSyncEditor) {
  247. isOriginOfScrollSyncEditor = false; // turn off the flag
  248. return;
  249. }
  250. // turn on the flag
  251. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  252. isOriginOfScrollSyncPreview = true;
  253. scrollSyncHelper.scrollEditor(editorRef.current, previewRef.current, offset);
  254. }, []);
  255. const scrollEditorByPreviewScrollWithThrottle = useMemo(() => throttle(20, scrollEditorByPreviewScroll), [scrollEditorByPreviewScroll]);
  256. // initial caret line
  257. useEffect(() => {
  258. if (editorRef.current != null) {
  259. editorRef.current.setCaretLine(0);
  260. }
  261. }, []);
  262. // set handler to set caret line
  263. useEffect(() => {
  264. const handler = (line) => {
  265. if (editorRef.current != null) {
  266. editorRef.current.setCaretLine(line);
  267. }
  268. if (previewRef.current != null) {
  269. scrollSyncHelper.scrollPreview(previewRef.current, line);
  270. }
  271. };
  272. globalEmitter.on('setCaretLine', handler);
  273. return function cleanup() {
  274. globalEmitter.removeListener('setCaretLine', handler);
  275. };
  276. }, []);
  277. const saveAndReloadHandler = useCallback(async(opts?: {overwriteScopesOfDescendants: boolean}) => {
  278. if (editorMode !== EditorMode.Editor) {
  279. return;
  280. }
  281. const grant = grantData?.grant || PageGrant.GRANT_PUBLIC;
  282. const grantedGroup = grantData?.grantedGroup;
  283. if (isSlackEnabled == null || currentPathname == null) {
  284. return;
  285. }
  286. let optionsToSave;
  287. const currentOptionsToSave = getOptionsToSave(isSlackEnabled, slackChannels, grant || 1, grantedGroup?.id, grantedGroup?.name, pageTags || []);
  288. if (opts != null) {
  289. optionsToSave = Object.assign(currentOptionsToSave, {
  290. ...opts,
  291. });
  292. }
  293. else {
  294. optionsToSave = currentOptionsToSave;
  295. }
  296. try {
  297. await saveAndReload(optionsToSave, { pageId, path: currentPagePath || currentPathname, revisionId: currentPage?.revision?._id }, markdown);
  298. }
  299. catch (error) {
  300. logger.error('failed to save', error);
  301. // pageContainer.showErrorToastr(error);
  302. if (error.code === 'conflict') {
  303. // pageContainer.setState({
  304. // remoteRevisionId: error.data.revisionId,
  305. // remoteRevisionBody: error.data.revisionBody,
  306. // remoteRevisionUpdateAt: error.data.createdAt,
  307. // lastUpdateUser: error.data.user,
  308. // });
  309. }
  310. }
  311. }, [currentPage?.revision?._id,
  312. currentPagePath,
  313. currentPathname,
  314. editorMode,
  315. grantData?.grant,
  316. grantData?.grantedGroup,
  317. isSlackEnabled,
  318. markdown,
  319. pageId,
  320. pageTags,
  321. slackChannels,
  322. ]);
  323. // set handler to save and reload Page
  324. useEffect(() => {
  325. globalEmitter.on('saveAndReload', saveAndReloadHandler);
  326. return function cleanup() {
  327. globalEmitter.removeListener('saveAndReload', saveAndReloadHandler);
  328. };
  329. }, [saveAndReloadHandler]);
  330. // set handler to focus
  331. useEffect(() => {
  332. if (editorRef.current != null && editorMode === EditorMode.Editor) {
  333. editorRef.current.forceToFocus();
  334. }
  335. }, [editorMode]);
  336. // set handler to update editor value
  337. useEffect(() => {
  338. const handler = (markdown) => {
  339. if (editorRef.current != null) {
  340. editorRef.current.setValue(markdown);
  341. }
  342. };
  343. globalEmitter.on('updateEditorValue', handler);
  344. return function cleanup() {
  345. globalEmitter.removeListener('updateEditorValue', handler);
  346. };
  347. }, []);
  348. // Displays an alert if there is a difference with original markdown body
  349. useEffect(() => {
  350. if (initialValue == null || isEnabledUnsavedWarning) {
  351. return;
  352. }
  353. if (initialValue !== markdown) {
  354. mutateIsEnabledUnsavedWarning(true);
  355. }
  356. }, [initialValue, isEnabledUnsavedWarning, markdown, mutateIsEnabledUnsavedWarning]);
  357. // Detect indent size from contents (only when users are allowed to change it)
  358. // useEffect(() => {
  359. // const currentPageMarkdown = pageContainer.state.markdown;
  360. // if (!isIndentSizeForced && currentPageMarkdown != null) {
  361. // const detectedIndent = detectIndent(currentPageMarkdown);
  362. // if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  363. // mutateCurrentIndentSize(detectedIndent.amount);
  364. // }
  365. // }
  366. // }, [isIndentSizeForced, mutateCurrentIndentSize, pageContainer.state.markdown]);
  367. if (!isEditable) {
  368. return <></>;
  369. }
  370. if (rendererOptions == null) {
  371. return <></>;
  372. }
  373. const isUploadable = isUploadableImage || isUploadableFile;
  374. return (
  375. <div className="d-flex flex-wrap">
  376. <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
  377. <Editor
  378. ref={editorRef}
  379. value={initialValue}
  380. isUploadable={isUploadable}
  381. isUploadableFile={isUploadableFile}
  382. isTextlintEnabled={isTextlintEnabled}
  383. indentSize={indentSize}
  384. onScroll={editorScrolledHandler}
  385. onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
  386. onChange={markdownChangedHandler}
  387. onUpload={uploadHandler}
  388. onSave={() => saveWithShortcut()}
  389. />
  390. </div>
  391. <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
  392. <Preview
  393. ref={previewRef}
  394. rendererOptions={rendererOptions}
  395. markdown={markdown}
  396. pagePath={currentPagePath}
  397. renderMathJaxOnInit={false}
  398. onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)}
  399. />
  400. </div>
  401. {/* <ConflictDiffModal
  402. isOpen={pageContainer.state.isConflictDiffModalOpen}
  403. onClose={() => pageContainer.setState({ isConflictDiffModalOpen: false })}
  404. pageContainer={pageContainer}
  405. markdownOnEdit={markdown}
  406. /> */}
  407. </div>
  408. );
  409. });
  410. PageEditor.displayName = 'PageEditor';
  411. /**
  412. * Wrapper component for using unstated
  413. */
  414. // const PageEditorWrapper = withUnstatedContainers(PageEditor, [PageContainer, EditorContainer]);
  415. // export default PageEditorWrapper;
  416. export default PageEditor;