PageEditor.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import type { CSSProperties } from 'react';
  2. import React, {
  3. useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,
  4. } from 'react';
  5. import type EventEmitter from 'events';
  6. import nodePath from 'path';
  7. import type { IPageHasId } from '@growi/core';
  8. import { useGlobalSocket } from '@growi/core/dist/swr';
  9. import { pathUtils } from '@growi/core/dist/utils';
  10. import {
  11. CodeMirrorEditorMain, GlobalCodeMirrorEditorKey,
  12. useCodeMirrorEditorIsolated, useResolvedThemeForEditor,
  13. } from '@growi/editor';
  14. import { useRect } from '@growi/ui/dist/utils';
  15. import detectIndent from 'detect-indent';
  16. import { useTranslation } from 'next-i18next';
  17. import { throttle, debounce } from 'throttle-debounce';
  18. import { useShouldExpandContent } from '~/client/services/layout';
  19. import { useUpdateStateAfterSave, updatePage } from '~/client/services/page-operation';
  20. import { apiv3Get, apiv3PostForm } from '~/client/util/apiv3-client';
  21. import { toastError, toastSuccess } from '~/client/util/toastr';
  22. import { SocketEventName } from '~/interfaces/websocket';
  23. import {
  24. useDefaultIndentSize, useCurrentUser,
  25. useCurrentPathname, useIsEnabledAttachTitleHeader,
  26. useIsEditable, useIsIndentSizeForced,
  27. useAcceptedUploadFileType,
  28. } from '~/stores/context';
  29. import {
  30. useEditorSettings,
  31. useCurrentIndentSize, usePageTagsForEditors,
  32. useIsConflict,
  33. useEditingMarkdown,
  34. useWaitingSaveProcessing,
  35. } from '~/stores/editor';
  36. import { useConflictDiffModal } from '~/stores/modal';
  37. import {
  38. useCurrentPagePath, useSWRMUTxCurrentPage, useSWRxCurrentPage, useSWRxTagsInfo, useCurrentPageId, useIsNotFound, useIsLatestRevision, useTemplateBodyData,
  39. } from '~/stores/page';
  40. import { mutatePageTree } from '~/stores/page-listing';
  41. import {
  42. useRemoteRevisionId,
  43. useRemoteRevisionBody,
  44. useRemoteRevisionLastUpdatedAt,
  45. useRemoteRevisionLastUpdateUser,
  46. } from '~/stores/remote-latest-page';
  47. import { usePreviewOptions } from '~/stores/renderer';
  48. import {
  49. EditorMode,
  50. useEditorMode, useSelectedGrant,
  51. } from '~/stores/ui';
  52. import { useNextThemes } from '~/stores/use-next-themes';
  53. import loggerFactory from '~/utils/logger';
  54. import { PageHeader } from '../PageHeader/PageHeader';
  55. // import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
  56. // import { ConflictDiffModal } from './ConflictDiffModal';
  57. import EditorNavbarBottom from './EditorNavbarBottom';
  58. import Preview from './Preview';
  59. import { scrollEditor, scrollPreview } from './ScrollSyncHelper';
  60. import '@growi/editor/dist/style.css';
  61. const logger = loggerFactory('growi:PageEditor');
  62. declare global {
  63. // eslint-disable-next-line vars-on-top, no-var
  64. var globalEmitter: EventEmitter;
  65. }
  66. // for scrolling
  67. let isOriginOfScrollSyncEditor = false;
  68. let isOriginOfScrollSyncPreview = false;
  69. type Props = {
  70. visibility?: boolean,
  71. }
  72. export const PageEditor = React.memo((props: Props): JSX.Element => {
  73. const { t } = useTranslation();
  74. const [previewRect, previewRef] = useRect();
  75. const { data: isNotFound } = useIsNotFound();
  76. const { data: pageId } = useCurrentPageId();
  77. const { data: currentPagePath } = useCurrentPagePath();
  78. const { data: currentPathname } = useCurrentPathname();
  79. const { data: currentPage } = useSWRxCurrentPage();
  80. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  81. const { data: grantData } = useSelectedGrant();
  82. const { sync: syncTagsInfoForEditor } = usePageTagsForEditors(pageId);
  83. const { mutate: mutateTagsInfo } = useSWRxTagsInfo(pageId);
  84. const { data: editingMarkdown, mutate: mutateEditingMarkdown } = useEditingMarkdown();
  85. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  86. const { data: templateBodyData } = useTemplateBodyData();
  87. const { data: isEditable } = useIsEditable();
  88. const { mutate: mutateWaitingSaveProcessing } = useWaitingSaveProcessing();
  89. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  90. const { data: isIndentSizeForced } = useIsIndentSizeForced();
  91. const { data: currentIndentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  92. const { data: defaultIndentSize } = useDefaultIndentSize();
  93. const { data: acceptedUploadFileType } = useAcceptedUploadFileType();
  94. const { data: conflictDiffModalStatus, close: closeConflictDiffModal } = useConflictDiffModal();
  95. const { data: editorSettings } = useEditorSettings();
  96. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  97. const { mutate: mutateRemotePageId } = useRemoteRevisionId();
  98. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionBody();
  99. const { mutate: mutateRemoteRevisionLastUpdatedAt } = useRemoteRevisionLastUpdatedAt();
  100. const { mutate: mutateRemoteRevisionLastUpdateUser } = useRemoteRevisionLastUpdateUser();
  101. const { data: user } = useCurrentUser();
  102. const { data: socket } = useGlobalSocket();
  103. const { data: rendererOptions } = usePreviewOptions();
  104. const { mutate: mutateIsConflict } = useIsConflict();
  105. const { mutate: mutateResolvedTheme } = useResolvedThemeForEditor();
  106. const shouldExpandContent = useShouldExpandContent(currentPage);
  107. const updateStateAfterSave = useUpdateStateAfterSave(pageId, { supressEditingMarkdownMutation: true });
  108. const { resolvedTheme } = useNextThemes();
  109. mutateResolvedTheme({ themeData: resolvedTheme });
  110. const currentRevisionId = currentPage?.revision?._id;
  111. const initialValueRef = useRef('');
  112. const initialValue = useMemo(() => {
  113. if (!isNotFound) {
  114. return editingMarkdown ?? '';
  115. }
  116. let initialValue = '';
  117. if (isEnabledAttachTitleHeader && currentPathname != null) {
  118. const pageTitle = nodePath.basename(currentPathname);
  119. initialValue += `${pathUtils.attachTitleHeader(pageTitle)}\n`;
  120. }
  121. if (templateBodyData != null) {
  122. initialValue += `${templateBodyData}\n`;
  123. }
  124. return initialValue;
  125. }, [isNotFound, currentPathname, editingMarkdown, isEnabledAttachTitleHeader, templateBodyData]);
  126. useEffect(() => {
  127. // set to ref
  128. initialValueRef.current = initialValue;
  129. }, [initialValue]);
  130. const [markdownToPreview, setMarkdownToPreview] = useState<string>(initialValue);
  131. const setMarkdownPreviewWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string) => {
  132. setMarkdownToPreview(value);
  133. })), []);
  134. const markdownChangedHandler = useCallback((value: string) => {
  135. setMarkdownPreviewWithDebounce(value);
  136. }, [setMarkdownPreviewWithDebounce]);
  137. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  138. const checkIsConflict = useCallback((data) => {
  139. const { s2cMessagePageUpdated } = data;
  140. const isConflict = markdownToPreview !== s2cMessagePageUpdated.revisionBody;
  141. mutateIsConflict(isConflict);
  142. }, [markdownToPreview, mutateIsConflict]);
  143. useEffect(() => {
  144. if (socket == null) { return }
  145. socket.on(SocketEventName.PageUpdated, checkIsConflict);
  146. return () => {
  147. socket.off(SocketEventName.PageUpdated, checkIsConflict);
  148. };
  149. }, [socket, checkIsConflict]);
  150. const save = useCallback(async(opts?: {slackChannels: string, overwriteScopesOfDescendants?: boolean}): Promise<IPageHasId | null> => {
  151. if (pageId == null || currentRevisionId == null || grantData == null) {
  152. logger.error('Some materials to save are invalid', {
  153. pageId, currentRevisionId, grantData,
  154. });
  155. throw new Error('Some materials to save are invalid');
  156. }
  157. try {
  158. mutateWaitingSaveProcessing(true);
  159. const { page } = await updatePage({
  160. pageId,
  161. revisionId: currentRevisionId,
  162. body: codeMirrorEditor?.getDoc() ?? '',
  163. grant: grantData?.grant,
  164. userRelatedGrantUserGroupIds: grantData?.userRelatedGrantedGroups?.map((group) => {
  165. return { item: group.id, type: group.type };
  166. }),
  167. ...(opts ?? {}),
  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. // eslint-disable-next-line max-len
  188. }, [codeMirrorEditor, grantData, pageId, currentRevisionId, mutateWaitingSaveProcessing, mutateRemotePageId, mutateRemoteRevisionId, mutateRemoteRevisionLastUpdatedAt, mutateRemoteRevisionLastUpdateUser]);
  189. const saveAndReturnToViewHandler = useCallback(async(opts: {slackChannels: string, overwriteScopesOfDescendants?: boolean}) => {
  190. const page = await save(opts);
  191. if (page == null) {
  192. return;
  193. }
  194. mutateEditorMode(EditorMode.View);
  195. updateStateAfterSave?.();
  196. }, [mutateEditorMode, save, updateStateAfterSave]);
  197. const saveWithShortcut = useCallback(async() => {
  198. const page = await save();
  199. if (page == null) {
  200. return;
  201. }
  202. toastSuccess(t('toaster.save_succeeded'));
  203. updateStateAfterSave?.();
  204. }, [save, t, updateStateAfterSave]);
  205. // the upload event handler
  206. const uploadHandler = useCallback((files: File[]) => {
  207. files.forEach(async(file) => {
  208. try {
  209. const { data: resLimit } = await apiv3Get('/attachment/limit', { fileSize: file.size });
  210. if (!resLimit.isUploadable) {
  211. throw new Error(resLimit.errorMessage);
  212. }
  213. const formData = new FormData();
  214. formData.append('file', file);
  215. if (pageId != null) {
  216. formData.append('page_id', pageId);
  217. }
  218. const { data: resAdd } = await apiv3PostForm('/attachment', formData);
  219. const attachment = resAdd.attachment;
  220. const fileName = attachment.originalName;
  221. let insertText = `[${fileName}](${attachment.filePathProxied})\n`;
  222. // when image
  223. if (attachment.fileFormat.startsWith('image/')) {
  224. // modify to "![fileName](url)" syntax
  225. insertText = `!${insertText}`;
  226. }
  227. codeMirrorEditor?.insertText(insertText);
  228. }
  229. catch (e) {
  230. logger.error('failed to upload', e);
  231. toastError(e);
  232. }
  233. });
  234. }, [codeMirrorEditor, pageId]);
  235. const scrollEditorHandler = useCallback(() => {
  236. if (codeMirrorEditor?.view?.scrollDOM == null || previewRef.current == null) {
  237. return;
  238. }
  239. if (isOriginOfScrollSyncPreview) {
  240. isOriginOfScrollSyncPreview = false;
  241. return;
  242. }
  243. isOriginOfScrollSyncEditor = true;
  244. scrollEditor(codeMirrorEditor.view.scrollDOM, previewRef.current);
  245. }, [codeMirrorEditor, previewRef]);
  246. const scrollEditorHandlerThrottle = useMemo(() => throttle(25, scrollEditorHandler), [scrollEditorHandler]);
  247. const scrollPreviewHandler = useCallback(() => {
  248. if (codeMirrorEditor?.view?.scrollDOM == null || previewRef.current == null) {
  249. return;
  250. }
  251. if (isOriginOfScrollSyncEditor) {
  252. isOriginOfScrollSyncEditor = false;
  253. return;
  254. }
  255. isOriginOfScrollSyncPreview = true;
  256. scrollPreview(codeMirrorEditor.view.scrollDOM, previewRef.current);
  257. }, [codeMirrorEditor, previewRef]);
  258. const scrollPreviewHandlerThrottle = useMemo(() => throttle(25, scrollPreviewHandler), [scrollPreviewHandler]);
  259. const afterResolvedHandler = useCallback(async() => {
  260. // get page data from db
  261. const pageData = await mutateCurrentPage();
  262. // update tag
  263. await mutateTagsInfo(); // get from DB
  264. syncTagsInfoForEditor(); // sync global state for client
  265. // clear isConflict
  266. mutateIsConflict(false);
  267. // set resolved markdown in editing markdown
  268. const markdown = pageData?.revision?.body ?? '';
  269. mutateEditingMarkdown(markdown);
  270. }, [mutateCurrentPage, mutateEditingMarkdown, mutateIsConflict, mutateTagsInfo, syncTagsInfoForEditor]);
  271. // initial caret line
  272. useEffect(() => {
  273. codeMirrorEditor?.setCaretLine();
  274. }, [codeMirrorEditor]);
  275. // set handler to save and return to View
  276. useEffect(() => {
  277. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  278. return function cleanup() {
  279. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  280. };
  281. }, [saveAndReturnToViewHandler]);
  282. // set handler to focus
  283. useLayoutEffect(() => {
  284. if (editorMode === EditorMode.Editor) {
  285. codeMirrorEditor?.focus();
  286. }
  287. }, [codeMirrorEditor, editorMode]);
  288. // Detect indent size from contents (only when users are allowed to change it)
  289. useEffect(() => {
  290. // do nothing if the indent size fixed
  291. if (isIndentSizeForced == null || isIndentSizeForced) {
  292. mutateCurrentIndentSize(undefined);
  293. return;
  294. }
  295. // detect from markdown
  296. if (initialValue != null) {
  297. const detectedIndent = detectIndent(initialValue);
  298. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  299. mutateCurrentIndentSize(detectedIndent.amount);
  300. }
  301. }
  302. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  303. // set handler to set caret line
  304. useEffect(() => {
  305. const handler = (lineNumber?: number) => {
  306. codeMirrorEditor?.setCaretLine(lineNumber);
  307. // TODO: scroll to the caret line
  308. };
  309. globalEmitter.on('setCaretLine', handler);
  310. return function cleanup() {
  311. globalEmitter.removeListener('setCaretLine', handler);
  312. };
  313. }, [codeMirrorEditor]);
  314. // TODO: Check the reproduction conditions that made this code necessary and confirm reproduction
  315. // // when transitioning to a different page, if the initialValue is the same,
  316. // // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  317. // const onRouterChangeComplete = useCallback(() => {
  318. // codeMirrorEditor?.initDoc(ydoc?.getText('codemirror').toString());
  319. // codeMirrorEditor?.setCaretLine();
  320. // }, [codeMirrorEditor, ydoc]);
  321. // useEffect(() => {
  322. // router.events.on('routeChangeComplete', onRouterChangeComplete);
  323. // return () => {
  324. // router.events.off('routeChangeComplete', onRouterChangeComplete);
  325. // };
  326. // }, [onRouterChangeComplete, router.events]);
  327. const pastEndStyle: CSSProperties | undefined = useMemo(() => {
  328. if (previewRect == null) {
  329. return undefined;
  330. }
  331. const previewRectHeight = previewRect.height;
  332. // containerHeight - 1.5 line height
  333. return { paddingBottom: `calc(${previewRectHeight}px - 2em)` };
  334. }, [previewRect]);
  335. if (!isEditable) {
  336. return <></>;
  337. }
  338. if (rendererOptions == null) {
  339. return <></>;
  340. }
  341. return (
  342. <div data-testid="page-editor" id="page-editor" className={`flex-expand-vert ${props.visibility ? '' : 'd-none'}`}>
  343. <div className="px-4 py-2">
  344. <PageHeader />
  345. </div>
  346. <div className={`flex-expand-horiz ${props.visibility ? '' : 'd-none'}`}>
  347. <div className="page-editor-editor-container flex-expand-vert">
  348. <CodeMirrorEditorMain
  349. onChange={markdownChangedHandler}
  350. onSave={saveWithShortcut}
  351. onUpload={uploadHandler}
  352. acceptedUploadFileType={acceptedUploadFileType}
  353. onScroll={scrollEditorHandlerThrottle}
  354. indentSize={currentIndentSize ?? defaultIndentSize}
  355. userName={user?.name}
  356. pageId={pageId ?? undefined}
  357. initialValue={initialValue}
  358. onOpenEditor={markdown => setMarkdownToPreview(markdown)}
  359. editorTheme={editorSettings?.theme}
  360. editorKeymap={editorSettings?.keymapMode}
  361. />
  362. </div>
  363. <div
  364. ref={previewRef}
  365. onScroll={scrollPreviewHandlerThrottle}
  366. className="page-editor-preview-container flex-expand-vert d-none d-lg-flex"
  367. >
  368. <Preview
  369. rendererOptions={rendererOptions}
  370. markdown={markdownToPreview}
  371. pagePath={currentPagePath}
  372. expandContentWidth={shouldExpandContent}
  373. style={pastEndStyle}
  374. />
  375. </div>
  376. {/*
  377. <ConflictDiffModal
  378. isOpen={conflictDiffModalStatus?.isOpened}
  379. onClose={() => closeConflictDiffModal()}
  380. markdownOnEdit={markdownToPreview}
  381. optionsToSave={optionsToSave}
  382. afterResolvedHandler={afterResolvedHandler}
  383. />
  384. */}
  385. </div>
  386. <EditorNavbarBottom />
  387. </div>
  388. );
  389. });
  390. PageEditor.displayName = 'PageEditor';