PageEditor.tsx 16 KB

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