PageEditor.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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 { EditorNavbar } from './EditorNavbar';
  56. import EditorNavbarBottom from './EditorNavbarBottom';
  57. import Preview from './Preview';
  58. import { scrollEditor, scrollPreview } from './ScrollSyncHelper';
  59. import '@growi/editor/dist/style.css';
  60. // import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
  61. // import { ConflictDiffModal } from './ConflictDiffModal';
  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 isRevisionIdRequiredForPageUpdate = currentPage?.revision?.origin === undefined;
  163. const { page } = await updatePage({
  164. pageId,
  165. revisionId: isRevisionIdRequiredForPageUpdate ? currentRevisionId : undefined,
  166. body: codeMirrorEditor?.getDoc() ?? '',
  167. grant: grantData?.grant,
  168. origin: Origin.Editor,
  169. userRelatedGrantUserGroupIds: grantData?.userRelatedGrantedGroups?.map((group) => {
  170. return { item: group.id, type: group.type };
  171. }),
  172. ...(opts ?? {}),
  173. });
  174. // to sync revision id with page tree: https://github.com/weseek/growi/pull/7227
  175. mutatePageTree();
  176. return page;
  177. }
  178. catch (error) {
  179. logger.error('failed to save', error);
  180. toastError(error);
  181. if (error.code === 'conflict') {
  182. mutateRemotePageId(error.data.revisionId);
  183. mutateRemoteRevisionId(error.data.revisionBody);
  184. mutateRemoteRevisionLastUpdatedAt(error.data.createdAt);
  185. mutateRemoteRevisionLastUpdateUser(error.data.user);
  186. }
  187. return null;
  188. }
  189. finally {
  190. mutateWaitingSaveProcessing(false);
  191. }
  192. // eslint-disable-next-line max-len
  193. }, [codeMirrorEditor, grantData, pageId, currentRevisionId, mutateWaitingSaveProcessing, mutateRemotePageId, mutateRemoteRevisionId, mutateRemoteRevisionLastUpdatedAt, mutateRemoteRevisionLastUpdateUser]);
  194. const saveAndReturnToViewHandler = useCallback(async(opts: {slackChannels: string, overwriteScopesOfDescendants?: boolean}) => {
  195. const page = await save(opts);
  196. if (page == null) {
  197. return;
  198. }
  199. mutateEditorMode(EditorMode.View);
  200. updateStateAfterSave?.();
  201. }, [mutateEditorMode, save, updateStateAfterSave]);
  202. const saveWithShortcut = useCallback(async() => {
  203. const page = await save();
  204. if (page == null) {
  205. return;
  206. }
  207. toastSuccess(t('toaster.save_succeeded'));
  208. updateStateAfterSave?.();
  209. }, [save, t, updateStateAfterSave]);
  210. // the upload event handler
  211. const uploadHandler = useCallback((files: File[]) => {
  212. files.forEach(async(file) => {
  213. try {
  214. const { data: resLimit } = await apiv3Get('/attachment/limit', { fileSize: file.size });
  215. if (!resLimit.isUploadable) {
  216. throw new Error(resLimit.errorMessage);
  217. }
  218. const formData = new FormData();
  219. formData.append('file', file);
  220. if (pageId != null) {
  221. formData.append('page_id', pageId);
  222. }
  223. const { data: resAdd } = await apiv3PostForm('/attachment', formData);
  224. const attachment = resAdd.attachment;
  225. const fileName = attachment.originalName;
  226. let insertText = `[${fileName}](${attachment.filePathProxied})\n`;
  227. // when image
  228. if (attachment.fileFormat.startsWith('image/')) {
  229. // modify to "![fileName](url)" syntax
  230. insertText = `!${insertText}`;
  231. }
  232. codeMirrorEditor?.insertText(insertText);
  233. }
  234. catch (e) {
  235. logger.error('failed to upload', e);
  236. toastError(e);
  237. }
  238. });
  239. }, [codeMirrorEditor, pageId]);
  240. const scrollEditorHandler = useCallback(() => {
  241. if (codeMirrorEditor?.view?.scrollDOM == null || previewRef.current == null) {
  242. return;
  243. }
  244. if (isOriginOfScrollSyncPreview) {
  245. isOriginOfScrollSyncPreview = false;
  246. return;
  247. }
  248. isOriginOfScrollSyncEditor = true;
  249. scrollEditor(codeMirrorEditor.view.scrollDOM, previewRef.current);
  250. }, [codeMirrorEditor]);
  251. const scrollEditorHandlerThrottle = useMemo(() => throttle(25, scrollEditorHandler), [scrollEditorHandler]);
  252. const scrollPreviewHandler = useCallback(() => {
  253. if (codeMirrorEditor?.view?.scrollDOM == null || previewRef.current == null) {
  254. return;
  255. }
  256. if (isOriginOfScrollSyncEditor) {
  257. isOriginOfScrollSyncEditor = false;
  258. return;
  259. }
  260. isOriginOfScrollSyncPreview = true;
  261. scrollPreview(codeMirrorEditor.view.scrollDOM, previewRef.current);
  262. }, [codeMirrorEditor]);
  263. const scrollPreviewHandlerThrottle = useMemo(() => throttle(25, scrollPreviewHandler), [scrollPreviewHandler]);
  264. const afterResolvedHandler = useCallback(async() => {
  265. // get page data from db
  266. const pageData = await mutateCurrentPage();
  267. // update tag
  268. await mutateTagsInfo(); // get from DB
  269. syncTagsInfoForEditor(); // sync global state for client
  270. // clear isConflict
  271. mutateIsConflict(false);
  272. // set resolved markdown in editing markdown
  273. const markdown = pageData?.revision?.body ?? '';
  274. mutateEditingMarkdown(markdown);
  275. }, [mutateCurrentPage, mutateEditingMarkdown, mutateIsConflict, mutateTagsInfo, syncTagsInfoForEditor]);
  276. // initial caret line
  277. useEffect(() => {
  278. codeMirrorEditor?.setCaretLine();
  279. }, [codeMirrorEditor]);
  280. // set handler to save and return to View
  281. useEffect(() => {
  282. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  283. return function cleanup() {
  284. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  285. };
  286. }, [saveAndReturnToViewHandler]);
  287. // set handler to focus
  288. useLayoutEffect(() => {
  289. if (editorMode === EditorMode.Editor) {
  290. codeMirrorEditor?.focus();
  291. }
  292. }, [codeMirrorEditor, editorMode]);
  293. // Detect indent size from contents (only when users are allowed to change it)
  294. useEffect(() => {
  295. // do nothing if the indent size fixed
  296. if (isIndentSizeForced == null || isIndentSizeForced) {
  297. mutateCurrentIndentSize(undefined);
  298. return;
  299. }
  300. // detect from markdown
  301. if (initialValue != null) {
  302. const detectedIndent = detectIndent(initialValue);
  303. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  304. mutateCurrentIndentSize(detectedIndent.amount);
  305. }
  306. }
  307. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  308. // set handler to set caret line
  309. useEffect(() => {
  310. const handler = (lineNumber?: number) => {
  311. codeMirrorEditor?.setCaretLine(lineNumber);
  312. // TODO: scroll to the caret line
  313. };
  314. globalEmitter.on('setCaretLine', handler);
  315. return function cleanup() {
  316. globalEmitter.removeListener('setCaretLine', handler);
  317. };
  318. }, [codeMirrorEditor]);
  319. // TODO: Check the reproduction conditions that made this code necessary and confirm reproduction
  320. // // when transitioning to a different page, if the initialValue is the same,
  321. // // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  322. // const onRouterChangeComplete = useCallback(() => {
  323. // codeMirrorEditor?.initDoc(ydoc?.getText('codemirror').toString());
  324. // codeMirrorEditor?.setCaretLine();
  325. // }, [codeMirrorEditor, ydoc]);
  326. // useEffect(() => {
  327. // router.events.on('routeChangeComplete', onRouterChangeComplete);
  328. // return () => {
  329. // router.events.off('routeChangeComplete', onRouterChangeComplete);
  330. // };
  331. // }, [onRouterChangeComplete, router.events]);
  332. const pastEndStyle: CSSProperties | undefined = useMemo(() => {
  333. if (previewRect == null) {
  334. return undefined;
  335. }
  336. const previewRectHeight = previewRect.height;
  337. // containerHeight - 1.5 line height
  338. return { paddingBottom: `calc(${previewRectHeight}px - 2em)` };
  339. }, [previewRect]);
  340. if (!isEditable) {
  341. return <></>;
  342. }
  343. if (rendererOptions == null) {
  344. return <></>;
  345. }
  346. return (
  347. <div data-testid="page-editor" id="page-editor" className={`flex-expand-vert ${props.visibility ? '' : 'd-none'}`}>
  348. <EditorNavbar />
  349. <div className={`flex-expand-horiz ${props.visibility ? '' : 'd-none'}`}>
  350. <div className="page-editor-editor-container flex-expand-vert border-end">
  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. editorSettings={editorSettings}
  362. onEditorsUpdated={onEditorsUpdated}
  363. />
  364. </div>
  365. <div
  366. ref={previewRef}
  367. onScroll={scrollPreviewHandlerThrottle}
  368. className="page-editor-preview-container flex-expand-vert overflow-y-auto d-none d-lg-flex"
  369. >
  370. <Preview
  371. rendererOptions={rendererOptions}
  372. markdown={markdownToPreview}
  373. pagePath={currentPagePath}
  374. expandContentWidth={shouldExpandContent}
  375. style={pastEndStyle}
  376. />
  377. </div>
  378. {/*
  379. <ConflictDiffModal
  380. isOpen={conflictDiffModalStatus?.isOpened}
  381. onClose={() => closeConflictDiffModal()}
  382. markdownOnEdit={markdownToPreview}
  383. optionsToSave={optionsToSave}
  384. afterResolvedHandler={afterResolvedHandler}
  385. />
  386. */}
  387. </div>
  388. <EditorNavbarBottom />
  389. </div>
  390. );
  391. });
  392. PageEditor.displayName = 'PageEditor';