PageEditor.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import React, {
  2. useCallback, useEffect, useMemo, useRef, useState,
  3. } from 'react';
  4. import EventEmitter from 'events';
  5. import { envUtils, IPageHasId, PageGrant } from '@growi/core';
  6. import detectIndent from 'detect-indent';
  7. import { useTranslation } from 'next-i18next';
  8. import { useRouter } from 'next/router';
  9. import { throttle, debounce } from 'throttle-debounce';
  10. import { saveOrUpdate } from '~/client/services/page-operation';
  11. import { toastSuccess, toastError } from '~/client/util/apiNotification';
  12. import { apiGet, apiPostForm } from '~/client/util/apiv1-client';
  13. import { getOptionsToSave } from '~/client/util/editor';
  14. import { IEditorMethods } from '~/interfaces/editor-methods';
  15. import {
  16. useCurrentPathname, useCurrentPageId,
  17. useIsEditable, useIsIndentSizeForced, useIsUploadableFile, useIsUploadableImage, useEditingMarkdown, useIsNotFound,
  18. } from '~/stores/context';
  19. import {
  20. useCurrentIndentSize, useSWRxSlackChannels, useIsSlackEnabled, useIsTextlintEnabled, usePageTagsForEditors,
  21. useIsEnabledUnsavedWarning,
  22. } from '~/stores/editor';
  23. import { useCurrentPagePath, useSWRxCurrentPage } from '~/stores/page';
  24. import { usePreviewOptions } from '~/stores/renderer';
  25. import {
  26. EditorMode,
  27. useEditorMode, useIsMobile, useSelectedGrant,
  28. } from '~/stores/ui';
  29. import loggerFactory from '~/utils/logger';
  30. // import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
  31. import Editor from './PageEditor/Editor';
  32. import Preview from './PageEditor/Preview';
  33. import scrollSyncHelper from './PageEditor/ScrollSyncHelper';
  34. const logger = loggerFactory('growi:PageEditor');
  35. declare const globalEmitter: EventEmitter;
  36. // for scrolling
  37. let lastScrolledDateWithCursor: Date | null = null;
  38. let isOriginOfScrollSyncEditor = false;
  39. let isOriginOfScrollSyncPreview = false;
  40. const PageEditor = React.memo((): JSX.Element => {
  41. const { t } = useTranslation();
  42. const router = useRouter();
  43. const { data: isNotFound } = useIsNotFound();
  44. const { data: pageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  45. const { data: currentPagePath } = useCurrentPagePath();
  46. const { data: currentPathname } = useCurrentPathname();
  47. const { data: currentPage, mutate: mutateCurrentPage } = useSWRxCurrentPage();
  48. const { data: grantData, mutate: mutateGrant } = useSelectedGrant();
  49. const { data: pageTags } = usePageTagsForEditors(pageId);
  50. const { data: editingMarkdown } = useEditingMarkdown();
  51. const { data: isEditable } = useIsEditable();
  52. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  53. const { data: isMobile } = useIsMobile();
  54. const { data: isSlackEnabled } = useIsSlackEnabled();
  55. const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
  56. const { data: isTextlintEnabled } = useIsTextlintEnabled();
  57. const { data: isIndentSizeForced } = useIsIndentSizeForced();
  58. const { data: indentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  59. const { data: isEnabledUnsavedWarning, mutate: mutateIsEnabledUnsavedWarning } = useIsEnabledUnsavedWarning();
  60. const { data: isUploadableFile } = useIsUploadableFile();
  61. const { data: isUploadableImage } = useIsUploadableImage();
  62. const { data: rendererOptions } = usePreviewOptions();
  63. const currentRevisionId = currentPage?.revision?._id;
  64. const initialValue = editingMarkdown ?? '';
  65. const markdownToSave = useRef<string>(initialValue);
  66. const [markdownToPreview, setMarkdownToPreview] = useState<string>(initialValue);
  67. const slackChannels = useMemo(() => (slackChannelsData ? slackChannelsData.toString() : ''), [slackChannelsData]);
  68. const editorRef = useRef<IEditorMethods>(null);
  69. const previewRef = useRef<HTMLDivElement>(null);
  70. // const optionsToSave = useMemo(() => {
  71. // if (grantData == null) {
  72. // return;
  73. // }
  74. // const slackChannels = slackChannelsData ? slackChannelsData.toString() : '';
  75. // const optionsToSave = getOptionsToSave(
  76. // isSlackEnabled ?? false, slackChannels,
  77. // grantData.grant, grantData.grantedGroup?.id, grantData.grantedGroup?.name,
  78. // pageTags || [],
  79. // );
  80. // return optionsToSave;
  81. // }, [grantData, isSlackEnabled, pageTags, slackChannelsData]);
  82. const setMarkdownWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string, isClean: boolean) => {
  83. markdownToSave.current = value;
  84. setMarkdownToPreview(value);
  85. // Displays an unsaved warning alert
  86. mutateIsEnabledUnsavedWarning(!isClean);
  87. })), [mutateIsEnabledUnsavedWarning]);
  88. const markdownChangedHandler = useCallback((value: string, isClean: boolean): void => {
  89. setMarkdownWithDebounce(value, isClean);
  90. }, [setMarkdownWithDebounce]);
  91. // return true if the save succeeds, otherwise false.
  92. const save = useCallback(async(opts?: {overwriteScopesOfDescendants: boolean}): Promise<IPageHasId | null> => {
  93. if (grantData == null || isSlackEnabled == null || currentPathname == null) {
  94. logger.error('Some materials to save are invalid', { grantData, isSlackEnabled, currentPathname });
  95. throw new Error('Some materials to save are invalid');
  96. }
  97. const grant = grantData.grant || PageGrant.GRANT_PUBLIC;
  98. const grantedGroup = grantData?.grantedGroup;
  99. const optionsToSave = Object.assign(
  100. getOptionsToSave(isSlackEnabled, slackChannels, grant || 1, grantedGroup?.id, grantedGroup?.name, pageTags || []),
  101. { ...opts },
  102. );
  103. try {
  104. const { page } = await saveOrUpdate(
  105. optionsToSave,
  106. { pageId, path: currentPagePath || currentPathname, revisionId: currentRevisionId },
  107. markdownToSave.current,
  108. );
  109. return page;
  110. }
  111. catch (error) {
  112. logger.error('failed to save', error);
  113. toastError(error);
  114. if (error.code === 'conflict') {
  115. // pageContainer.setState({
  116. // remoteRevisionId: error.data.revisionId,
  117. // remoteRevisionBody: error.data.revisionBody,
  118. // remoteRevisionUpdateAt: error.data.createdAt,
  119. // lastUpdateUser: error.data.user,
  120. // });
  121. }
  122. return null;
  123. }
  124. // eslint-disable-next-line max-len
  125. }, [grantData, isSlackEnabled, currentPathname, slackChannels, pageTags, pageId, currentPagePath, currentRevisionId]);
  126. const saveAndReturnToViewHandler = useCallback(async(opts?: {overwriteScopesOfDescendants: boolean}) => {
  127. if (editorMode !== EditorMode.Editor) {
  128. return;
  129. }
  130. const page = await save(opts);
  131. if (page == null) {
  132. return;
  133. }
  134. // The updateFn should be a promise or asynchronous function to handle the remote mutation
  135. // it should return updated data. see: https://swr.vercel.app/docs/mutation#optimistic-updates
  136. // Moreover, `async() => false` does not work since it's too fast to be calculated.
  137. await mutateIsEnabledUnsavedWarning(new Promise(r => setTimeout(() => r(false), 10)), { optimisticData: () => false });
  138. if (isNotFound) {
  139. await router.push(`/${page._id}`);
  140. }
  141. else {
  142. await mutateCurrentPageId(page._id);
  143. await mutateCurrentPage();
  144. }
  145. mutateEditorMode(EditorMode.View);
  146. }, [editorMode, save, mutateIsEnabledUnsavedWarning, isNotFound, mutateEditorMode, router, mutateCurrentPageId, mutateCurrentPage]);
  147. const saveWithShortcut = useCallback(async() => {
  148. if (editorMode !== EditorMode.Editor) {
  149. return;
  150. }
  151. const isSuccess = await save();
  152. if (isSuccess) {
  153. toastSuccess(t('toaster.save_succeeded'));
  154. }
  155. }, [editorMode, save, t]);
  156. /**
  157. * the upload event handler
  158. * @param {any} file
  159. */
  160. const uploadHandler = useCallback(async(file) => {
  161. if (editorRef.current == null) {
  162. return;
  163. }
  164. try {
  165. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  166. let res: any = await apiGet('/attachments.limit', {
  167. fileSize: file.size,
  168. });
  169. if (!res.isUploadable) {
  170. throw new Error(res.errorMessage);
  171. }
  172. const formData = new FormData();
  173. // const { pageId, path } = pageContainer.state;
  174. formData.append('file', file);
  175. if (currentPagePath != null) {
  176. formData.append('path', currentPagePath);
  177. }
  178. if (pageId != null) {
  179. formData.append('page_id', pageId);
  180. }
  181. res = await apiPostForm('/attachments.add', formData);
  182. const attachment = res.attachment;
  183. const fileName = attachment.originalName;
  184. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  185. // when image
  186. if (attachment.fileFormat.startsWith('image/')) {
  187. // modify to "![fileName](url)" syntax
  188. insertText = `!${insertText}`;
  189. }
  190. editorRef.current.insertText(insertText);
  191. // when if created newly
  192. if (res.pageCreated) {
  193. logger.info('Page is created', res.page._id);
  194. globalEmitter.emit('resetInitializedHackMdStatus');
  195. mutateGrant(res.page.grant);
  196. }
  197. }
  198. catch (e) {
  199. logger.error('failed to upload', e);
  200. toastError(e);
  201. }
  202. finally {
  203. editorRef.current.terminateUploadingState();
  204. }
  205. }, [currentPagePath, mutateGrant, pageId]);
  206. const scrollPreviewByEditorLine = useCallback((line: number) => {
  207. if (previewRef.current == null) {
  208. return;
  209. }
  210. // prevent circular invocation
  211. if (isOriginOfScrollSyncPreview) {
  212. isOriginOfScrollSyncPreview = false; // turn off the flag
  213. return;
  214. }
  215. // turn on the flag
  216. isOriginOfScrollSyncEditor = true;
  217. scrollSyncHelper.scrollPreview(previewRef.current, line);
  218. }, []);
  219. const scrollPreviewByEditorLineWithThrottle = useMemo(() => throttle(20, scrollPreviewByEditorLine), [scrollPreviewByEditorLine]);
  220. /**
  221. * the scroll event handler from codemirror
  222. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  223. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  224. * And data.line is also available that is added by Editor component
  225. * @see https://codemirror.net/doc/manual.html#events
  226. */
  227. const editorScrolledHandler = useCallback(({ line }: { line: number }) => {
  228. // prevent scrolling
  229. // if the elapsed time from last scroll with cursor is shorter than 40ms
  230. const now = new Date();
  231. if (lastScrolledDateWithCursor != null && now.getTime() - lastScrolledDateWithCursor.getTime() < 40) {
  232. return;
  233. }
  234. scrollPreviewByEditorLineWithThrottle(line);
  235. }, [scrollPreviewByEditorLineWithThrottle]);
  236. /**
  237. * scroll Preview element by cursor moving
  238. * @param {number} line
  239. */
  240. const scrollPreviewByCursorMoving = useCallback((line: number) => {
  241. if (previewRef.current == null) {
  242. return;
  243. }
  244. // prevent circular invocation
  245. if (isOriginOfScrollSyncPreview) {
  246. isOriginOfScrollSyncPreview = false; // turn off the flag
  247. return;
  248. }
  249. // turn on the flag
  250. isOriginOfScrollSyncEditor = true;
  251. if (previewRef.current != null) {
  252. scrollSyncHelper.scrollPreviewToRevealOverflowing(previewRef.current, line);
  253. }
  254. }, []);
  255. const scrollPreviewByCursorMovingWithThrottle = useMemo(() => throttle(20, scrollPreviewByCursorMoving), [scrollPreviewByCursorMoving]);
  256. /**
  257. * the scroll event handler from codemirror
  258. * @param {number} line
  259. * @see https://codemirror.net/doc/manual.html#events
  260. */
  261. const editorScrollCursorIntoViewHandler = useCallback((line: number) => {
  262. // record date
  263. lastScrolledDateWithCursor = new Date();
  264. scrollPreviewByCursorMovingWithThrottle(line);
  265. }, [scrollPreviewByCursorMovingWithThrottle]);
  266. /**
  267. * scroll Editor component by scroll event of Preview component
  268. * @param {number} offset
  269. */
  270. const scrollEditorByPreviewScroll = useCallback((offset: number) => {
  271. if (editorRef.current == null || previewRef.current == null) {
  272. return;
  273. }
  274. // prevent circular invocation
  275. if (isOriginOfScrollSyncEditor) {
  276. isOriginOfScrollSyncEditor = false; // turn off the flag
  277. return;
  278. }
  279. // turn on the flag
  280. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  281. isOriginOfScrollSyncPreview = true;
  282. scrollSyncHelper.scrollEditor(editorRef.current, previewRef.current, offset);
  283. }, []);
  284. const scrollEditorByPreviewScrollWithThrottle = useMemo(() => throttle(20, scrollEditorByPreviewScroll), [scrollEditorByPreviewScroll]);
  285. // initialize
  286. useEffect(() => {
  287. if (initialValue == null) {
  288. return;
  289. }
  290. markdownToSave.current = initialValue;
  291. setMarkdownToPreview(initialValue);
  292. mutateIsEnabledUnsavedWarning(false);
  293. }, [initialValue, mutateIsEnabledUnsavedWarning]);
  294. // initial caret line
  295. useEffect(() => {
  296. if (editorRef.current != null) {
  297. editorRef.current.setCaretLine(0);
  298. }
  299. }, []);
  300. // set handler to set caret line
  301. useEffect(() => {
  302. const handler = (line) => {
  303. if (editorRef.current != null) {
  304. editorRef.current.setCaretLine(line);
  305. }
  306. if (previewRef.current != null) {
  307. scrollSyncHelper.scrollPreview(previewRef.current, line);
  308. }
  309. };
  310. globalEmitter.on('setCaretLine', handler);
  311. return function cleanup() {
  312. globalEmitter.removeListener('setCaretLine', handler);
  313. };
  314. }, []);
  315. // set handler to save and return to View
  316. useEffect(() => {
  317. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  318. return function cleanup() {
  319. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  320. };
  321. }, [saveAndReturnToViewHandler]);
  322. // set handler to focus
  323. useEffect(() => {
  324. if (editorRef.current != null && editorMode === EditorMode.Editor) {
  325. editorRef.current.forceToFocus();
  326. }
  327. }, [editorMode]);
  328. // Unnecessary code. Delete after PageEditor and PageEditorByHackmd implementation has completed. -- 2022.09.06 Yuki Takei
  329. //
  330. // set handler to update editor value
  331. // useEffect(() => {
  332. // const handler = (markdown) => {
  333. // if (editorRef.current != null) {
  334. // editorRef.current.setValue(markdown);
  335. // }
  336. // };
  337. // globalEmitter.on('updateEditorValue', handler);
  338. // return function cleanup() {
  339. // globalEmitter.removeListener('updateEditorValue', handler);
  340. // };
  341. // }, []);
  342. // Detect indent size from contents (only when users are allowed to change it)
  343. // useEffect(() => {
  344. // const currentPageMarkdown = pageContainer.state.markdown;
  345. // if (!isIndentSizeForced && currentPageMarkdown != null) {
  346. // const detectedIndent = detectIndent(currentPageMarkdown);
  347. // if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  348. // mutateCurrentIndentSize(detectedIndent.amount);
  349. // }
  350. // }
  351. // }, [isIndentSizeForced, mutateCurrentIndentSize, pageContainer.state.markdown]);
  352. if (!isEditable) {
  353. return <></>;
  354. }
  355. if (rendererOptions == null) {
  356. return <></>;
  357. }
  358. const isUploadable = isUploadableImage || isUploadableFile;
  359. return (
  360. <div className="d-flex flex-wrap">
  361. <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
  362. <Editor
  363. ref={editorRef}
  364. value={initialValue}
  365. isUploadable={isUploadable}
  366. isUploadableFile={isUploadableFile}
  367. isTextlintEnabled={isTextlintEnabled}
  368. indentSize={indentSize}
  369. onScroll={editorScrolledHandler}
  370. onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
  371. onChange={markdownChangedHandler}
  372. onUpload={uploadHandler}
  373. onSave={saveWithShortcut}
  374. />
  375. </div>
  376. <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
  377. <Preview
  378. ref={previewRef}
  379. rendererOptions={rendererOptions}
  380. markdown={markdownToPreview}
  381. pagePath={currentPagePath}
  382. onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)}
  383. />
  384. </div>
  385. {/* <ConflictDiffModal
  386. isOpen={pageContainer.state.isConflictDiffModalOpen}
  387. onClose={() => pageContainer.setState({ isConflictDiffModalOpen: false })}
  388. pageContainer={pageContainer}
  389. markdownOnEdit={markdown}
  390. optionsToSave={optionsToSave}
  391. /> */}
  392. </div>
  393. );
  394. });
  395. PageEditor.displayName = 'PageEditor';
  396. export default PageEditor;