PageEditor.tsx 15 KB

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