PageEditor.tsx 13 KB

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