PageEditor.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. useDefaultIndentSize, useCurrentUser,
  24. useCurrentPathname, useIsEnabledAttachTitleHeader,
  25. useIsEditable, useIsIndentSizeForced,
  26. useAcceptedUploadFileType,
  27. } from '~/stores-universal/context';
  28. import { EditorMode, useEditorMode } from '~/stores-universal/ui';
  29. import { useNextThemes } from '~/stores-universal/use-next-themes';
  30. import {
  31. useEditorSettings,
  32. useCurrentIndentSize,
  33. useEditingMarkdown,
  34. useWaitingSaveProcessing,
  35. } from '~/stores/editor';
  36. import {
  37. useCurrentPagePath, useSWRxCurrentPage, useCurrentPageId, useIsNotFound, useTemplateBodyData, useSWRxCurrentGrantData,
  38. } from '~/stores/page';
  39. import { mutatePageTree } from '~/stores/page-listing';
  40. import { usePreviewOptions } from '~/stores/renderer';
  41. import { useIsUntitledPage, useSelectedGrant } from '~/stores/ui';
  42. import { useEditingUsers } from '~/stores/use-editing-users';
  43. import { useCurrentPageYjsData } from '~/stores/yjs';
  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 { data: currentPageYjsData } = useCurrentPageYjsData();
  96. const { onEditorsUpdated } = useEditingUsers();
  97. const onConflict = useConflictResolver();
  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. const handler = (lineNumber?: number) => {
  250. if (currentPageYjsData?.hasRevisionBodyDiff) {
  251. return;
  252. }
  253. codeMirrorEditor?.setCaretLine(lineNumber);
  254. };
  255. globalEmitter.on('setCaretLine', handler);
  256. if (globalEmitter.listenerCount('getCaretLine') >= 1 && codeMirrorEditor?.view != null) {
  257. globalEmitter.emit('getCaretLine', handler);
  258. globalEmitter.removeAllListeners('getCaretLine');
  259. }
  260. return function cleanup() {
  261. globalEmitter.removeListener('setCaretLine', handler);
  262. };
  263. }, [codeMirrorEditor, codeMirrorEditor?.view]);
  264. // TODO: Check the reproduction conditions that made this code necessary and confirm reproduction
  265. // // when transitioning to a different page, if the initialValue is the same,
  266. // // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  267. // const onRouterChangeComplete = useCallback(() => {
  268. // codeMirrorEditor?.initDoc(ydoc?.getText('codemirror').toString());
  269. // codeMirrorEditor?.setCaretLine();
  270. // }, [codeMirrorEditor, ydoc]);
  271. // useEffect(() => {
  272. // router.events.on('routeChangeComplete', onRouterChangeComplete);
  273. // return () => {
  274. // router.events.off('routeChangeComplete', onRouterChangeComplete);
  275. // };
  276. // }, [onRouterChangeComplete, router.events]);
  277. const pastEndStyle: CSSProperties | undefined = useMemo(() => {
  278. if (previewRect == null) {
  279. return undefined;
  280. }
  281. const previewRectHeight = previewRect.height;
  282. // containerHeight - 1.5 line height
  283. return { paddingBottom: `calc(${previewRectHeight}px - 2em)` };
  284. }, [previewRect]);
  285. if (!isEditable) {
  286. return <></>;
  287. }
  288. if (rendererOptions == null) {
  289. return <></>;
  290. }
  291. return (
  292. <div data-testid="page-editor" id="page-editor" className={`flex-expand-vert ${props.visibility ? '' : 'd-none'}`}>
  293. <EditorNavbar />
  294. <div className={`flex-expand-horiz ${props.visibility ? '' : 'd-none'}`}>
  295. <div className="page-editor-editor-container flex-expand-vert border-end">
  296. <CodeMirrorEditorMain
  297. isEditorMode={editorMode === EditorMode.Editor}
  298. onChange={markdownChangedHandler}
  299. onSave={saveWithShortcut}
  300. onUpload={uploadHandler}
  301. acceptedUploadFileType={acceptedUploadFileType}
  302. onScroll={scrollEditorHandlerThrottle}
  303. indentSize={currentIndentSize ?? defaultIndentSize}
  304. user={user ?? undefined}
  305. pageId={pageId ?? undefined}
  306. initialValue={initialValue}
  307. editorSettings={editorSettings}
  308. onEditorsUpdated={onEditorsUpdated}
  309. />
  310. </div>
  311. <div
  312. ref={previewRef}
  313. onScroll={scrollPreviewHandlerThrottle}
  314. className="page-editor-preview-container flex-expand-vert overflow-y-auto d-none d-lg-flex"
  315. >
  316. <Preview
  317. rendererOptions={rendererOptions}
  318. markdown={markdownToPreview}
  319. pagePath={currentPagePath}
  320. expandContentWidth={shouldExpandContent}
  321. style={pastEndStyle}
  322. />
  323. </div>
  324. </div>
  325. <EditorNavbarBottom />
  326. </div>
  327. );
  328. });
  329. PageEditor.displayName = 'PageEditor';