PageEditor.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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, CodeMirrorEditorMainReadOnly, 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, useIsOldRevisionPage,
  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 { scrollEditor, scrollPreview } 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. // for scrolling
  58. let isOriginOfScrollSyncEditor = false;
  59. let isOriginOfScrollSyncPreview = false;
  60. export type SaveOptions = {
  61. slackChannels: string,
  62. overwriteScopesOfDescendants?: boolean
  63. }
  64. export type Save = (
  65. revisionId?: string,
  66. requestMarkdown?: string,
  67. opts?: SaveOptions,
  68. onConflict?: ConflictHandler
  69. ) => Promise<IPageHasId | null>
  70. type Props = {
  71. visibility?: boolean,
  72. }
  73. export const PageEditor = React.memo((props: Props): JSX.Element => {
  74. const { t } = useTranslation();
  75. const previewRef = useRef<HTMLDivElement>(null);
  76. const [previewRect] = useRect(previewRef);
  77. const { data: isNotFound } = useIsNotFound();
  78. const { data: pageId } = useCurrentPageId();
  79. const { data: currentPagePath } = useCurrentPagePath();
  80. const { data: currentPathname } = useCurrentPathname();
  81. const { data: currentPage } = useSWRxCurrentPage();
  82. const { data: grantData } = useSelectedGrant();
  83. const { data: editingMarkdown } = useEditingMarkdown();
  84. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  85. const { data: templateBodyData } = useTemplateBodyData();
  86. const { data: isEditable } = useIsEditable();
  87. const { mutate: mutateWaitingSaveProcessing } = useWaitingSaveProcessing();
  88. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  89. const { data: isIndentSizeForced } = useIsIndentSizeForced();
  90. const { data: currentIndentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  91. const { data: defaultIndentSize } = useDefaultIndentSize();
  92. const { data: acceptedUploadFileType } = useAcceptedUploadFileType();
  93. const { data: editorSettings } = useEditorSettings();
  94. const { data: user } = useCurrentUser();
  95. const { data: isOldRevisionPage } = useIsOldRevisionPage();
  96. const { onEditorsUpdated } = useEditingUsers();
  97. const onConflict = useConflictResolver();
  98. const { data: rendererOptions } = usePreviewOptions();
  99. const { mutate: mutateResolvedTheme } = useResolvedThemeForEditor();
  100. const shouldExpandContent = useShouldExpandContent(currentPage);
  101. const updateStateAfterSave = useUpdateStateAfterSave(pageId, { supressEditingMarkdownMutation: true });
  102. useConflictEffect();
  103. const { resolvedTheme } = useNextThemes();
  104. mutateResolvedTheme({ themeData: resolvedTheme });
  105. const currentRevisionId = currentPage?.revision?._id;
  106. const isRevisionIdRequiredForPageUpdate = currentPage?.revision?.origin === undefined;
  107. const initialValueRef = useRef('');
  108. const initialValue = useMemo(() => {
  109. if (!isNotFound) {
  110. return editingMarkdown ?? '';
  111. }
  112. let initialValue = '';
  113. if (isEnabledAttachTitleHeader && currentPathname != null) {
  114. const pageTitle = nodePath.basename(currentPathname);
  115. initialValue += `${pathUtils.attachTitleHeader(pageTitle)}\n`;
  116. }
  117. if (templateBodyData != null) {
  118. initialValue += `${templateBodyData}\n`;
  119. }
  120. return initialValue;
  121. }, [isNotFound, currentPathname, editingMarkdown, isEnabledAttachTitleHeader, templateBodyData]);
  122. useEffect(() => {
  123. // set to ref
  124. initialValueRef.current = initialValue;
  125. }, [initialValue]);
  126. const [markdownToPreview, setMarkdownToPreview] = useState<string>(initialValue);
  127. const setMarkdownPreviewWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string) => {
  128. setMarkdownToPreview(value);
  129. })), []);
  130. useEffect(() => {
  131. setMarkdownToPreview(initialValue);
  132. }, [initialValue]);
  133. const markdownChangedHandler = useCallback((value: string) => {
  134. setMarkdownPreviewWithDebounce(value);
  135. }, [setMarkdownPreviewWithDebounce]);
  136. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  137. const save: Save = useCallback(async(revisionId, markdown, opts, onConflict) => {
  138. if (pageId == null || grantData == null) {
  139. logger.error('Some materials to save are invalid', {
  140. pageId, grantData,
  141. });
  142. throw new Error('Some materials to save are invalid');
  143. }
  144. try {
  145. mutateWaitingSaveProcessing(true);
  146. const { page } = await updatePage({
  147. pageId,
  148. revisionId,
  149. body: markdown ?? '',
  150. grant: grantData?.grant,
  151. origin: Origin.Editor,
  152. userRelatedGrantUserGroupIds: grantData?.userRelatedGrantedGroups?.map((group) => {
  153. return { item: group.id, type: group.type };
  154. }),
  155. ...(opts ?? {}),
  156. });
  157. // to sync revision id with page tree: https://github.com/weseek/growi/pull/7227
  158. mutatePageTree();
  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, grantData, mutateWaitingSaveProcessing, t]);
  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. files.forEach(async(file) => {
  199. try {
  200. const { data: resLimit } = await apiv3Get('/attachment/limit', { fileSize: file.size });
  201. if (!resLimit.isUploadable) {
  202. throw new Error(resLimit.errorMessage);
  203. }
  204. const formData = new FormData();
  205. formData.append('file', file);
  206. if (pageId != null) {
  207. formData.append('page_id', pageId);
  208. }
  209. const { data: resAdd } = await apiv3PostForm('/attachment', formData);
  210. const attachment = resAdd.attachment;
  211. const fileName = attachment.originalName;
  212. let insertText = `[${fileName}](${attachment.filePathProxied})\n`;
  213. // when image
  214. if (attachment.fileFormat.startsWith('image/')) {
  215. // modify to "![fileName](url)" syntax
  216. insertText = `!${insertText}`;
  217. }
  218. codeMirrorEditor?.insertText(insertText);
  219. }
  220. catch (e) {
  221. logger.error('failed to upload', e);
  222. toastError(e);
  223. }
  224. });
  225. }, [codeMirrorEditor, pageId]);
  226. const scrollEditorHandler = useCallback(() => {
  227. if (codeMirrorEditor?.view?.scrollDOM == null || previewRef.current == null) {
  228. return;
  229. }
  230. if (isOriginOfScrollSyncPreview) {
  231. isOriginOfScrollSyncPreview = false;
  232. return;
  233. }
  234. isOriginOfScrollSyncEditor = true;
  235. scrollEditor(codeMirrorEditor.view.scrollDOM, previewRef.current);
  236. }, [codeMirrorEditor]);
  237. const scrollEditorHandlerThrottle = useMemo(() => throttle(25, scrollEditorHandler), [scrollEditorHandler]);
  238. const scrollPreviewHandler = useCallback(() => {
  239. if (codeMirrorEditor?.view?.scrollDOM == null || previewRef.current == null) {
  240. return;
  241. }
  242. if (isOriginOfScrollSyncEditor) {
  243. isOriginOfScrollSyncEditor = false;
  244. return;
  245. }
  246. isOriginOfScrollSyncPreview = true;
  247. scrollPreview(codeMirrorEditor.view.scrollDOM, previewRef.current);
  248. }, [codeMirrorEditor]);
  249. const scrollPreviewHandlerThrottle = useMemo(() => throttle(25, scrollPreviewHandler), [scrollPreviewHandler]);
  250. // initial caret line
  251. useEffect(() => {
  252. codeMirrorEditor?.setCaretLine();
  253. }, [codeMirrorEditor]);
  254. // set handler to save and return to View
  255. useEffect(() => {
  256. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  257. return function cleanup() {
  258. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  259. };
  260. }, [saveAndReturnToViewHandler]);
  261. // set handler to focus
  262. useLayoutEffect(() => {
  263. if (editorMode === EditorMode.Editor) {
  264. codeMirrorEditor?.focus();
  265. }
  266. }, [codeMirrorEditor, editorMode]);
  267. // Detect indent size from contents (only when users are allowed to change it)
  268. useEffect(() => {
  269. // do nothing if the indent size fixed
  270. if (isIndentSizeForced == null || isIndentSizeForced) {
  271. mutateCurrentIndentSize(undefined);
  272. return;
  273. }
  274. // detect from markdown
  275. if (initialValue != null) {
  276. const detectedIndent = detectIndent(initialValue);
  277. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  278. mutateCurrentIndentSize(detectedIndent.amount);
  279. }
  280. }
  281. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  282. // set handler to set caret line
  283. useEffect(() => {
  284. const handler = (lineNumber?: number) => {
  285. codeMirrorEditor?.setCaretLine(lineNumber);
  286. // TODO: scroll to the caret line
  287. };
  288. globalEmitter.on('setCaretLine', handler);
  289. return function cleanup() {
  290. globalEmitter.removeListener('setCaretLine', handler);
  291. };
  292. }, [codeMirrorEditor]);
  293. // TODO: Check the reproduction conditions that made this code necessary and confirm reproduction
  294. // // when transitioning to a different page, if the initialValue is the same,
  295. // // UnControlled CodeMirror value does not reset, so explicitly set the value to initialValue
  296. // const onRouterChangeComplete = useCallback(() => {
  297. // codeMirrorEditor?.initDoc(ydoc?.getText('codemirror').toString());
  298. // codeMirrorEditor?.setCaretLine();
  299. // }, [codeMirrorEditor, ydoc]);
  300. // useEffect(() => {
  301. // router.events.on('routeChangeComplete', onRouterChangeComplete);
  302. // return () => {
  303. // router.events.off('routeChangeComplete', onRouterChangeComplete);
  304. // };
  305. // }, [onRouterChangeComplete, router.events]);
  306. const pastEndStyle: CSSProperties | undefined = useMemo(() => {
  307. if (previewRect == null) {
  308. return undefined;
  309. }
  310. const previewRectHeight = previewRect.height;
  311. // containerHeight - 1.5 line height
  312. return { paddingBottom: `calc(${previewRectHeight}px - 2em)` };
  313. }, [previewRect]);
  314. if (!isEditable) {
  315. return <></>;
  316. }
  317. if (rendererOptions == null) {
  318. return <></>;
  319. }
  320. return (
  321. <div data-testid="page-editor" id="page-editor" className={`flex-expand-vert ${props.visibility ? '' : 'd-none'}`}>
  322. <EditorNavbar />
  323. <div className={`flex-expand-horiz ${props.visibility ? '' : 'd-none'}`}>
  324. <div className="page-editor-editor-container flex-expand-vert border-end">
  325. { !isOldRevisionPage
  326. ? (
  327. <CodeMirrorEditorMain
  328. onChange={markdownChangedHandler}
  329. onSave={saveWithShortcut}
  330. onUpload={uploadHandler}
  331. acceptedUploadFileType={acceptedUploadFileType}
  332. onScroll={scrollEditorHandlerThrottle}
  333. indentSize={currentIndentSize ?? defaultIndentSize}
  334. user={user ?? undefined}
  335. pageId={pageId ?? undefined}
  336. initialValue={initialValue}
  337. editorSettings={editorSettings}
  338. onEditorsUpdated={onEditorsUpdated}
  339. />
  340. )
  341. : (
  342. <CodeMirrorEditorMainReadOnly
  343. body={initialValue}
  344. />
  345. )
  346. }
  347. </div>
  348. <div
  349. ref={previewRef}
  350. onScroll={scrollPreviewHandlerThrottle}
  351. className="page-editor-preview-container flex-expand-vert overflow-y-auto d-none d-lg-flex"
  352. >
  353. <Preview
  354. rendererOptions={rendererOptions}
  355. markdown={markdownToPreview}
  356. pagePath={currentPagePath}
  357. expandContentWidth={shouldExpandContent}
  358. style={pastEndStyle}
  359. />
  360. </div>
  361. </div>
  362. { !isOldRevisionPage && (<EditorNavbarBottom />) }
  363. </div>
  364. );
  365. });
  366. PageEditor.displayName = 'PageEditor';