PageEditor.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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,
  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, useIsIndentSizeForced,
  26. useAcceptedUploadFileType,
  27. } from '~/stores/context';
  28. import {
  29. useEditorSettings,
  30. useCurrentIndentSize, useIsSlackEnabled, usePageTagsForEditors,
  31. useIsConflict,
  32. useEditingMarkdown,
  33. useWaitingSaveProcessing,
  34. } from '~/stores/editor';
  35. import { useConflictDiffModal } from '~/stores/modal';
  36. import {
  37. useCurrentPagePath, useSWRMUTxCurrentPage, useSWRxCurrentPage, useSWRxTagsInfo, useCurrentPageId, useIsNotFound, useIsLatestRevision, useTemplateBodyData,
  38. } from '~/stores/page';
  39. import { mutatePageTree } from '~/stores/page-listing';
  40. import {
  41. useRemoteRevisionId,
  42. useRemoteRevisionBody,
  43. useRemoteRevisionLastUpdatedAt,
  44. useRemoteRevisionLastUpdateUser,
  45. } from '~/stores/remote-latest-page';
  46. import { usePreviewOptions } from '~/stores/renderer';
  47. import {
  48. EditorMode,
  49. useEditorMode, useSelectedGrant,
  50. } from '~/stores/ui';
  51. import { useNextThemes } from '~/stores/use-next-themes';
  52. import loggerFactory from '~/utils/logger';
  53. import { PageHeader } from '../PageHeader/PageHeader';
  54. // import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
  55. // import { ConflictDiffModal } from './ConflictDiffModal';
  56. // import Editor from './Editor';
  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 router = useRouter();
  75. const previewRef = useRef<HTMLDivElement>(null);
  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: isSlackEnabled } = useIsSlackEnabled();
  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 { 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 scrollEditorHandler = useCallback(() => {
  254. if (codeMirrorEditor?.view?.scrollDOM == null || previewRef.current == null) {
  255. return;
  256. }
  257. if (isOriginOfScrollSyncPreview) {
  258. isOriginOfScrollSyncPreview = false;
  259. return;
  260. }
  261. isOriginOfScrollSyncEditor = true;
  262. scrollEditor(codeMirrorEditor.view.scrollDOM, previewRef.current);
  263. }, [codeMirrorEditor, previewRef]);
  264. const scrollEditorHandlerThrottle = useMemo(() => throttle(25, scrollEditorHandler), [scrollEditorHandler]);
  265. const scrollPreviewHandler = useCallback(() => {
  266. if (codeMirrorEditor?.view?.scrollDOM == null || previewRef.current == null) {
  267. return;
  268. }
  269. if (isOriginOfScrollSyncEditor) {
  270. isOriginOfScrollSyncEditor = false;
  271. return;
  272. }
  273. isOriginOfScrollSyncPreview = true;
  274. scrollPreview(codeMirrorEditor.view.scrollDOM, previewRef.current);
  275. }, [codeMirrorEditor, previewRef]);
  276. const scrollPreviewHandlerThrottle = useMemo(() => throttle(25, scrollPreviewHandler), [scrollPreviewHandler]);
  277. const afterResolvedHandler = useCallback(async() => {
  278. // get page data from db
  279. const pageData = await mutateCurrentPage();
  280. // update tag
  281. await mutateTagsInfo(); // get from DB
  282. syncTagsInfoForEditor(); // sync global state for client
  283. // clear isConflict
  284. mutateIsConflict(false);
  285. // set resolved markdown in editing markdown
  286. const markdown = pageData?.revision.body ?? '';
  287. mutateEditingMarkdown(markdown);
  288. }, [mutateCurrentPage, mutateEditingMarkdown, mutateIsConflict, mutateTagsInfo, syncTagsInfoForEditor]);
  289. // initial caret line
  290. useEffect(() => {
  291. codeMirrorEditor?.setCaretLine();
  292. }, [codeMirrorEditor]);
  293. // set handler to save and return to View
  294. useEffect(() => {
  295. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  296. return function cleanup() {
  297. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  298. };
  299. }, [saveAndReturnToViewHandler]);
  300. // set handler to focus
  301. useLayoutEffect(() => {
  302. if (editorMode === EditorMode.Editor) {
  303. codeMirrorEditor?.focus();
  304. }
  305. }, [codeMirrorEditor, editorMode]);
  306. // Detect indent size from contents (only when users are allowed to change it)
  307. useEffect(() => {
  308. // do nothing if the indent size fixed
  309. if (isIndentSizeForced == null || isIndentSizeForced) {
  310. mutateCurrentIndentSize(undefined);
  311. return;
  312. }
  313. // detect from markdown
  314. if (initialValue != null) {
  315. const detectedIndent = detectIndent(initialValue);
  316. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  317. mutateCurrentIndentSize(detectedIndent.amount);
  318. }
  319. }
  320. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  321. // TODO: Check the reproduction conditions that made this code necessary and confirm reproduction
  322. // // when transitioning to a different page, if the initialValue is the same,
  323. // // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  324. // const onRouterChangeComplete = useCallback(() => {
  325. // codeMirrorEditor?.initDoc(ydoc?.getText('codemirror').toString());
  326. // codeMirrorEditor?.setCaretLine();
  327. // }, [codeMirrorEditor, ydoc]);
  328. // useEffect(() => {
  329. // router.events.on('routeChangeComplete', onRouterChangeComplete);
  330. // return () => {
  331. // router.events.off('routeChangeComplete', onRouterChangeComplete);
  332. // };
  333. // }, [onRouterChangeComplete, router.events]);
  334. if (!isEditable) {
  335. return <></>;
  336. }
  337. if (rendererOptions == null) {
  338. return <></>;
  339. }
  340. return (
  341. <div data-testid="page-editor" id="page-editor" className={`flex-expand-vert ${props.visibility ? '' : 'd-none'}`}>
  342. <div className="px-4 py-2">
  343. <PageHeader />
  344. </div>
  345. <div className={`flex-expand-horiz ${props.visibility ? '' : 'd-none'}`}>
  346. <div className="page-editor-editor-container flex-expand-vert">
  347. {/* <Editor
  348. ref={editorRef}
  349. value={initialValue}
  350. isUploadable={isUploadable}
  351. isUploadAllFileAllowed={isUploadAllFileAllowed}
  352. indentSize={currentIndentSize}
  353. onScroll={editorScrolledHandler}
  354. onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
  355. onChange={markdownChangedHandler}
  356. onUpload={uploadHandler}
  357. onSave={saveWithShortcut}
  358. /> */}
  359. <CodeMirrorEditorMain
  360. onChange={markdownChangedHandler}
  361. onSave={saveWithShortcut}
  362. onUpload={uploadHandler}
  363. acceptedUploadFileType={acceptedUploadFileType}
  364. onScroll={scrollEditorHandlerThrottle}
  365. indentSize={currentIndentSize ?? defaultIndentSize}
  366. userName={user?.name}
  367. pageId={pageId ?? undefined}
  368. initialValue={initialValue}
  369. onOpenEditor={markdown => setMarkdownToPreview(markdown)}
  370. editorTheme={editorSettings?.theme}
  371. editorKeymap={editorSettings?.keymapMode}
  372. />
  373. </div>
  374. <div ref={previewRef} onScroll={scrollPreviewHandlerThrottle} className="page-editor-preview-container flex-expand-vert d-none d-lg-flex">
  375. <Preview
  376. rendererOptions={rendererOptions}
  377. markdown={markdownToPreview}
  378. pagePath={currentPagePath}
  379. expandContentWidth={shouldExpandContent}
  380. // TODO: Dynamic changes by height or resizing the last element
  381. pastEnd={500}
  382. />
  383. </div>
  384. {/*
  385. <ConflictDiffModal
  386. isOpen={conflictDiffModalStatus?.isOpened}
  387. onClose={() => closeConflictDiffModal()}
  388. markdownOnEdit={markdownToPreview}
  389. optionsToSave={optionsToSave}
  390. afterResolvedHandler={afterResolvedHandler}
  391. />
  392. */}
  393. </div>
  394. <EditorNavbarBottom />
  395. </div>
  396. );
  397. });
  398. PageEditor.displayName = 'PageEditor';