PageEditor.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import type { CSSProperties, JSX } 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 { Origin } from '@growi/core';
  8. import type { IPageHasId } from '@growi/core/dist/interfaces';
  9. import { pathUtils } from '@growi/core/dist/utils';
  10. import { GlobalCodeMirrorEditorKey } from '@growi/editor';
  11. import { CodeMirrorEditorMain } from '@growi/editor/dist/client/components/CodeMirrorEditorMain';
  12. import { useCodeMirrorEditorIsolated } from '@growi/editor/dist/client/stores/codemirror-editor';
  13. import { useResolvedThemeForEditor } from '@growi/editor/dist/client/stores/use-resolved-theme';
  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 { useUpdateStateAfterSave } from '~/client/services/page-operation';
  19. import { useUpdatePage, extractRemoteRevisionDataFromErrorObj } from '~/client/services/update-page';
  20. import { uploadAttachments } from '~/client/services/upload-attachments';
  21. import { toastError, toastSuccess, toastWarning } from '~/client/util/toastr';
  22. import { useShouldExpandContent } from '~/services/layout/use-should-expand-content';
  23. import {
  24. useDefaultIndentSize, useCurrentUser,
  25. useCurrentPathname, useIsEnabledAttachTitleHeader,
  26. useIsEditable, useIsIndentSizeForced,
  27. useAcceptedUploadFileType, useIsEnableUnifiedMergeView,
  28. } from '~/stores-universal/context';
  29. import { EditorMode, useEditorMode } from '~/stores-universal/ui';
  30. import { useNextThemes } from '~/stores-universal/use-next-themes';
  31. import {
  32. useReservedNextCaretLine,
  33. useEditorSettings,
  34. useCurrentIndentSize,
  35. useEditingMarkdown,
  36. useWaitingSaveProcessing,
  37. } from '~/stores/editor';
  38. import {
  39. useCurrentPagePath, useSWRxCurrentPage, useCurrentPageId, useIsNotFound, useTemplateBodyData, useSWRxCurrentGrantData,
  40. } from '~/stores/page';
  41. import { mutatePageTree, mutateRecentlyUpdated } from '~/stores/page-listing';
  42. import { usePreviewOptions } from '~/stores/renderer';
  43. import { useIsUntitledPage, useSelectedGrant } from '~/stores/ui';
  44. import { useEditingClients } from '~/stores/use-editing-clients';
  45. import loggerFactory from '~/utils/logger';
  46. import { EditorNavbar } from './EditorNavbar';
  47. import { EditorNavbarBottom } from './EditorNavbarBottom';
  48. import Preview from './Preview';
  49. import { useScrollSync } from './ScrollSyncHelper';
  50. import { useConflictResolver, useConflictEffect, type ConflictHandler } from './conflict';
  51. import '@growi/editor/dist/style.css';
  52. const logger = loggerFactory('growi:PageEditor');
  53. declare global {
  54. // eslint-disable-next-line vars-on-top, no-var
  55. var globalEmitter: EventEmitter;
  56. }
  57. export type SaveOptions = {
  58. wip: boolean,
  59. slackChannels: string,
  60. isSlackEnabled: boolean,
  61. overwriteScopesOfDescendants?: boolean
  62. }
  63. export type Save = (
  64. revisionId?: string,
  65. requestMarkdown?: string,
  66. opts?: SaveOptions,
  67. onConflict?: ConflictHandler
  68. ) => Promise<IPageHasId | null>
  69. type Props = {
  70. visibility?: boolean,
  71. }
  72. export const PageEditorSubstance = (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 { data: selectedGrant } = useSelectedGrant();
  82. const { data: editingMarkdown } = useEditingMarkdown();
  83. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  84. const { data: templateBodyData } = useTemplateBodyData();
  85. const { data: isEditable } = useIsEditable();
  86. const { mutate: mutateWaitingSaveProcessing } = useWaitingSaveProcessing();
  87. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  88. const { data: isUntitledPage } = useIsUntitledPage();
  89. const { data: isIndentSizeForced } = useIsIndentSizeForced();
  90. const { data: currentIndentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  91. const { data: defaultIndentSize } = useDefaultIndentSize();
  92. const { data: acceptedUploadFileType } = useAcceptedUploadFileType();
  93. const { data: editorSettings } = useEditorSettings();
  94. const { mutate: mutateIsGrantNormalized } = useSWRxCurrentGrantData(currentPage?._id);
  95. const { data: user } = useCurrentUser();
  96. const { mutate: mutateEditingUsers } = useEditingClients();
  97. const onConflict = useConflictResolver();
  98. const { data: reservedNextCaretLine, mutate: mutateReservedNextCaretLine } = useReservedNextCaretLine();
  99. const { data: isEnableUnifiedMergeView } = useIsEnableUnifiedMergeView();
  100. const { data: rendererOptions } = usePreviewOptions();
  101. const { mutate: mutateResolvedTheme } = useResolvedThemeForEditor();
  102. const shouldExpandContent = useShouldExpandContent(currentPage);
  103. const updatePage = useUpdatePage();
  104. const updateStateAfterSave = useUpdateStateAfterSave(pageId, { supressEditingMarkdownMutation: true });
  105. useConflictEffect();
  106. const { resolvedTheme } = useNextThemes();
  107. mutateResolvedTheme({ themeData: resolvedTheme });
  108. const currentRevisionId = currentPage?.revision?._id;
  109. const isRevisionIdRequiredForPageUpdate = currentPage?.revision?.origin === undefined;
  110. const initialValueRef = useRef('');
  111. const initialValue = useMemo(() => {
  112. if (!isNotFound) {
  113. return editingMarkdown ?? '';
  114. }
  115. let initialValue = '';
  116. if (isEnabledAttachTitleHeader && currentPathname != null) {
  117. const pageTitle = nodePath.basename(currentPathname);
  118. initialValue += `${pathUtils.attachTitleHeader(pageTitle)}\n`;
  119. }
  120. if (templateBodyData != null) {
  121. initialValue += `${templateBodyData}\n`;
  122. }
  123. return initialValue;
  124. }, [isNotFound, currentPathname, editingMarkdown, isEnabledAttachTitleHeader, templateBodyData]);
  125. useEffect(() => {
  126. // set to ref
  127. initialValueRef.current = initialValue;
  128. }, [initialValue]);
  129. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  130. const [markdownToPreview, setMarkdownToPreview] = useState<string>(codeMirrorEditor?.getDoc() ?? '');
  131. const setMarkdownPreviewWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string) => {
  132. setMarkdownToPreview(value);
  133. })), []);
  134. const { scrollEditorHandler, scrollPreviewHandler } = useScrollSync(GlobalCodeMirrorEditorKey.MAIN, previewRef);
  135. const scrollEditorHandlerThrottle = useMemo(() => throttle(25, scrollEditorHandler), [scrollEditorHandler]);
  136. const scrollPreviewHandlerThrottle = useMemo(() => throttle(25, scrollPreviewHandler), [scrollPreviewHandler]);
  137. const save: Save = useCallback(async(revisionId, markdown, opts, onConflict) => {
  138. if (pageId == null || selectedGrant == null) {
  139. logger.error('Some materials to save are invalid', {
  140. pageId, selectedGrant,
  141. });
  142. throw new Error('Some materials to save are invalid');
  143. }
  144. try {
  145. mutateWaitingSaveProcessing(true);
  146. const { page } = await updatePage({
  147. pageId,
  148. revisionId,
  149. wip: opts?.wip,
  150. body: markdown ?? '',
  151. grant: selectedGrant?.grant,
  152. origin: Origin.Editor,
  153. userRelatedGrantUserGroupIds: selectedGrant?.userRelatedGrantedGroups,
  154. ...(opts ?? {}),
  155. });
  156. // to sync revision id with page tree: https://github.com/weseek/growi/pull/7227
  157. mutatePageTree();
  158. mutateRecentlyUpdated();
  159. // sync current grant data after update
  160. mutateIsGrantNormalized();
  161. return page;
  162. }
  163. catch (error) {
  164. logger.error('failed to save', error);
  165. const remoteRevisionData = extractRemoteRevisionDataFromErrorObj(error);
  166. if (remoteRevisionData != null) {
  167. onConflict?.(remoteRevisionData, markdown ?? '', save, opts);
  168. toastWarning(t('modal_resolve_conflict.conflicts_with_new_body_on_server_side'));
  169. return null;
  170. }
  171. toastError(error);
  172. return null;
  173. }
  174. finally {
  175. mutateWaitingSaveProcessing(false);
  176. }
  177. }, [pageId, selectedGrant, mutateWaitingSaveProcessing, updatePage, mutateIsGrantNormalized, t]);
  178. const saveAndReturnToViewHandler = useCallback(async(opts: SaveOptions) => {
  179. const markdown = codeMirrorEditor?.getDoc();
  180. const revisionId = isRevisionIdRequiredForPageUpdate ? currentRevisionId : undefined;
  181. const page = await save(revisionId, markdown, opts, onConflict);
  182. if (page == null) {
  183. return;
  184. }
  185. mutateEditorMode(EditorMode.View);
  186. updateStateAfterSave?.();
  187. }, [codeMirrorEditor, currentRevisionId, isRevisionIdRequiredForPageUpdate, mutateEditorMode, onConflict, save, updateStateAfterSave]);
  188. const saveWithShortcut = useCallback(async() => {
  189. const markdown = codeMirrorEditor?.getDoc();
  190. const revisionId = isRevisionIdRequiredForPageUpdate ? currentRevisionId : undefined;
  191. const page = await save(revisionId, markdown, undefined, onConflict);
  192. if (page == null) {
  193. return;
  194. }
  195. toastSuccess(t('toaster.save_succeeded'));
  196. updateStateAfterSave?.();
  197. }, [codeMirrorEditor, currentRevisionId, isRevisionIdRequiredForPageUpdate, onConflict, save, t, updateStateAfterSave]);
  198. // the upload event handler
  199. const uploadHandler = useCallback((files: File[]) => {
  200. if (pageId == null) {
  201. logger.error('pageId is invalid', {
  202. pageId,
  203. });
  204. throw new Error('pageId is invalid');
  205. }
  206. uploadAttachments(pageId, files, {
  207. onUploaded: (attachment) => {
  208. const fileName = attachment.originalName;
  209. const prefix = attachment.fileFormat.startsWith('image/')
  210. ? '!' // use "![fileName](url)" syntax when image
  211. : '';
  212. const insertText = `${prefix}[${fileName}](${attachment.filePathProxied})\n`;
  213. codeMirrorEditor?.insertText(insertText);
  214. },
  215. onError: (error) => {
  216. toastError(error);
  217. },
  218. });
  219. }, [codeMirrorEditor, pageId]);
  220. const cmProps = useMemo(() => ({
  221. onChange: (value: string) => {
  222. setMarkdownPreviewWithDebounce(value);
  223. },
  224. }), [setMarkdownPreviewWithDebounce]);
  225. // set handler to save and return to View
  226. useEffect(() => {
  227. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  228. return function cleanup() {
  229. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  230. };
  231. }, [saveAndReturnToViewHandler]);
  232. // set handler to focus
  233. useLayoutEffect(() => {
  234. if (editorMode === EditorMode.Editor && isUntitledPage === false) {
  235. codeMirrorEditor?.focus();
  236. }
  237. }, [codeMirrorEditor, editorMode, isUntitledPage]);
  238. // Detect indent size from contents (only when users are allowed to change it)
  239. useEffect(() => {
  240. // do nothing if the indent size fixed
  241. if (isIndentSizeForced == null || isIndentSizeForced) {
  242. mutateCurrentIndentSize(undefined);
  243. return;
  244. }
  245. // detect from markdown
  246. if (initialValue != null) {
  247. const detectedIndent = detectIndent(initialValue);
  248. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  249. mutateCurrentIndentSize(detectedIndent.amount);
  250. }
  251. }
  252. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  253. // set caret line if the edit button next to Header is clicked.
  254. useEffect(() => {
  255. if (codeMirrorEditor?.setCaretLine == null) {
  256. return;
  257. }
  258. if (editorMode === EditorMode.Editor) {
  259. codeMirrorEditor.setCaretLine(reservedNextCaretLine ?? 0, true);
  260. }
  261. }, [codeMirrorEditor, editorMode, reservedNextCaretLine]);
  262. // reset caret line if returning to the View.
  263. useEffect(() => {
  264. if (editorMode === EditorMode.View) {
  265. mutateReservedNextCaretLine(0);
  266. }
  267. }, [editorMode, mutateReservedNextCaretLine]);
  268. // TODO: Check the reproduction conditions that made this code necessary and confirm reproduction
  269. // // when transitioning to a different page, if the initialValue is the same,
  270. // // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  271. // const onRouterChangeComplete = useCallback(() => {
  272. // codeMirrorEditor?.initDoc(ydoc?.getText('codemirror').toString());
  273. // codeMirrorEditor?.setCaretLine();
  274. // }, [codeMirrorEditor, ydoc]);
  275. // useEffect(() => {
  276. // router.events.on('routeChangeComplete', onRouterChangeComplete);
  277. // return () => {
  278. // router.events.off('routeChangeComplete', onRouterChangeComplete);
  279. // };
  280. // }, [onRouterChangeComplete, router.events]);
  281. const pastEndStyle: CSSProperties | undefined = useMemo(() => {
  282. if (previewRect == null) {
  283. return undefined;
  284. }
  285. const previewRectHeight = previewRect.height;
  286. // containerHeight - 1.5 line height
  287. return { paddingBottom: `calc(${previewRectHeight}px - 2em)` };
  288. }, [previewRect]);
  289. if (!isEditable) {
  290. return <></>;
  291. }
  292. if (rendererOptions == null) {
  293. return <></>;
  294. }
  295. return (
  296. <div className={`flex-expand-horiz ${props.visibility ? '' : 'd-none'}`}>
  297. <div className="page-editor-editor-container flex-expand-vert border-end">
  298. <CodeMirrorEditorMain
  299. enableUnifiedMergeView={isEnableUnifiedMergeView}
  300. enableCollaboration={editorMode === EditorMode.Editor}
  301. onSave={saveWithShortcut}
  302. onUpload={uploadHandler}
  303. acceptedUploadFileType={acceptedUploadFileType}
  304. onScroll={scrollEditorHandlerThrottle}
  305. indentSize={currentIndentSize ?? defaultIndentSize}
  306. user={user ?? undefined}
  307. pageId={pageId ?? undefined}
  308. editorSettings={editorSettings}
  309. onEditorsUpdated={mutateEditingUsers}
  310. cmProps={cmProps}
  311. />
  312. </div>
  313. <div
  314. ref={previewRef}
  315. onScroll={scrollPreviewHandlerThrottle}
  316. className="page-editor-preview-container flex-expand-vert overflow-y-auto d-none d-lg-flex"
  317. >
  318. <Preview
  319. rendererOptions={rendererOptions}
  320. markdown={markdownToPreview}
  321. pagePath={currentPagePath}
  322. expandContentWidth={shouldExpandContent}
  323. style={pastEndStyle}
  324. />
  325. </div>
  326. </div>
  327. );
  328. };
  329. export const PageEditor = React.memo((props: Props): JSX.Element => {
  330. return (
  331. <div data-testid="page-editor" id="page-editor" className={`flex-expand-vert ${props.visibility ? '' : 'd-none'}`}>
  332. <EditorNavbar />
  333. <PageEditorSubstance visibility={props.visibility} />
  334. <EditorNavbarBottom />
  335. </div>
  336. );
  337. });
  338. PageEditor.displayName = 'PageEditor';