PageEditor.tsx 19 KB

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