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