PageEditor.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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(undefined);
  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 grantedGroups = grantData.grantedGroups?.map((group) => {
  146. return { item: group.id, type: group.type };
  147. });
  148. const optionsToSave = {
  149. isSlackEnabled: isSlackEnabled ?? false,
  150. slackChannels: '', // set in save method by opts in SavePageControlls.tsx
  151. grant: grantData.grant,
  152. pageTags: pageTags ?? [],
  153. grantUserGroupIds: grantedGroups,
  154. };
  155. return optionsToSave;
  156. }, [grantData, isSlackEnabled, pageTags]);
  157. const setMarkdownWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string, isClean: boolean) => {
  158. markdownToSave.current = value;
  159. setMarkdownToPreview(value);
  160. // Displays an unsaved warning alert
  161. mutateIsEnabledUnsavedWarning(!isClean);
  162. })), [mutateIsEnabledUnsavedWarning]);
  163. const markdownChangedHandler = useCallback((value: string, isClean: boolean): void => {
  164. setMarkdownWithDebounce(value, isClean);
  165. }, [setMarkdownWithDebounce]);
  166. const save = useCallback(async(opts?: {slackChannels: string, overwriteScopesOfDescendants?: boolean}): Promise<IPageHasId | null> => {
  167. if (currentPathname == null || optionsToSave == null) {
  168. logger.error('Some materials to save are invalid', { grantData, isSlackEnabled, currentPathname });
  169. throw new Error('Some materials to save are invalid');
  170. }
  171. const options = Object.assign(optionsToSave, opts);
  172. try {
  173. mutateWaitingSaveProcessing(true);
  174. const { page } = await saveOrUpdate(
  175. markdownToSave.current,
  176. { pageId, path: currentPagePath || currentPathname, revisionId: currentRevisionId },
  177. options,
  178. );
  179. // to sync revision id with page tree: https://github.com/weseek/growi/pull/7227
  180. mutatePageTree();
  181. return page;
  182. }
  183. catch (error) {
  184. logger.error('failed to save', error);
  185. toastError(error);
  186. if (error.code === 'conflict') {
  187. mutateRemotePageId(error.data.revisionId);
  188. mutateRemoteRevisionId(error.data.revisionBody);
  189. mutateRemoteRevisionLastUpdatedAt(error.data.createdAt);
  190. mutateRemoteRevisionLastUpdateUser(error.data.user);
  191. }
  192. return null;
  193. }
  194. finally {
  195. mutateWaitingSaveProcessing(false);
  196. }
  197. }, [
  198. currentPathname, optionsToSave, grantData, isSlackEnabled, saveOrUpdate, pageId,
  199. currentPagePath, currentRevisionId,
  200. mutateWaitingSaveProcessing, mutateRemotePageId, mutateRemoteRevisionId, mutateRemoteRevisionLastUpdatedAt, mutateRemoteRevisionLastUpdateUser,
  201. ]);
  202. const saveAndReturnToViewHandler = useCallback(async(opts: {slackChannels: string, overwriteScopesOfDescendants?: boolean}) => {
  203. if (editorMode !== EditorMode.Editor) {
  204. return;
  205. }
  206. const page = await save(opts);
  207. if (page == null) {
  208. return;
  209. }
  210. if (isNotFound) {
  211. await router.push(`/${page._id}`);
  212. }
  213. else {
  214. updateStateAfterSave?.();
  215. }
  216. mutateEditorMode(EditorMode.View);
  217. }, [editorMode, save, isNotFound, mutateEditorMode, router, updateStateAfterSave]);
  218. const saveWithShortcut = useCallback(async() => {
  219. if (editorMode !== EditorMode.Editor) {
  220. return;
  221. }
  222. const page = await save();
  223. if (page == null) {
  224. return;
  225. }
  226. if (isNotFound) {
  227. await router.push(`/${page._id}#edit`);
  228. }
  229. else {
  230. updateStateAfterSave?.();
  231. }
  232. toastSuccess(t('toaster.save_succeeded'));
  233. mutateEditorMode(EditorMode.Editor);
  234. }, [editorMode, isNotFound, mutateEditorMode, router, save, t, updateStateAfterSave]);
  235. /**
  236. * the upload event handler
  237. * @param {any} file
  238. */
  239. const uploadHandler = useCallback(async(file) => {
  240. if (editorRef.current == null) {
  241. return;
  242. }
  243. try {
  244. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  245. let res: any = await apiGet('/attachments.limit', {
  246. fileSize: file.size,
  247. });
  248. if (!res.isUploadable) {
  249. throw new Error(res.errorMessage);
  250. }
  251. const formData = new FormData();
  252. // const { pageId, path } = pageContainer.state;
  253. formData.append('file', file);
  254. if (currentPagePath != null) {
  255. formData.append('path', currentPagePath);
  256. }
  257. if (pageId != null) {
  258. formData.append('page_id', pageId);
  259. }
  260. if (pageId == null && markdownToSave.current != null) {
  261. formData.append('page_body', markdownToSave.current);
  262. }
  263. res = await apiPostForm('/attachments.add', formData);
  264. const attachment = res.attachment;
  265. const fileName = attachment.originalName;
  266. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  267. // when image
  268. if (attachment.fileFormat.startsWith('image/')) {
  269. // modify to "![fileName](url)" syntax
  270. insertText = `!${insertText}`;
  271. }
  272. editorRef.current.insertText(insertText);
  273. // when if created newly
  274. // Not using 'mutateGrant' to inherit the grant of the parent page
  275. if (res.pageCreated) {
  276. logger.info('Page is created', res.page._id);
  277. globalEmitter.emit('resetInitializedHackMdStatus');
  278. mutateIsLatestRevision(true);
  279. setCreatedPageRevisionIdWithAttachment(res.page.revision);
  280. await mutateCurrentPageId(res.page._id);
  281. await mutateCurrentPage();
  282. }
  283. }
  284. catch (e) {
  285. logger.error('failed to upload', e);
  286. toastError(e);
  287. }
  288. finally {
  289. editorRef.current.terminateUploadingState();
  290. }
  291. }, [currentPagePath, mutateCurrentPage, mutateCurrentPageId, mutateIsLatestRevision, pageId]);
  292. const scrollPreviewByEditorLine = useCallback((line: number) => {
  293. if (previewRef.current == null) {
  294. return;
  295. }
  296. // prevent circular invocation
  297. if (isOriginOfScrollSyncPreview) {
  298. isOriginOfScrollSyncPreview = false; // turn off the flag
  299. return;
  300. }
  301. // turn on the flag
  302. isOriginOfScrollSyncEditor = true;
  303. scrollSyncHelper.scrollPreview(previewRef.current, line);
  304. }, []);
  305. const scrollPreviewByEditorLineWithThrottle = useMemo(() => throttle(20, scrollPreviewByEditorLine), [scrollPreviewByEditorLine]);
  306. /**
  307. * the scroll event handler from codemirror
  308. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  309. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  310. * And data.line is also available that is added by Editor component
  311. * @see https://codemirror.net/doc/manual.html#events
  312. */
  313. const editorScrolledHandler = useCallback(({ line }: { line: number }) => {
  314. // prevent scrolling
  315. // if the elapsed time from last scroll with cursor is shorter than 40ms
  316. const now = new Date();
  317. if (lastScrolledDateWithCursor != null && now.getTime() - lastScrolledDateWithCursor.getTime() < 40) {
  318. return;
  319. }
  320. scrollPreviewByEditorLineWithThrottle(line);
  321. }, [scrollPreviewByEditorLineWithThrottle]);
  322. /**
  323. * scroll Preview element by cursor moving
  324. * @param {number} line
  325. */
  326. const scrollPreviewByCursorMoving = useCallback((line: number) => {
  327. if (previewRef.current == null) {
  328. return;
  329. }
  330. // prevent circular invocation
  331. if (isOriginOfScrollSyncPreview) {
  332. isOriginOfScrollSyncPreview = false; // turn off the flag
  333. return;
  334. }
  335. // turn on the flag
  336. isOriginOfScrollSyncEditor = true;
  337. if (previewRef.current != null) {
  338. scrollSyncHelper.scrollPreviewToRevealOverflowing(previewRef.current, line);
  339. }
  340. }, []);
  341. const scrollPreviewByCursorMovingWithThrottle = useMemo(() => throttle(20, scrollPreviewByCursorMoving), [scrollPreviewByCursorMoving]);
  342. /**
  343. * the scroll event handler from codemirror
  344. * @param {number} line
  345. * @see https://codemirror.net/doc/manual.html#events
  346. */
  347. const editorScrollCursorIntoViewHandler = useCallback((line: number) => {
  348. // record date
  349. lastScrolledDateWithCursor = new Date();
  350. scrollPreviewByCursorMovingWithThrottle(line);
  351. }, [scrollPreviewByCursorMovingWithThrottle]);
  352. /**
  353. * scroll Editor component by scroll event of Preview component
  354. * @param {number} offset
  355. */
  356. const scrollEditorByPreviewScroll = useCallback((offset: number) => {
  357. if (editorRef.current == null || previewRef.current == null) {
  358. return;
  359. }
  360. // prevent circular invocation
  361. if (isOriginOfScrollSyncEditor) {
  362. isOriginOfScrollSyncEditor = false; // turn off the flag
  363. return;
  364. }
  365. // turn on the flag
  366. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  367. isOriginOfScrollSyncPreview = true;
  368. scrollSyncHelper.scrollEditor(editorRef.current, previewRef.current, offset);
  369. }, []);
  370. const scrollEditorByPreviewScrollWithThrottle = useMemo(() => throttle(20, scrollEditorByPreviewScroll), [scrollEditorByPreviewScroll]);
  371. const afterResolvedHandler = useCallback(async() => {
  372. // get page data from db
  373. const pageData = await mutateCurrentPage();
  374. // update tag
  375. await mutateTagsInfo(); // get from DB
  376. syncTagsInfoForEditor(); // sync global state for client
  377. // clear isConflict
  378. mutateIsConflict(false);
  379. // set resolved markdown in editing markdown
  380. const markdown = pageData?.revision.body ?? '';
  381. mutateEditingMarkdown(markdown);
  382. }, [mutateCurrentPage, mutateEditingMarkdown, mutateIsConflict, mutateTagsInfo, syncTagsInfoForEditor]);
  383. // initialize
  384. useEffect(() => {
  385. if (initialValue == null) {
  386. return;
  387. }
  388. markdownToSave.current = initialValue;
  389. setMarkdownToPreview(initialValue);
  390. mutateIsEnabledUnsavedWarning(false);
  391. }, [initialValue, mutateIsEnabledUnsavedWarning]);
  392. // initial caret line
  393. useEffect(() => {
  394. if (editorRef.current != null) {
  395. editorRef.current.setCaretLine(0);
  396. }
  397. }, []);
  398. // set handler to set caret line
  399. useEffect(() => {
  400. const handler = (line) => {
  401. if (editorRef.current != null) {
  402. editorRef.current.setCaretLine(line);
  403. }
  404. if (previewRef.current != null) {
  405. scrollSyncHelper.scrollPreview(previewRef.current, line);
  406. }
  407. };
  408. globalEmitter.on('setCaretLine', handler);
  409. return function cleanup() {
  410. globalEmitter.removeListener('setCaretLine', handler);
  411. };
  412. }, []);
  413. // set handler to save and return to View
  414. useEffect(() => {
  415. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  416. return function cleanup() {
  417. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  418. };
  419. }, [saveAndReturnToViewHandler]);
  420. // set handler to focus
  421. useEffect(() => {
  422. if (editorRef.current != null && editorMode === EditorMode.Editor) {
  423. editorRef.current.forceToFocus();
  424. }
  425. }, [editorMode]);
  426. // Detect indent size from contents (only when users are allowed to change it)
  427. useEffect(() => {
  428. // do nothing if the indent size fixed
  429. if (isIndentSizeForced == null || isIndentSizeForced) {
  430. return;
  431. }
  432. // detect from markdown
  433. if (initialValue != null) {
  434. const detectedIndent = detectIndent(initialValue);
  435. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  436. mutateCurrentIndentSize(detectedIndent.amount);
  437. }
  438. }
  439. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  440. // when transitioning to a different page, if the initialValue is the same,
  441. // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  442. const onRouterChangeComplete = useCallback(() => {
  443. editorRef.current?.setValue(initialValue);
  444. editorRef.current?.setCaretLine(0);
  445. }, [initialValue]);
  446. useEffect(() => {
  447. router.events.on('routeChangeComplete', onRouterChangeComplete);
  448. return () => {
  449. router.events.off('routeChangeComplete', onRouterChangeComplete);
  450. };
  451. }, [onRouterChangeComplete, router.events]);
  452. if (!isEditable) {
  453. return <></>;
  454. }
  455. if (rendererOptions == null) {
  456. return <></>;
  457. }
  458. const isUploadable = isUploadableImage || isUploadableFile;
  459. return (
  460. <div className="d-flex flex-wrap">
  461. <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
  462. <Editor
  463. ref={editorRef}
  464. value={initialValue}
  465. isUploadable={isUploadable}
  466. isUploadableFile={isUploadableFile}
  467. indentSize={currentIndentSize}
  468. onScroll={editorScrolledHandler}
  469. onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
  470. onChange={markdownChangedHandler}
  471. onUpload={uploadHandler}
  472. onSave={saveWithShortcut}
  473. />
  474. </div>
  475. <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
  476. <Preview
  477. ref={previewRef}
  478. rendererOptions={rendererOptions}
  479. markdown={markdownToPreview}
  480. pagePath={currentPagePath}
  481. onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)}
  482. />
  483. </div>
  484. <ConflictDiffModal
  485. isOpen={conflictDiffModalStatus?.isOpened}
  486. onClose={() => closeConflictDiffModal()}
  487. markdownOnEdit={markdownToPreview}
  488. optionsToSave={optionsToSave}
  489. afterResolvedHandler={afterResolvedHandler}
  490. />
  491. </div>
  492. );
  493. });
  494. PageEditor.displayName = 'PageEditor';
  495. export default PageEditor;