PageEditor.tsx 17 KB

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