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