PageEditor.tsx 14 KB

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