PageEditor.tsx 16 KB

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