PageEditor.tsx 20 KB

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