PageEditor.tsx 15 KB

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