PageEditor.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. 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: isIndentSizeForced } = useIsIndentSizeForced();
  88. const { data: currentIndentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  89. const { data: defaultIndentSize } = useDefaultIndentSize();
  90. const { data: acceptedUploadFileType } = useAcceptedUploadFileType();
  91. const { data: editorSettings } = useEditorSettings();
  92. const { mutate: mutateIsGrantNormalized } = useSWRxCurrentGrantData(currentPage?._id);
  93. const { data: user } = useCurrentUser();
  94. const { onEditorsUpdated } = useEditingUsers();
  95. const onConflict = useConflictResolver();
  96. const { data: rendererOptions } = usePreviewOptions();
  97. const { mutate: mutateResolvedTheme } = useResolvedThemeForEditor();
  98. const shouldExpandContent = useShouldExpandContent(currentPage);
  99. const updateStateAfterSave = useUpdateStateAfterSave(pageId, { supressEditingMarkdownMutation: true });
  100. useConflictEffect();
  101. const { resolvedTheme } = useNextThemes();
  102. mutateResolvedTheme({ themeData: resolvedTheme });
  103. const currentRevisionId = currentPage?.revision?._id;
  104. const isRevisionIdRequiredForPageUpdate = currentPage?.revision?.origin === undefined;
  105. const initialValueRef = useRef('');
  106. const initialValue = useMemo(() => {
  107. if (!isNotFound) {
  108. return editingMarkdown ?? '';
  109. }
  110. let initialValue = '';
  111. if (isEnabledAttachTitleHeader && currentPathname != null) {
  112. const pageTitle = nodePath.basename(currentPathname);
  113. initialValue += `${pathUtils.attachTitleHeader(pageTitle)}\n`;
  114. }
  115. if (templateBodyData != null) {
  116. initialValue += `${templateBodyData}\n`;
  117. }
  118. return initialValue;
  119. }, [isNotFound, currentPathname, editingMarkdown, isEnabledAttachTitleHeader, templateBodyData]);
  120. useEffect(() => {
  121. // set to ref
  122. initialValueRef.current = initialValue;
  123. }, [initialValue]);
  124. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  125. const [markdownToPreview, setMarkdownToPreview] = useState<string>(codeMirrorEditor?.getDoc() ?? '');
  126. const setMarkdownPreviewWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string) => {
  127. setMarkdownToPreview(value);
  128. })), []);
  129. const markdownChangedHandler = useCallback((value: string) => {
  130. setMarkdownPreviewWithDebounce(value);
  131. }, [setMarkdownPreviewWithDebounce]);
  132. const { scrollEditorHandler, scrollPreviewHandler } = useScrollSync(GlobalCodeMirrorEditorKey.MAIN, previewRef);
  133. const scrollEditorHandlerThrottle = useMemo(() => throttle(25, scrollEditorHandler), [scrollEditorHandler]);
  134. const scrollPreviewHandlerThrottle = useMemo(() => throttle(25, scrollPreviewHandler), [scrollPreviewHandler]);
  135. const save: Save = useCallback(async(revisionId, markdown, opts, onConflict) => {
  136. if (pageId == null || selectedGrant == null) {
  137. logger.error('Some materials to save are invalid', {
  138. pageId, selectedGrant,
  139. });
  140. throw new Error('Some materials to save are invalid');
  141. }
  142. try {
  143. mutateWaitingSaveProcessing(true);
  144. const { page } = await updatePage({
  145. pageId,
  146. revisionId,
  147. wip: opts?.wip,
  148. body: markdown ?? '',
  149. grant: selectedGrant?.grant,
  150. origin: Origin.Editor,
  151. userRelatedGrantUserGroupIds: selectedGrant?.userRelatedGrantedGroups,
  152. ...(opts ?? {}),
  153. });
  154. // to sync revision id with page tree: https://github.com/weseek/growi/pull/7227
  155. mutatePageTree();
  156. // sync current grant data after update
  157. mutateIsGrantNormalized();
  158. return page;
  159. }
  160. catch (error) {
  161. logger.error('failed to save', error);
  162. const remoteRevisionData = extractRemoteRevisionDataFromErrorObj(error);
  163. if (remoteRevisionData != null) {
  164. onConflict?.(remoteRevisionData, markdown ?? '', save, opts);
  165. toastWarning(t('modal_resolve_conflict.conflicts_with_new_body_on_server_side'));
  166. return null;
  167. }
  168. toastError(error);
  169. return null;
  170. }
  171. finally {
  172. mutateWaitingSaveProcessing(false);
  173. }
  174. }, [pageId, selectedGrant, mutateWaitingSaveProcessing, t, mutateIsGrantNormalized]);
  175. const saveAndReturnToViewHandler = useCallback(async(opts: SaveOptions) => {
  176. const markdown = codeMirrorEditor?.getDoc();
  177. const revisionId = isRevisionIdRequiredForPageUpdate ? currentRevisionId : undefined;
  178. const page = await save(revisionId, markdown, opts, onConflict);
  179. if (page == null) {
  180. return;
  181. }
  182. mutateEditorMode(EditorMode.View);
  183. updateStateAfterSave?.();
  184. }, [codeMirrorEditor, currentRevisionId, isRevisionIdRequiredForPageUpdate, mutateEditorMode, onConflict, save, updateStateAfterSave]);
  185. const saveWithShortcut = useCallback(async() => {
  186. const markdown = codeMirrorEditor?.getDoc();
  187. const revisionId = isRevisionIdRequiredForPageUpdate ? currentRevisionId : undefined;
  188. const page = await save(revisionId, markdown, undefined, onConflict);
  189. if (page == null) {
  190. return;
  191. }
  192. toastSuccess(t('toaster.save_succeeded'));
  193. updateStateAfterSave?.();
  194. }, [codeMirrorEditor, currentRevisionId, isRevisionIdRequiredForPageUpdate, onConflict, save, t, updateStateAfterSave]);
  195. // the upload event handler
  196. const uploadHandler = useCallback((files: File[]) => {
  197. if (pageId == null) {
  198. logger.error('pageId is invalid', {
  199. pageId,
  200. });
  201. throw new Error('pageId is invalid');
  202. }
  203. uploadAttachments(pageId, files, {
  204. onUploaded: (attachment) => {
  205. const fileName = attachment.originalName;
  206. const prefix = attachment.fileFormat.startsWith('image/')
  207. ? '!' // use "![fileName](url)" syntax when image
  208. : '';
  209. const insertText = `${prefix}[${fileName}](${attachment.filePathProxied})\n`;
  210. codeMirrorEditor?.insertText(insertText);
  211. },
  212. onError: (error) => {
  213. toastError(error);
  214. },
  215. });
  216. }, [codeMirrorEditor, pageId]);
  217. // set handler to save and return to View
  218. useEffect(() => {
  219. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  220. return function cleanup() {
  221. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  222. };
  223. }, [saveAndReturnToViewHandler]);
  224. // set handler to focus
  225. useLayoutEffect(() => {
  226. if (editorMode === EditorMode.Editor) {
  227. codeMirrorEditor?.focus();
  228. }
  229. }, [codeMirrorEditor, currentPage, editorMode]);
  230. // Detect indent size from contents (only when users are allowed to change it)
  231. useEffect(() => {
  232. // do nothing if the indent size fixed
  233. if (isIndentSizeForced == null || isIndentSizeForced) {
  234. mutateCurrentIndentSize(undefined);
  235. return;
  236. }
  237. // detect from markdown
  238. if (initialValue != null) {
  239. const detectedIndent = detectIndent(initialValue);
  240. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  241. mutateCurrentIndentSize(detectedIndent.amount);
  242. }
  243. }
  244. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  245. // set handler to set caret line
  246. useEffect(() => {
  247. const handler = (lineNumber?: number) => {
  248. codeMirrorEditor?.setCaretLine(lineNumber);
  249. // TODO: scroll to the caret line
  250. };
  251. globalEmitter.on('setCaretLine', handler);
  252. return function cleanup() {
  253. globalEmitter.removeListener('setCaretLine', handler);
  254. };
  255. }, [codeMirrorEditor]);
  256. // TODO: Check the reproduction conditions that made this code necessary and confirm reproduction
  257. // // when transitioning to a different page, if the initialValue is the same,
  258. // // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  259. // const onRouterChangeComplete = useCallback(() => {
  260. // codeMirrorEditor?.initDoc(ydoc?.getText('codemirror').toString());
  261. // codeMirrorEditor?.setCaretLine();
  262. // }, [codeMirrorEditor, ydoc]);
  263. // useEffect(() => {
  264. // router.events.on('routeChangeComplete', onRouterChangeComplete);
  265. // return () => {
  266. // router.events.off('routeChangeComplete', onRouterChangeComplete);
  267. // };
  268. // }, [onRouterChangeComplete, router.events]);
  269. const pastEndStyle: CSSProperties | undefined = useMemo(() => {
  270. if (previewRect == null) {
  271. return undefined;
  272. }
  273. const previewRectHeight = previewRect.height;
  274. // containerHeight - 1.5 line height
  275. return { paddingBottom: `calc(${previewRectHeight}px - 2em)` };
  276. }, [previewRect]);
  277. if (!isEditable) {
  278. return <></>;
  279. }
  280. if (rendererOptions == null) {
  281. return <></>;
  282. }
  283. return (
  284. <div data-testid="page-editor" id="page-editor" className={`flex-expand-vert ${props.visibility ? '' : 'd-none'}`}>
  285. <EditorNavbar />
  286. <div className={`flex-expand-horiz ${props.visibility ? '' : 'd-none'}`}>
  287. <div className="page-editor-editor-container flex-expand-vert border-end">
  288. <CodeMirrorEditorMain
  289. isEditorMode={editorMode === EditorMode.Editor}
  290. onChange={markdownChangedHandler}
  291. onSave={saveWithShortcut}
  292. onUpload={uploadHandler}
  293. acceptedUploadFileType={acceptedUploadFileType}
  294. onScroll={scrollEditorHandlerThrottle}
  295. indentSize={currentIndentSize ?? defaultIndentSize}
  296. user={user ?? undefined}
  297. pageId={pageId ?? undefined}
  298. initialValue={initialValue}
  299. editorSettings={editorSettings}
  300. onEditorsUpdated={onEditorsUpdated}
  301. />
  302. </div>
  303. <div
  304. ref={previewRef}
  305. onScroll={scrollPreviewHandlerThrottle}
  306. className="page-editor-preview-container flex-expand-vert overflow-y-auto d-none d-lg-flex"
  307. >
  308. <Preview
  309. rendererOptions={rendererOptions}
  310. markdown={markdownToPreview}
  311. pagePath={currentPagePath}
  312. expandContentWidth={shouldExpandContent}
  313. style={pastEndStyle}
  314. />
  315. </div>
  316. </div>
  317. <EditorNavbarBottom />
  318. </div>
  319. );
  320. });
  321. PageEditor.displayName = 'PageEditor';