PageEditor.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. import React, {
  2. useCallback, useEffect, useMemo, useRef, useState,
  3. } from 'react';
  4. import EventEmitter from 'events';
  5. import nodePath from 'path';
  6. import {
  7. IPageHasId, pathUtils,
  8. } from '@growi/core';
  9. import detectIndent from 'detect-indent';
  10. import { useTranslation } from 'next-i18next';
  11. import { useRouter } from 'next/router';
  12. import { throttle, debounce } from 'throttle-debounce';
  13. import { useUpdateStateAfterSave, useSaveOrUpdate } from '~/client/services/page-operation';
  14. import { apiGet, apiPostForm } from '~/client/util/apiv1-client';
  15. import { toastError, toastSuccess } from '~/client/util/toastr';
  16. import { IEditorMethods } from '~/interfaces/editor-methods';
  17. import { OptionsToSave } from '~/interfaces/page-operation';
  18. import { SocketEventName } from '~/interfaces/websocket';
  19. import {
  20. useCurrentPathname, useIsEnabledAttachTitleHeader,
  21. useIsEditable, useIsUploadableFile, useIsUploadableImage, useIsIndentSizeForced,
  22. } from '~/stores/context';
  23. import {
  24. useCurrentIndentSize, useIsSlackEnabled, usePageTagsForEditors,
  25. useIsEnabledUnsavedWarning,
  26. useIsConflict,
  27. useEditingMarkdown,
  28. useWaitingSaveProcessing,
  29. } from '~/stores/editor';
  30. import { useConflictDiffModal } from '~/stores/modal';
  31. import {
  32. useCurrentPagePath, useSWRMUTxCurrentPage, useSWRxCurrentPage, useSWRxTagsInfo, useCurrentPageId, useIsNotFound, useIsLatestRevision, useTemplateBodyData,
  33. } from '~/stores/page';
  34. import { mutatePageTree } from '~/stores/page-listing';
  35. import {
  36. useRemoteRevisionId,
  37. useRemoteRevisionBody,
  38. useRemoteRevisionLastUpdatedAt,
  39. useRemoteRevisionLastUpdateUser,
  40. } from '~/stores/remote-latest-page';
  41. import { usePreviewOptions } from '~/stores/renderer';
  42. import {
  43. EditorMode,
  44. useEditorMode, useSelectedGrant,
  45. } from '~/stores/ui';
  46. import { useGlobalSocket } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. // import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
  49. import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
  50. import Editor from './PageEditor/Editor';
  51. import Preview from './PageEditor/Preview';
  52. import scrollSyncHelper from './PageEditor/ScrollSyncHelper';
  53. const logger = loggerFactory('growi:PageEditor');
  54. declare global {
  55. // eslint-disable-next-line vars-on-top, no-var
  56. var globalEmitter: EventEmitter;
  57. }
  58. // for scrolling
  59. let lastScrolledDateWithCursor: Date | null = null;
  60. let isOriginOfScrollSyncEditor = false;
  61. let isOriginOfScrollSyncPreview = false;
  62. const PageEditor = React.memo((): JSX.Element => {
  63. const { t } = useTranslation();
  64. const router = useRouter();
  65. const { data: isNotFound } = useIsNotFound();
  66. const { data: pageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  67. const { data: currentPagePath } = useCurrentPagePath();
  68. const { data: currentPathname } = useCurrentPathname();
  69. const { data: currentPage } = useSWRxCurrentPage();
  70. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  71. const { data: grantData, mutate: mutateGrant } = useSelectedGrant();
  72. const { data: pageTags, sync: syncTagsInfoForEditor } = usePageTagsForEditors(pageId);
  73. const { mutate: mutateTagsInfo } = useSWRxTagsInfo(pageId);
  74. const { data: editingMarkdown, mutate: mutateEditingMarkdown } = useEditingMarkdown();
  75. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  76. const { data: templateBodyData } = useTemplateBodyData();
  77. const { data: isEditable } = useIsEditable();
  78. const { mutate: mutateWaitingSaveProcessing } = useWaitingSaveProcessing();
  79. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  80. const { data: isSlackEnabled } = useIsSlackEnabled();
  81. const { data: isIndentSizeForced } = useIsIndentSizeForced();
  82. const { data: currentIndentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  83. const { data: isUploadableFile } = useIsUploadableFile();
  84. const { data: isUploadableImage } = useIsUploadableImage();
  85. const { data: conflictDiffModalStatus, close: closeConflictDiffModal } = useConflictDiffModal();
  86. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  87. const { mutate: mutateRemotePageId } = useRemoteRevisionId();
  88. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionBody();
  89. const { mutate: mutateRemoteRevisionLastUpdatedAt } = useRemoteRevisionLastUpdatedAt();
  90. const { mutate: mutateRemoteRevisionLastUpdateUser } = useRemoteRevisionLastUpdateUser();
  91. const { data: rendererOptions } = usePreviewOptions();
  92. const { mutate: mutateIsEnabledUnsavedWarning } = useIsEnabledUnsavedWarning();
  93. const saveOrUpdate = useSaveOrUpdate();
  94. const updateStateAfterSave = useUpdateStateAfterSave(pageId, { supressEditingMarkdownMutation: true });
  95. const currentRevisionId = currentPage?.revision?._id;
  96. const initialValue = useMemo(() => {
  97. if (!isNotFound) {
  98. return editingMarkdown ?? '';
  99. }
  100. let initialValue = '';
  101. if (isEnabledAttachTitleHeader && currentPathname != null) {
  102. const pageTitle = nodePath.basename(currentPathname);
  103. initialValue += `${pathUtils.attachTitleHeader(pageTitle)}\n`;
  104. }
  105. if (templateBodyData != null) {
  106. initialValue += `${templateBodyData}\n`;
  107. }
  108. return initialValue;
  109. }, [isNotFound, currentPathname, editingMarkdown, isEnabledAttachTitleHeader, templateBodyData]);
  110. const markdownToSave = useRef<string>(initialValue);
  111. const [markdownToPreview, setMarkdownToPreview] = useState<string>(initialValue);
  112. const [isPageCreatedWithAttachmentUpload, setIsPageCreatedWithAttachmentUpload] = useState(false);
  113. const { data: socket } = useGlobalSocket();
  114. const { mutate: mutateIsConflict } = useIsConflict();
  115. const editorRef = useRef<IEditorMethods>(null);
  116. const previewRef = useRef<HTMLDivElement>(null);
  117. const checkIsConflict = useCallback((data) => {
  118. const { s2cMessagePageUpdated } = data;
  119. const isConflict = markdownToPreview !== s2cMessagePageUpdated.revisionBody;
  120. mutateIsConflict(isConflict);
  121. }, [markdownToPreview, mutateIsConflict]);
  122. useEffect(() => {
  123. markdownToSave.current = initialValue;
  124. setMarkdownToPreview(initialValue);
  125. }, [initialValue]);
  126. useEffect(() => {
  127. if (socket == null) { return }
  128. socket.on(SocketEventName.PageUpdated, checkIsConflict);
  129. return () => {
  130. socket.off(SocketEventName.PageUpdated, checkIsConflict);
  131. };
  132. }, [socket, checkIsConflict]);
  133. const optionsToSave = useMemo((): OptionsToSave | undefined => {
  134. if (grantData == null) {
  135. return;
  136. }
  137. const optionsToSave = {
  138. isSlackEnabled: isSlackEnabled ?? false,
  139. slackChannels: '', // set in save method by opts in SavePageControlls.tsx
  140. grant: grantData.grant,
  141. pageTags: pageTags ?? [],
  142. grantUserGroupId: grantData.grantedGroup?.id,
  143. grantUserGroupName: grantData.grantedGroup?.name,
  144. };
  145. return optionsToSave;
  146. }, [grantData, isSlackEnabled, pageTags]);
  147. const setMarkdownWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string, isClean: boolean) => {
  148. markdownToSave.current = value;
  149. setMarkdownToPreview(value);
  150. // Displays an unsaved warning alert
  151. mutateIsEnabledUnsavedWarning(!isClean);
  152. })), [mutateIsEnabledUnsavedWarning]);
  153. const markdownChangedHandler = useCallback((value: string, isClean: boolean): void => {
  154. setMarkdownWithDebounce(value, isClean);
  155. }, [setMarkdownWithDebounce]);
  156. const save = useCallback(async(opts?: {slackChannels: string, overwriteScopesOfDescendants?: boolean}): Promise<IPageHasId | null> => {
  157. if (currentPathname == null || optionsToSave == null) {
  158. logger.error('Some materials to save are invalid', { grantData, isSlackEnabled, currentPathname });
  159. throw new Error('Some materials to save are invalid');
  160. }
  161. const options = Object.assign(optionsToSave, opts);
  162. try {
  163. mutateWaitingSaveProcessing(true);
  164. const { page } = await saveOrUpdate(
  165. markdownToSave.current,
  166. { pageId, path: currentPagePath || currentPathname, revisionId: currentRevisionId },
  167. options,
  168. );
  169. // to sync revision id with page tree: https://github.com/weseek/growi/pull/7227
  170. mutatePageTree();
  171. return page;
  172. }
  173. catch (error) {
  174. logger.error('failed to save', error);
  175. toastError(error);
  176. if (error.code === 'conflict') {
  177. mutateRemotePageId(error.data.revisionId);
  178. mutateRemoteRevisionId(error.data.revisionBody);
  179. mutateRemoteRevisionLastUpdatedAt(error.data.createdAt);
  180. mutateRemoteRevisionLastUpdateUser(error.data.user);
  181. }
  182. return null;
  183. }
  184. finally {
  185. mutateWaitingSaveProcessing(false);
  186. }
  187. }, [
  188. currentPathname, optionsToSave, grantData, isSlackEnabled, saveOrUpdate, pageId,
  189. currentPagePath, currentRevisionId,
  190. mutateWaitingSaveProcessing, mutateRemotePageId, mutateRemoteRevisionId, mutateRemoteRevisionLastUpdatedAt, mutateRemoteRevisionLastUpdateUser,
  191. ]);
  192. const saveAndReturnToViewHandler = useCallback(async(opts: {slackChannels: string, overwriteScopesOfDescendants?: boolean}) => {
  193. if (editorMode !== EditorMode.Editor) {
  194. return;
  195. }
  196. const page = await save(opts);
  197. if (page == null) {
  198. return;
  199. }
  200. if (isNotFound) {
  201. await router.push(`/${page._id}`);
  202. }
  203. else {
  204. updateStateAfterSave?.();
  205. }
  206. mutateEditorMode(EditorMode.View);
  207. }, [editorMode, save, isNotFound, mutateEditorMode, router, updateStateAfterSave]);
  208. const saveWithShortcut = useCallback(async() => {
  209. if (editorMode !== EditorMode.Editor) {
  210. return;
  211. }
  212. const page = await save();
  213. if (page == null) {
  214. return;
  215. }
  216. if (isNotFound) {
  217. await router.push(`/${page._id}#edit`);
  218. }
  219. else {
  220. updateStateAfterSave?.();
  221. }
  222. toastSuccess(t('toaster.save_succeeded'));
  223. mutateEditorMode(EditorMode.Editor);
  224. }, [editorMode, isNotFound, mutateEditorMode, router, save, t, updateStateAfterSave]);
  225. /**
  226. * the upload event handler
  227. * @param {any} file
  228. */
  229. const uploadHandler = useCallback(async(file) => {
  230. if (editorRef.current == null) {
  231. return;
  232. }
  233. try {
  234. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  235. let res: any = await apiGet('/attachments.limit', {
  236. fileSize: file.size,
  237. });
  238. if (!res.isUploadable) {
  239. throw new Error(res.errorMessage);
  240. }
  241. const formData = new FormData();
  242. // const { pageId, path } = pageContainer.state;
  243. formData.append('file', file);
  244. if (currentPagePath != null) {
  245. formData.append('path', currentPagePath);
  246. }
  247. if (pageId != null) {
  248. formData.append('page_id', pageId);
  249. }
  250. if (pageId == null && markdownToSave.current != null) {
  251. formData.append('page_body', markdownToSave.current);
  252. }
  253. res = await apiPostForm('/attachments.add', formData);
  254. const attachment = res.attachment;
  255. const fileName = attachment.originalName;
  256. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  257. // when image
  258. if (attachment.fileFormat.startsWith('image/')) {
  259. // modify to "![fileName](url)" syntax
  260. insertText = `!${insertText}`;
  261. }
  262. editorRef.current.insertText(insertText);
  263. // when if created newly
  264. // Not using 'mutateGrant' to inherit the grant of the parent page
  265. if (res.pageCreated) {
  266. logger.info('Page is created', res.page._id);
  267. setIsPageCreatedWithAttachmentUpload(true);
  268. globalEmitter.emit('resetInitializedHackMdStatus');
  269. mutateIsLatestRevision(true);
  270. await mutateCurrentPageId(res.page._id);
  271. await mutateCurrentPage();
  272. }
  273. }
  274. catch (e) {
  275. logger.error('failed to upload', e);
  276. toastError(e);
  277. }
  278. finally {
  279. editorRef.current.terminateUploadingState();
  280. }
  281. }, [currentPagePath, mutateCurrentPage, mutateCurrentPageId, mutateIsLatestRevision, pageId]);
  282. const scrollPreviewByEditorLine = useCallback((line: number) => {
  283. if (previewRef.current == null) {
  284. return;
  285. }
  286. // prevent circular invocation
  287. if (isOriginOfScrollSyncPreview) {
  288. isOriginOfScrollSyncPreview = false; // turn off the flag
  289. return;
  290. }
  291. // turn on the flag
  292. isOriginOfScrollSyncEditor = true;
  293. scrollSyncHelper.scrollPreview(previewRef.current, line);
  294. }, []);
  295. const scrollPreviewByEditorLineWithThrottle = useMemo(() => throttle(20, scrollPreviewByEditorLine), [scrollPreviewByEditorLine]);
  296. /**
  297. * the scroll event handler from codemirror
  298. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  299. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  300. * And data.line is also available that is added by Editor component
  301. * @see https://codemirror.net/doc/manual.html#events
  302. */
  303. const editorScrolledHandler = useCallback(({ line }: { line: number }) => {
  304. // prevent scrolling
  305. // if the elapsed time from last scroll with cursor is shorter than 40ms
  306. const now = new Date();
  307. if (lastScrolledDateWithCursor != null && now.getTime() - lastScrolledDateWithCursor.getTime() < 40) {
  308. return;
  309. }
  310. scrollPreviewByEditorLineWithThrottle(line);
  311. }, [scrollPreviewByEditorLineWithThrottle]);
  312. /**
  313. * scroll Preview element by cursor moving
  314. * @param {number} line
  315. */
  316. const scrollPreviewByCursorMoving = useCallback((line: number) => {
  317. if (previewRef.current == null) {
  318. return;
  319. }
  320. // prevent circular invocation
  321. if (isOriginOfScrollSyncPreview) {
  322. isOriginOfScrollSyncPreview = false; // turn off the flag
  323. return;
  324. }
  325. // turn on the flag
  326. isOriginOfScrollSyncEditor = true;
  327. if (previewRef.current != null) {
  328. scrollSyncHelper.scrollPreviewToRevealOverflowing(previewRef.current, line);
  329. }
  330. }, []);
  331. const scrollPreviewByCursorMovingWithThrottle = useMemo(() => throttle(20, scrollPreviewByCursorMoving), [scrollPreviewByCursorMoving]);
  332. /**
  333. * the scroll event handler from codemirror
  334. * @param {number} line
  335. * @see https://codemirror.net/doc/manual.html#events
  336. */
  337. const editorScrollCursorIntoViewHandler = useCallback((line: number) => {
  338. // record date
  339. lastScrolledDateWithCursor = new Date();
  340. scrollPreviewByCursorMovingWithThrottle(line);
  341. }, [scrollPreviewByCursorMovingWithThrottle]);
  342. /**
  343. * scroll Editor component by scroll event of Preview component
  344. * @param {number} offset
  345. */
  346. const scrollEditorByPreviewScroll = useCallback((offset: number) => {
  347. if (editorRef.current == null || previewRef.current == null) {
  348. return;
  349. }
  350. // prevent circular invocation
  351. if (isOriginOfScrollSyncEditor) {
  352. isOriginOfScrollSyncEditor = false; // turn off the flag
  353. return;
  354. }
  355. // turn on the flag
  356. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  357. isOriginOfScrollSyncPreview = true;
  358. scrollSyncHelper.scrollEditor(editorRef.current, previewRef.current, offset);
  359. }, []);
  360. const scrollEditorByPreviewScrollWithThrottle = useMemo(() => throttle(20, scrollEditorByPreviewScroll), [scrollEditorByPreviewScroll]);
  361. const afterResolvedHandler = useCallback(async() => {
  362. // get page data from db
  363. const pageData = await mutateCurrentPage();
  364. // update tag
  365. await mutateTagsInfo(); // get from DB
  366. syncTagsInfoForEditor(); // sync global state for client
  367. // clear isConflict
  368. mutateIsConflict(false);
  369. // set resolved markdown in editing markdown
  370. const markdown = pageData?.revision.body ?? '';
  371. mutateEditingMarkdown(markdown);
  372. }, [mutateCurrentPage, mutateEditingMarkdown, mutateIsConflict, mutateTagsInfo, syncTagsInfoForEditor]);
  373. // initialize
  374. useEffect(() => {
  375. if (initialValue == null) {
  376. return;
  377. }
  378. markdownToSave.current = initialValue;
  379. setMarkdownToPreview(initialValue);
  380. mutateIsEnabledUnsavedWarning(false);
  381. }, [initialValue, mutateIsEnabledUnsavedWarning]);
  382. // initial caret line
  383. useEffect(() => {
  384. if (editorRef.current != null) {
  385. editorRef.current.setCaretLine(0);
  386. }
  387. }, []);
  388. // set handler to set caret line
  389. useEffect(() => {
  390. const handler = (line) => {
  391. if (editorRef.current != null) {
  392. editorRef.current.setCaretLine(line);
  393. }
  394. if (previewRef.current != null) {
  395. scrollSyncHelper.scrollPreview(previewRef.current, line);
  396. }
  397. };
  398. globalEmitter.on('setCaretLine', handler);
  399. return function cleanup() {
  400. globalEmitter.removeListener('setCaretLine', handler);
  401. };
  402. }, []);
  403. // set handler to save and return to View
  404. useEffect(() => {
  405. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  406. return function cleanup() {
  407. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  408. };
  409. }, [saveAndReturnToViewHandler]);
  410. // set handler to focus
  411. useEffect(() => {
  412. if (editorRef.current != null && editorMode === EditorMode.Editor) {
  413. editorRef.current.forceToFocus();
  414. }
  415. }, [editorMode]);
  416. // Detect indent size from contents (only when users are allowed to change it)
  417. useEffect(() => {
  418. // do nothing if the indent size fixed
  419. if (isIndentSizeForced == null || isIndentSizeForced) {
  420. return;
  421. }
  422. // detect from markdown
  423. if (initialValue != null) {
  424. const detectedIndent = detectIndent(initialValue);
  425. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  426. mutateCurrentIndentSize(detectedIndent.amount);
  427. }
  428. }
  429. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  430. // when transitioning to a different page, if the initialValue is the same,
  431. // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  432. // Also, if an attachment is uploaded and a new page is created,
  433. // "useCurrentPagePath" changes, but no page transition is made, so nothing is done.
  434. useEffect(() => {
  435. if (currentPagePath != null && !isPageCreatedWithAttachmentUpload) {
  436. editorRef.current?.setValue(initialValue);
  437. }
  438. setIsPageCreatedWithAttachmentUpload(false);
  439. }, [currentPagePath, initialValue, isPageCreatedWithAttachmentUpload]);
  440. if (!isEditable) {
  441. return <></>;
  442. }
  443. if (rendererOptions == null) {
  444. return <></>;
  445. }
  446. const isUploadable = isUploadableImage || isUploadableFile;
  447. return (
  448. <div className="d-flex flex-wrap">
  449. <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
  450. <Editor
  451. ref={editorRef}
  452. value={initialValue}
  453. isUploadable={isUploadable}
  454. isUploadableFile={isUploadableFile}
  455. indentSize={currentIndentSize}
  456. onScroll={editorScrolledHandler}
  457. onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
  458. onChange={markdownChangedHandler}
  459. onUpload={uploadHandler}
  460. onSave={saveWithShortcut}
  461. />
  462. </div>
  463. <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
  464. <Preview
  465. ref={previewRef}
  466. rendererOptions={rendererOptions}
  467. markdown={markdownToPreview}
  468. pagePath={currentPagePath}
  469. onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)}
  470. />
  471. </div>
  472. <ConflictDiffModal
  473. isOpen={conflictDiffModalStatus?.isOpened}
  474. onClose={() => closeConflictDiffModal()}
  475. markdownOnEdit={markdownToPreview}
  476. optionsToSave={optionsToSave}
  477. afterResolvedHandler={afterResolvedHandler}
  478. />
  479. </div>
  480. );
  481. });
  482. PageEditor.displayName = 'PageEditor';
  483. export default PageEditor;