PageEditor.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 {
  11. CodeMirrorEditorMain,
  12. useCodeMirrorEditorIsolated, useResolvedThemeForEditor,
  13. } from '@growi/editor/dist/client';
  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 { useShouldExpandContent } from '~/client/services/layout';
  19. import { useUpdateStateAfterSave } from '~/client/services/page-operation';
  20. import { updatePage, extractRemoteRevisionDataFromErrorObj } from '~/client/services/update-page';
  21. import { uploadAttachments } from '~/client/services/upload-attachments';
  22. import { toastError, toastSuccess, toastWarning } from '~/client/util/toastr';
  23. import {
  24. useDefaultIndentSize, useCurrentUser,
  25. useCurrentPathname, useIsEnabledAttachTitleHeader,
  26. useIsEditable, useIsIndentSizeForced,
  27. useAcceptedUploadFileType,
  28. } from '~/stores/context';
  29. import {
  30. useEditorSettings,
  31. useCurrentIndentSize,
  32. useEditingMarkdown,
  33. useWaitingSaveProcessing,
  34. } from '~/stores/editor';
  35. import {
  36. useCurrentPagePath, useSWRxCurrentPage, useCurrentPageId, useIsNotFound, useTemplateBodyData, useSWRxCurrentGrantData,
  37. } from '~/stores/page';
  38. import { mutatePageTree } from '~/stores/page-listing';
  39. import { usePreviewOptions } from '~/stores/renderer';
  40. import {
  41. EditorMode,
  42. useEditorMode, useIsUntitledPage, useSelectedGrant,
  43. } from '~/stores/ui';
  44. import { useEditingUsers } from '~/stores/use-editing-users';
  45. import { useNextThemes } from '~/stores/use-next-themes';
  46. import loggerFactory from '~/utils/logger';
  47. import { EditorNavbar } from './EditorNavbar';
  48. import EditorNavbarBottom from './EditorNavbarBottom';
  49. import Preview from './Preview';
  50. import { useScrollSync } from './ScrollSyncHelper';
  51. import { useConflictResolver, useConflictEffect, type ConflictHandler } from './conflict';
  52. import '@growi/editor/dist/style.css';
  53. const logger = loggerFactory('growi:PageEditor');
  54. declare global {
  55. // eslint-disable-next-line vars-on-top, no-var
  56. var globalEmitter: EventEmitter;
  57. }
  58. export type SaveOptions = {
  59. wip: boolean,
  60. slackChannels: string,
  61. isSlackEnabled: boolean,
  62. overwriteScopesOfDescendants?: boolean
  63. }
  64. export type Save = (
  65. revisionId?: string,
  66. requestMarkdown?: string,
  67. opts?: SaveOptions,
  68. onConflict?: ConflictHandler
  69. ) => Promise<IPageHasId | null>
  70. type Props = {
  71. visibility?: boolean,
  72. }
  73. export const PageEditor = React.memo((props: Props): JSX.Element => {
  74. const { t } = useTranslation();
  75. const previewRef = useRef<HTMLDivElement>(null);
  76. const [previewRect] = useRect(previewRef);
  77. const { data: isNotFound } = useIsNotFound();
  78. const { data: pageId } = useCurrentPageId();
  79. const { data: currentPagePath } = useCurrentPagePath();
  80. const { data: currentPathname } = useCurrentPathname();
  81. const { data: currentPage } = useSWRxCurrentPage();
  82. const { data: selectedGrant } = useSelectedGrant();
  83. const { data: editingMarkdown } = useEditingMarkdown();
  84. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  85. const { data: templateBodyData } = useTemplateBodyData();
  86. const { data: isEditable } = useIsEditable();
  87. const { mutate: mutateWaitingSaveProcessing } = useWaitingSaveProcessing();
  88. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  89. const { data: isUntitledPage } = useIsUntitledPage();
  90. const { data: isIndentSizeForced } = useIsIndentSizeForced();
  91. const { data: currentIndentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  92. const { data: defaultIndentSize } = useDefaultIndentSize();
  93. const { data: acceptedUploadFileType } = useAcceptedUploadFileType();
  94. const { data: editorSettings } = useEditorSettings();
  95. const { mutate: mutateIsGrantNormalized } = useSWRxCurrentGrantData(currentPage?._id);
  96. const { data: user } = useCurrentUser();
  97. const { onEditorsUpdated } = useEditingUsers();
  98. const onConflict = useConflictResolver();
  99. const { data: rendererOptions } = usePreviewOptions();
  100. const { mutate: mutateResolvedTheme } = useResolvedThemeForEditor();
  101. const shouldExpandContent = useShouldExpandContent(currentPage);
  102. const updateStateAfterSave = useUpdateStateAfterSave(pageId, { supressEditingMarkdownMutation: true });
  103. useConflictEffect();
  104. const { resolvedTheme } = useNextThemes();
  105. mutateResolvedTheme({ themeData: resolvedTheme });
  106. const currentRevisionId = currentPage?.revision?._id;
  107. const isRevisionIdRequiredForPageUpdate = currentPage?.revision?.origin === undefined;
  108. const initialValueRef = useRef('');
  109. const initialValue = useMemo(() => {
  110. if (!isNotFound) {
  111. return editingMarkdown ?? '';
  112. }
  113. let initialValue = '';
  114. if (isEnabledAttachTitleHeader && currentPathname != null) {
  115. const pageTitle = nodePath.basename(currentPathname);
  116. initialValue += `${pathUtils.attachTitleHeader(pageTitle)}\n`;
  117. }
  118. if (templateBodyData != null) {
  119. initialValue += `${templateBodyData}\n`;
  120. }
  121. return initialValue;
  122. }, [isNotFound, currentPathname, editingMarkdown, isEnabledAttachTitleHeader, templateBodyData]);
  123. useEffect(() => {
  124. // set to ref
  125. initialValueRef.current = initialValue;
  126. }, [initialValue]);
  127. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  128. const [markdownToPreview, setMarkdownToPreview] = useState<string>(codeMirrorEditor?.getDoc() ?? '');
  129. const setMarkdownPreviewWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string) => {
  130. setMarkdownToPreview(value);
  131. })), []);
  132. const markdownChangedHandler = useCallback((value: string) => {
  133. setMarkdownPreviewWithDebounce(value);
  134. }, [setMarkdownPreviewWithDebounce]);
  135. const { scrollEditorHandler, scrollPreviewHandler } = useScrollSync(GlobalCodeMirrorEditorKey.MAIN, previewRef);
  136. const scrollEditorHandlerThrottle = useMemo(() => throttle(25, scrollEditorHandler), [scrollEditorHandler]);
  137. const scrollPreviewHandlerThrottle = useMemo(() => throttle(25, scrollPreviewHandler), [scrollPreviewHandler]);
  138. const save: Save = useCallback(async(revisionId, markdown, opts, onConflict) => {
  139. if (pageId == null || selectedGrant == null) {
  140. logger.error('Some materials to save are invalid', {
  141. pageId, selectedGrant,
  142. });
  143. throw new Error('Some materials to save are invalid');
  144. }
  145. try {
  146. mutateWaitingSaveProcessing(true);
  147. const { page } = await updatePage({
  148. pageId,
  149. revisionId,
  150. wip: opts?.wip,
  151. body: markdown ?? '',
  152. grant: selectedGrant?.grant,
  153. origin: Origin.Editor,
  154. userRelatedGrantUserGroupIds: selectedGrant?.userRelatedGrantedGroups,
  155. ...(opts ?? {}),
  156. });
  157. // to sync revision id with page tree: https://github.com/weseek/growi/pull/7227
  158. mutatePageTree();
  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, t, mutateIsGrantNormalized]);
  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. // set handler to save and return to View
  221. useEffect(() => {
  222. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  223. return function cleanup() {
  224. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  225. };
  226. }, [saveAndReturnToViewHandler]);
  227. // set handler to focus
  228. useLayoutEffect(() => {
  229. if (editorMode === EditorMode.Editor && isUntitledPage === false) {
  230. codeMirrorEditor?.focus();
  231. }
  232. }, [codeMirrorEditor, editorMode, isUntitledPage]);
  233. // Detect indent size from contents (only when users are allowed to change it)
  234. useEffect(() => {
  235. // do nothing if the indent size fixed
  236. if (isIndentSizeForced == null || isIndentSizeForced) {
  237. mutateCurrentIndentSize(undefined);
  238. return;
  239. }
  240. // detect from markdown
  241. if (initialValue != null) {
  242. const detectedIndent = detectIndent(initialValue);
  243. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  244. mutateCurrentIndentSize(detectedIndent.amount);
  245. }
  246. }
  247. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  248. // set handler to set caret line
  249. useEffect(() => {
  250. const handler = (lineNumber?: number) => {
  251. codeMirrorEditor?.setCaretLineInit(lineNumber);
  252. };
  253. globalEmitter.on('setCaretLine', handler);
  254. if (globalEmitter.listenerCount('getCaretLine') >= 1 && codeMirrorEditor?.view != null) {
  255. globalEmitter.emit('getCaretLine', handler);
  256. globalEmitter.removeAllListeners('getCaretLine');
  257. }
  258. return function cleanup() {
  259. globalEmitter.removeListener('setCaretLine', handler);
  260. };
  261. }, [codeMirrorEditor, codeMirrorEditor?.view]);
  262. // TODO: Check the reproduction conditions that made this code necessary and confirm reproduction
  263. // // when transitioning to a different page, if the initialValue is the same,
  264. // // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  265. // const onRouterChangeComplete = useCallback(() => {
  266. // codeMirrorEditor?.initDoc(ydoc?.getText('codemirror').toString());
  267. // codeMirrorEditor?.setCaretLine();
  268. // }, [codeMirrorEditor, ydoc]);
  269. // useEffect(() => {
  270. // router.events.on('routeChangeComplete', onRouterChangeComplete);
  271. // return () => {
  272. // router.events.off('routeChangeComplete', onRouterChangeComplete);
  273. // };
  274. // }, [onRouterChangeComplete, router.events]);
  275. const pastEndStyle: CSSProperties | undefined = useMemo(() => {
  276. if (previewRect == null) {
  277. return undefined;
  278. }
  279. const previewRectHeight = previewRect.height;
  280. // containerHeight - 1.5 line height
  281. return { paddingBottom: `calc(${previewRectHeight}px - 2em)` };
  282. }, [previewRect]);
  283. if (!isEditable) {
  284. return <></>;
  285. }
  286. if (rendererOptions == null) {
  287. return <></>;
  288. }
  289. return (
  290. <div data-testid="page-editor" id="page-editor" className={`flex-expand-vert ${props.visibility ? '' : 'd-none'}`}>
  291. <EditorNavbar />
  292. <div className={`flex-expand-horiz ${props.visibility ? '' : 'd-none'}`}>
  293. <div className="page-editor-editor-container flex-expand-vert border-end">
  294. <CodeMirrorEditorMain
  295. isEditorMode={editorMode === EditorMode.Editor}
  296. onChange={markdownChangedHandler}
  297. onSave={saveWithShortcut}
  298. onUpload={uploadHandler}
  299. acceptedUploadFileType={acceptedUploadFileType}
  300. onScroll={scrollEditorHandlerThrottle}
  301. indentSize={currentIndentSize ?? defaultIndentSize}
  302. user={user ?? undefined}
  303. pageId={pageId ?? undefined}
  304. initialValue={initialValue}
  305. editorSettings={editorSettings}
  306. onEditorsUpdated={onEditorsUpdated}
  307. />
  308. </div>
  309. <div
  310. ref={previewRef}
  311. onScroll={scrollPreviewHandlerThrottle}
  312. className="page-editor-preview-container flex-expand-vert overflow-y-auto d-none d-lg-flex"
  313. >
  314. <Preview
  315. rendererOptions={rendererOptions}
  316. markdown={markdownToPreview}
  317. pagePath={currentPagePath}
  318. expandContentWidth={shouldExpandContent}
  319. style={pastEndStyle}
  320. />
  321. </div>
  322. </div>
  323. <EditorNavbarBottom />
  324. </div>
  325. );
  326. });
  327. PageEditor.displayName = 'PageEditor';