PageEditor.tsx 19 KB

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