PageEditor.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 { apiv3Get, apiv3PostForm } from '~/client/util/apiv3-client';
  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,
  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. slackChannels: string,
  59. overwriteScopesOfDescendants?: boolean
  60. }
  61. export type Save = (
  62. revisionId?: string,
  63. requestMarkdown?: string,
  64. opts?: SaveOptions,
  65. onConflict?: ConflictHandler
  66. ) => Promise<IPageHasId | null>
  67. type Props = {
  68. visibility?: boolean,
  69. }
  70. export const PageEditor = React.memo((props: Props): JSX.Element => {
  71. const { t } = useTranslation();
  72. const previewRef = useRef<HTMLDivElement>(null);
  73. const [previewRect] = useRect(previewRef);
  74. const { data: isNotFound } = useIsNotFound();
  75. const { data: pageId } = useCurrentPageId();
  76. const { data: currentPagePath } = useCurrentPagePath();
  77. const { data: currentPathname } = useCurrentPathname();
  78. const { data: currentPage } = useSWRxCurrentPage();
  79. const { data: grantData } = useSelectedGrant();
  80. const { data: editingMarkdown } = useEditingMarkdown();
  81. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  82. const { data: templateBodyData } = useTemplateBodyData();
  83. const { data: isEditable } = useIsEditable();
  84. const { mutate: mutateWaitingSaveProcessing } = useWaitingSaveProcessing();
  85. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  86. const { data: isIndentSizeForced } = useIsIndentSizeForced();
  87. const { data: currentIndentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  88. const { data: defaultIndentSize } = useDefaultIndentSize();
  89. const { data: acceptedUploadFileType } = useAcceptedUploadFileType();
  90. const { data: editorSettings } = useEditorSettings();
  91. const { data: user } = useCurrentUser();
  92. const { onEditorsUpdated } = useEditingUsers();
  93. const onConflict = useConflictResolver();
  94. const { data: rendererOptions } = usePreviewOptions();
  95. const { mutate: mutateResolvedTheme } = useResolvedThemeForEditor();
  96. const shouldExpandContent = useShouldExpandContent(currentPage);
  97. const updateStateAfterSave = useUpdateStateAfterSave(pageId, { supressEditingMarkdownMutation: true });
  98. useConflictEffect();
  99. const { resolvedTheme } = useNextThemes();
  100. mutateResolvedTheme({ themeData: resolvedTheme });
  101. const currentRevisionId = currentPage?.revision?._id;
  102. const isRevisionIdRequiredForPageUpdate = currentPage?.revision?.origin === undefined;
  103. const initialValueRef = useRef('');
  104. const initialValue = useMemo(() => {
  105. if (!isNotFound) {
  106. return editingMarkdown ?? '';
  107. }
  108. let initialValue = '';
  109. if (isEnabledAttachTitleHeader && currentPathname != null) {
  110. const pageTitle = nodePath.basename(currentPathname);
  111. initialValue += `${pathUtils.attachTitleHeader(pageTitle)}\n`;
  112. }
  113. if (templateBodyData != null) {
  114. initialValue += `${templateBodyData}\n`;
  115. }
  116. return initialValue;
  117. }, [isNotFound, currentPathname, editingMarkdown, isEnabledAttachTitleHeader, templateBodyData]);
  118. useEffect(() => {
  119. // set to ref
  120. initialValueRef.current = initialValue;
  121. }, [initialValue]);
  122. const [markdownToPreview, setMarkdownToPreview] = useState<string>(initialValue);
  123. const setMarkdownPreviewWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string) => {
  124. setMarkdownToPreview(value);
  125. })), []);
  126. const markdownChangedHandler = useCallback((value: string) => {
  127. setMarkdownPreviewWithDebounce(value);
  128. }, [setMarkdownPreviewWithDebounce]);
  129. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  130. const { scrollEditorHandler, scrollPreviewHandler } = useScrollSync(GlobalCodeMirrorEditorKey.MAIN, previewRef);
  131. const scrollEditorHandlerThrottle = useMemo(() => throttle(25, scrollEditorHandler), [scrollEditorHandler]);
  132. const scrollPreviewHandlerThrottle = useMemo(() => throttle(25, scrollPreviewHandler), [scrollPreviewHandler]);
  133. const save: Save = useCallback(async(revisionId, markdown, opts, onConflict) => {
  134. if (pageId == null || grantData == null) {
  135. logger.error('Some materials to save are invalid', {
  136. pageId, grantData,
  137. });
  138. throw new Error('Some materials to save are invalid');
  139. }
  140. try {
  141. mutateWaitingSaveProcessing(true);
  142. const { page } = await updatePage({
  143. pageId,
  144. revisionId,
  145. body: markdown ?? '',
  146. grant: grantData?.grant,
  147. origin: Origin.Editor,
  148. userRelatedGrantUserGroupIds: grantData?.userRelatedGrantedGroups?.map((group) => {
  149. return { item: group.id, type: group.type };
  150. }),
  151. ...(opts ?? {}),
  152. });
  153. // to sync revision id with page tree: https://github.com/weseek/growi/pull/7227
  154. mutatePageTree();
  155. return page;
  156. }
  157. catch (error) {
  158. logger.error('failed to save', error);
  159. const remoteRevisionData = extractRemoteRevisionDataFromErrorObj(error);
  160. if (remoteRevisionData != null) {
  161. onConflict?.(remoteRevisionData, markdown ?? '', save, opts);
  162. toastWarning(t('modal_resolve_conflict.conflicts_with_new_body_on_server_side'));
  163. return null;
  164. }
  165. toastError(error);
  166. return null;
  167. }
  168. finally {
  169. mutateWaitingSaveProcessing(false);
  170. }
  171. }, [pageId, grantData, mutateWaitingSaveProcessing, t]);
  172. const saveAndReturnToViewHandler = useCallback(async(opts: SaveOptions) => {
  173. const markdown = codeMirrorEditor?.getDoc();
  174. const revisionId = isRevisionIdRequiredForPageUpdate ? currentRevisionId : undefined;
  175. const page = await save(revisionId, markdown, opts, onConflict);
  176. if (page == null) {
  177. return;
  178. }
  179. mutateEditorMode(EditorMode.View);
  180. updateStateAfterSave?.();
  181. }, [codeMirrorEditor, currentRevisionId, isRevisionIdRequiredForPageUpdate, mutateEditorMode, onConflict, save, updateStateAfterSave]);
  182. const saveWithShortcut = useCallback(async() => {
  183. const markdown = codeMirrorEditor?.getDoc();
  184. const revisionId = isRevisionIdRequiredForPageUpdate ? currentRevisionId : undefined;
  185. const page = await save(revisionId, markdown, undefined, onConflict);
  186. if (page == null) {
  187. return;
  188. }
  189. toastSuccess(t('toaster.save_succeeded'));
  190. updateStateAfterSave?.();
  191. }, [codeMirrorEditor, currentRevisionId, isRevisionIdRequiredForPageUpdate, onConflict, save, t, updateStateAfterSave]);
  192. // the upload event handler
  193. const uploadHandler = useCallback((files: File[]) => {
  194. files.forEach(async(file) => {
  195. try {
  196. const { data: resLimit } = await apiv3Get('/attachment/limit', { fileSize: file.size });
  197. if (!resLimit.isUploadable) {
  198. throw new Error(resLimit.errorMessage);
  199. }
  200. const formData = new FormData();
  201. formData.append('file', file);
  202. if (pageId != null) {
  203. formData.append('page_id', pageId);
  204. }
  205. const { data: resAdd } = await apiv3PostForm('/attachment', formData);
  206. const attachment = resAdd.attachment;
  207. const fileName = attachment.originalName;
  208. let insertText = `[${fileName}](${attachment.filePathProxied})\n`;
  209. // when image
  210. if (attachment.fileFormat.startsWith('image/')) {
  211. // modify to "![fileName](url)" syntax
  212. insertText = `!${insertText}`;
  213. }
  214. codeMirrorEditor?.insertText(insertText);
  215. }
  216. catch (e) {
  217. logger.error('failed to upload', e);
  218. toastError(e);
  219. }
  220. });
  221. }, [codeMirrorEditor, pageId]);
  222. // initial caret line
  223. useEffect(() => {
  224. codeMirrorEditor?.setCaretLine();
  225. }, [codeMirrorEditor]);
  226. // set handler to save and return to View
  227. useEffect(() => {
  228. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  229. return function cleanup() {
  230. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  231. };
  232. }, [saveAndReturnToViewHandler]);
  233. // set handler to focus
  234. useLayoutEffect(() => {
  235. if (editorMode === EditorMode.Editor) {
  236. codeMirrorEditor?.focus();
  237. }
  238. }, [codeMirrorEditor, editorMode]);
  239. // Detect indent size from contents (only when users are allowed to change it)
  240. useEffect(() => {
  241. // do nothing if the indent size fixed
  242. if (isIndentSizeForced == null || isIndentSizeForced) {
  243. mutateCurrentIndentSize(undefined);
  244. return;
  245. }
  246. // detect from markdown
  247. if (initialValue != null) {
  248. const detectedIndent = detectIndent(initialValue);
  249. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  250. mutateCurrentIndentSize(detectedIndent.amount);
  251. }
  252. }
  253. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  254. // set handler to set caret line
  255. useEffect(() => {
  256. const handler = (lineNumber?: number) => {
  257. codeMirrorEditor?.setCaretLine(lineNumber);
  258. // TODO: scroll to the caret line
  259. };
  260. globalEmitter.on('setCaretLine', handler);
  261. return function cleanup() {
  262. globalEmitter.removeListener('setCaretLine', handler);
  263. };
  264. }, [codeMirrorEditor]);
  265. // TODO: Check the reproduction conditions that made this code necessary and confirm reproduction
  266. // // when transitioning to a different page, if the initialValue is the same,
  267. // // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  268. // const onRouterChangeComplete = useCallback(() => {
  269. // codeMirrorEditor?.initDoc(ydoc?.getText('codemirror').toString());
  270. // codeMirrorEditor?.setCaretLine();
  271. // }, [codeMirrorEditor, ydoc]);
  272. // useEffect(() => {
  273. // router.events.on('routeChangeComplete', onRouterChangeComplete);
  274. // return () => {
  275. // router.events.off('routeChangeComplete', onRouterChangeComplete);
  276. // };
  277. // }, [onRouterChangeComplete, router.events]);
  278. const pastEndStyle: CSSProperties | undefined = useMemo(() => {
  279. if (previewRect == null) {
  280. return undefined;
  281. }
  282. const previewRectHeight = previewRect.height;
  283. // containerHeight - 1.5 line height
  284. return { paddingBottom: `calc(${previewRectHeight}px - 2em)` };
  285. }, [previewRect]);
  286. if (!isEditable) {
  287. return <></>;
  288. }
  289. if (rendererOptions == null) {
  290. return <></>;
  291. }
  292. return (
  293. <div data-testid="page-editor" id="page-editor" className={`flex-expand-vert ${props.visibility ? '' : 'd-none'}`}>
  294. <EditorNavbar />
  295. <div className={`flex-expand-horiz ${props.visibility ? '' : 'd-none'}`}>
  296. <div className="page-editor-editor-container flex-expand-vert border-end">
  297. <CodeMirrorEditorMain
  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';