PageEditor.tsx 17 KB

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