PageEditor.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import React, {
  2. useCallback, useEffect, useMemo, useRef, useState,
  3. } from 'react';
  4. import EventEmitter from 'events';
  5. import {
  6. IPageHasId, PageGrant, pathUtils,
  7. } from '@growi/core';
  8. import detectIndent from 'detect-indent';
  9. import { useTranslation } from 'next-i18next';
  10. import { useRouter } from 'next/router';
  11. import { throttle, debounce } from 'throttle-debounce';
  12. import { useUpdateStateAfterSave, useSaveOrUpdate } from '~/client/services/page-operation';
  13. import { apiGet, apiPostForm } from '~/client/util/apiv1-client';
  14. import { toastError, toastSuccess } from '~/client/util/toastr';
  15. import { IEditorMethods } from '~/interfaces/editor-methods';
  16. import { OptionsToSave } from '~/interfaces/page-operation';
  17. import { SocketEventName } from '~/interfaces/websocket';
  18. import {
  19. useCurrentPathname, useCurrentPageId, useIsEnabledAttachTitleHeader, useTemplateBodyData,
  20. useIsEditable, useIsUploadableFile, useIsUploadableImage, useIsNotFound, useIsIndentSizeForced,
  21. } from '~/stores/context';
  22. import {
  23. useCurrentIndentSize, useSWRxSlackChannels, useIsSlackEnabled, useIsTextlintEnabled, usePageTagsForEditors,
  24. useIsEnabledUnsavedWarning,
  25. useIsConflict,
  26. useEditingMarkdown,
  27. } from '~/stores/editor';
  28. import { useConflictDiffModal } from '~/stores/modal';
  29. import { useCurrentPagePath, useSWRxCurrentPage, useSWRxTagsInfo } from '~/stores/page';
  30. import { usePageTreeTermManager } from '~/stores/page-listing';
  31. import { useSetRemoteLatestPageData } from '~/stores/remote-latest-page';
  32. import { usePreviewOptions } from '~/stores/renderer';
  33. import {
  34. EditorMode,
  35. useEditorMode, useSelectedGrant,
  36. } from '~/stores/ui';
  37. import { useGlobalSocket } from '~/stores/websocket';
  38. import { registerGrowiFacade } from '~/utils/growi-facade';
  39. import loggerFactory from '~/utils/logger';
  40. // import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
  41. import { ConflictDiffModal } from './PageEditor/ConflictDiffModal';
  42. import Editor from './PageEditor/Editor';
  43. import Preview from './PageEditor/Preview';
  44. import scrollSyncHelper from './PageEditor/ScrollSyncHelper';
  45. const logger = loggerFactory('growi:PageEditor');
  46. declare global {
  47. // eslint-disable-next-line vars-on-top, no-var
  48. var globalEmitter: EventEmitter;
  49. }
  50. // for scrolling
  51. let lastScrolledDateWithCursor: Date | null = null;
  52. let isOriginOfScrollSyncEditor = false;
  53. let isOriginOfScrollSyncPreview = false;
  54. const PageEditor = React.memo((): JSX.Element => {
  55. const { t } = useTranslation();
  56. const router = useRouter();
  57. const { data: isNotFound } = useIsNotFound();
  58. const { data: pageId } = useCurrentPageId();
  59. const { data: currentPagePath } = useCurrentPagePath();
  60. const { data: currentPathname } = useCurrentPathname();
  61. const { data: currentPage, mutate: mutateCurrentPage } = useSWRxCurrentPage();
  62. const { data: grantData, mutate: mutateGrant } = useSelectedGrant();
  63. const { data: pageTags, sync: syncTagsInfoForEditor } = usePageTagsForEditors(pageId);
  64. const { mutate: mutateTagsInfo } = useSWRxTagsInfo(pageId);
  65. const { data: editingMarkdown, mutate: mutateEditingMarkdown } = useEditingMarkdown();
  66. const { data: isEnabledAttachTitleHeader } = useIsEnabledAttachTitleHeader();
  67. const { data: templateBodyData } = useTemplateBodyData();
  68. const { data: isEditable } = useIsEditable();
  69. const { data: editorMode, mutate: mutateEditorMode } = useEditorMode();
  70. const { data: isSlackEnabled } = useIsSlackEnabled();
  71. const { data: isTextlintEnabled } = useIsTextlintEnabled();
  72. const { data: isIndentSizeForced } = useIsIndentSizeForced();
  73. const { data: currentIndentSize, mutate: mutateCurrentIndentSize } = useCurrentIndentSize();
  74. const { data: isUploadableFile } = useIsUploadableFile();
  75. const { data: isUploadableImage } = useIsUploadableImage();
  76. const { data: conflictDiffModalStatus, close: closeConflictDiffModal } = useConflictDiffModal();
  77. const { advance: advancePt } = usePageTreeTermManager();
  78. const { data: rendererOptions, mutate: mutateRendererOptions } = usePreviewOptions();
  79. const { mutate: mutateIsEnabledUnsavedWarning } = useIsEnabledUnsavedWarning();
  80. const saveOrUpdate = useSaveOrUpdate();
  81. const updateStateAfterSave = useUpdateStateAfterSave(pageId);
  82. const currentRevisionId = currentPage?.revision?._id;
  83. const initialValue = useMemo(() => {
  84. if (!isNotFound) {
  85. return editingMarkdown ?? '';
  86. }
  87. let initialValue = '';
  88. if (isEnabledAttachTitleHeader && currentPathname != null) {
  89. initialValue += `${pathUtils.attachTitleHeader(currentPathname)}\n`;
  90. }
  91. if (templateBodyData != null) {
  92. initialValue += `${templateBodyData}\n`;
  93. }
  94. return initialValue;
  95. }, [isNotFound, currentPathname, editingMarkdown, isEnabledAttachTitleHeader, templateBodyData]);
  96. const markdownToSave = useRef<string>(initialValue);
  97. const [markdownToPreview, setMarkdownToPreview] = useState<string>(initialValue);
  98. const { data: socket } = useGlobalSocket();
  99. const { mutate: mutateIsConflict } = useIsConflict();
  100. const editorRef = useRef<IEditorMethods>(null);
  101. const previewRef = useRef<HTMLDivElement>(null);
  102. const checkIsConflict = useCallback((data) => {
  103. const { s2cMessagePageUpdated } = data;
  104. const isConflict = markdownToPreview !== s2cMessagePageUpdated.revisionBody;
  105. mutateIsConflict(isConflict);
  106. }, [markdownToPreview, mutateIsConflict]);
  107. useEffect(() => {
  108. markdownToSave.current = initialValue;
  109. setMarkdownToPreview(initialValue);
  110. }, [initialValue]);
  111. useEffect(() => {
  112. if (socket == null) { return }
  113. socket.on(SocketEventName.PageUpdated, checkIsConflict);
  114. return () => {
  115. socket.off(SocketEventName.PageUpdated, checkIsConflict);
  116. };
  117. }, [socket, checkIsConflict]);
  118. const optionsToSave = useMemo((): OptionsToSave | undefined => {
  119. if (grantData == null) {
  120. return;
  121. }
  122. const optionsToSave = {
  123. isSlackEnabled: isSlackEnabled ?? false,
  124. slackChannels: '', // set in save method by opts in SavePageControlls.tsx
  125. grant: grantData.grant,
  126. pageTags: pageTags ?? [],
  127. grantUserGroupId: grantData.grantedGroup?.id,
  128. grantUserGroupName: grantData.grantedGroup?.name,
  129. };
  130. return optionsToSave;
  131. }, [grantData, isSlackEnabled, pageTags]);
  132. // register to facade
  133. useEffect(() => {
  134. // for markdownRenderer
  135. registerGrowiFacade({
  136. markdownRenderer: {
  137. optionsMutators: {
  138. previewOptionsMutator: mutateRendererOptions,
  139. },
  140. },
  141. });
  142. }, [mutateRendererOptions]);
  143. const setMarkdownWithDebounce = useMemo(() => debounce(100, throttle(150, (value: string, isClean: boolean) => {
  144. markdownToSave.current = value;
  145. setMarkdownToPreview(value);
  146. // Displays an unsaved warning alert
  147. mutateIsEnabledUnsavedWarning(!isClean);
  148. })), [mutateIsEnabledUnsavedWarning]);
  149. const markdownChangedHandler = useCallback((value: string, isClean: boolean): void => {
  150. setMarkdownWithDebounce(value, isClean);
  151. }, [setMarkdownWithDebounce]);
  152. const save = useCallback(async(opts?: {slackChannels: string, overwriteScopesOfDescendants?: boolean}): Promise<IPageHasId | null> => {
  153. if (currentPathname == null || optionsToSave == null) {
  154. logger.error('Some materials to save are invalid', { grantData, isSlackEnabled, currentPathname });
  155. throw new Error('Some materials to save are invalid');
  156. }
  157. const options = Object.assign(optionsToSave, opts);
  158. try {
  159. const { page } = await saveOrUpdate(
  160. markdownToSave.current,
  161. { pageId, path: currentPagePath || currentPathname, revisionId: currentRevisionId },
  162. options,
  163. );
  164. // to sync revision id with page tree: https://github.com/weseek/growi/pull/7227
  165. advancePt();
  166. return page;
  167. }
  168. catch (error) {
  169. logger.error('failed to save', error);
  170. toastError(error);
  171. if (error.code === 'conflict') {
  172. // pageContainer.setState({
  173. // remoteRevisionId: error.data.revisionId,
  174. // remoteRevisionBody: error.data.revisionBody,
  175. // remoteRevisionUpdateAt: error.data.createdAt,
  176. // lastUpdateUser: error.data.user,
  177. // });
  178. }
  179. return null;
  180. }
  181. // eslint-disable-next-line max-len
  182. }, [currentPathname, optionsToSave, grantData, isSlackEnabled, saveOrUpdate, pageId, currentPagePath, currentRevisionId, advancePt]);
  183. const saveAndReturnToViewHandler = useCallback(async(opts: {slackChannels: string, overwriteScopesOfDescendants?: boolean}) => {
  184. if (editorMode !== EditorMode.Editor) {
  185. return;
  186. }
  187. const page = await save(opts);
  188. if (page == null) {
  189. return;
  190. }
  191. if (isNotFound) {
  192. await router.push(`/${page._id}`);
  193. }
  194. else {
  195. updateStateAfterSave?.();
  196. }
  197. mutateEditorMode(EditorMode.View);
  198. }, [editorMode, save, isNotFound, mutateEditorMode, router, updateStateAfterSave]);
  199. const saveWithShortcut = useCallback(async() => {
  200. if (editorMode !== EditorMode.Editor) {
  201. return;
  202. }
  203. const page = await save();
  204. if (page != null) {
  205. updateStateAfterSave?.();
  206. toastSuccess(t('toaster.save_succeeded'));
  207. }
  208. }, [editorMode, save, t, updateStateAfterSave]);
  209. /**
  210. * the upload event handler
  211. * @param {any} file
  212. */
  213. const uploadHandler = useCallback(async(file) => {
  214. if (editorRef.current == null) {
  215. return;
  216. }
  217. try {
  218. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  219. let res: any = await apiGet('/attachments.limit', {
  220. fileSize: file.size,
  221. });
  222. if (!res.isUploadable) {
  223. throw new Error(res.errorMessage);
  224. }
  225. const formData = new FormData();
  226. // const { pageId, path } = pageContainer.state;
  227. formData.append('file', file);
  228. if (currentPagePath != null) {
  229. formData.append('path', currentPagePath);
  230. }
  231. if (pageId != null) {
  232. formData.append('page_id', pageId);
  233. }
  234. res = await apiPostForm('/attachments.add', formData);
  235. const attachment = res.attachment;
  236. const fileName = attachment.originalName;
  237. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  238. // when image
  239. if (attachment.fileFormat.startsWith('image/')) {
  240. // modify to "![fileName](url)" syntax
  241. insertText = `!${insertText}`;
  242. }
  243. editorRef.current.insertText(insertText);
  244. // when if created newly
  245. if (res.pageCreated) {
  246. logger.info('Page is created', res.page._id);
  247. globalEmitter.emit('resetInitializedHackMdStatus');
  248. mutateGrant(res.page.grant);
  249. }
  250. }
  251. catch (e) {
  252. logger.error('failed to upload', e);
  253. toastError(e);
  254. }
  255. finally {
  256. editorRef.current.terminateUploadingState();
  257. }
  258. }, [currentPagePath, mutateGrant, pageId]);
  259. const scrollPreviewByEditorLine = useCallback((line: number) => {
  260. if (previewRef.current == null) {
  261. return;
  262. }
  263. // prevent circular invocation
  264. if (isOriginOfScrollSyncPreview) {
  265. isOriginOfScrollSyncPreview = false; // turn off the flag
  266. return;
  267. }
  268. // turn on the flag
  269. isOriginOfScrollSyncEditor = true;
  270. scrollSyncHelper.scrollPreview(previewRef.current, line);
  271. }, []);
  272. const scrollPreviewByEditorLineWithThrottle = useMemo(() => throttle(20, scrollPreviewByEditorLine), [scrollPreviewByEditorLine]);
  273. /**
  274. * the scroll event handler from codemirror
  275. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  276. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  277. * And data.line is also available that is added by Editor component
  278. * @see https://codemirror.net/doc/manual.html#events
  279. */
  280. const editorScrolledHandler = useCallback(({ line }: { line: number }) => {
  281. // prevent scrolling
  282. // if the elapsed time from last scroll with cursor is shorter than 40ms
  283. const now = new Date();
  284. if (lastScrolledDateWithCursor != null && now.getTime() - lastScrolledDateWithCursor.getTime() < 40) {
  285. return;
  286. }
  287. scrollPreviewByEditorLineWithThrottle(line);
  288. }, [scrollPreviewByEditorLineWithThrottle]);
  289. /**
  290. * scroll Preview element by cursor moving
  291. * @param {number} line
  292. */
  293. const scrollPreviewByCursorMoving = useCallback((line: number) => {
  294. if (previewRef.current == null) {
  295. return;
  296. }
  297. // prevent circular invocation
  298. if (isOriginOfScrollSyncPreview) {
  299. isOriginOfScrollSyncPreview = false; // turn off the flag
  300. return;
  301. }
  302. // turn on the flag
  303. isOriginOfScrollSyncEditor = true;
  304. if (previewRef.current != null) {
  305. scrollSyncHelper.scrollPreviewToRevealOverflowing(previewRef.current, line);
  306. }
  307. }, []);
  308. const scrollPreviewByCursorMovingWithThrottle = useMemo(() => throttle(20, scrollPreviewByCursorMoving), [scrollPreviewByCursorMoving]);
  309. /**
  310. * the scroll event handler from codemirror
  311. * @param {number} line
  312. * @see https://codemirror.net/doc/manual.html#events
  313. */
  314. const editorScrollCursorIntoViewHandler = useCallback((line: number) => {
  315. // record date
  316. lastScrolledDateWithCursor = new Date();
  317. scrollPreviewByCursorMovingWithThrottle(line);
  318. }, [scrollPreviewByCursorMovingWithThrottle]);
  319. /**
  320. * scroll Editor component by scroll event of Preview component
  321. * @param {number} offset
  322. */
  323. const scrollEditorByPreviewScroll = useCallback((offset: number) => {
  324. if (editorRef.current == null || previewRef.current == null) {
  325. return;
  326. }
  327. // prevent circular invocation
  328. if (isOriginOfScrollSyncEditor) {
  329. isOriginOfScrollSyncEditor = false; // turn off the flag
  330. return;
  331. }
  332. // turn on the flag
  333. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  334. isOriginOfScrollSyncPreview = true;
  335. scrollSyncHelper.scrollEditor(editorRef.current, previewRef.current, offset);
  336. }, []);
  337. const scrollEditorByPreviewScrollWithThrottle = useMemo(() => throttle(20, scrollEditorByPreviewScroll), [scrollEditorByPreviewScroll]);
  338. const afterResolvedHandler = useCallback(async() => {
  339. // get page data from db
  340. const pageData = await mutateCurrentPage();
  341. // update tag
  342. await mutateTagsInfo(); // get from DB
  343. syncTagsInfoForEditor(); // sync global state for client
  344. // clear isConflict
  345. mutateIsConflict(false);
  346. // set resolved markdown in editing markdown
  347. const markdown = pageData?.revision.body ?? '';
  348. mutateEditingMarkdown(markdown);
  349. }, [mutateCurrentPage, mutateEditingMarkdown, mutateIsConflict, mutateTagsInfo, syncTagsInfoForEditor]);
  350. // initialize
  351. useEffect(() => {
  352. if (initialValue == null) {
  353. return;
  354. }
  355. markdownToSave.current = initialValue;
  356. setMarkdownToPreview(initialValue);
  357. mutateIsEnabledUnsavedWarning(false);
  358. }, [initialValue, mutateIsEnabledUnsavedWarning]);
  359. // initial caret line
  360. useEffect(() => {
  361. if (editorRef.current != null) {
  362. editorRef.current.setCaretLine(0);
  363. }
  364. }, []);
  365. // set handler to set caret line
  366. useEffect(() => {
  367. const handler = (line) => {
  368. if (editorRef.current != null) {
  369. editorRef.current.setCaretLine(line);
  370. }
  371. if (previewRef.current != null) {
  372. scrollSyncHelper.scrollPreview(previewRef.current, line);
  373. }
  374. };
  375. globalEmitter.on('setCaretLine', handler);
  376. return function cleanup() {
  377. globalEmitter.removeListener('setCaretLine', handler);
  378. };
  379. }, []);
  380. // set handler to save and return to View
  381. useEffect(() => {
  382. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  383. return function cleanup() {
  384. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  385. };
  386. }, [saveAndReturnToViewHandler]);
  387. // set handler to focus
  388. useEffect(() => {
  389. if (editorRef.current != null && editorMode === EditorMode.Editor) {
  390. editorRef.current.forceToFocus();
  391. }
  392. }, [editorMode]);
  393. // Detect indent size from contents (only when users are allowed to change it)
  394. useEffect(() => {
  395. // do nothing if the indent size fixed
  396. if (isIndentSizeForced == null || isIndentSizeForced) {
  397. return;
  398. }
  399. // detect from markdown
  400. if (initialValue != null) {
  401. const detectedIndent = detectIndent(initialValue);
  402. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  403. mutateCurrentIndentSize(detectedIndent.amount);
  404. }
  405. }
  406. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  407. if (!isEditable) {
  408. return <></>;
  409. }
  410. if (rendererOptions == null) {
  411. return <></>;
  412. }
  413. const isUploadable = isUploadableImage || isUploadableFile;
  414. return (
  415. <div className="d-flex flex-wrap">
  416. <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
  417. <Editor
  418. ref={editorRef}
  419. value={initialValue}
  420. isUploadable={isUploadable}
  421. isUploadableFile={isUploadableFile}
  422. isTextlintEnabled={isTextlintEnabled}
  423. indentSize={currentIndentSize}
  424. onScroll={editorScrolledHandler}
  425. onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
  426. onChange={markdownChangedHandler}
  427. onUpload={uploadHandler}
  428. onSave={saveWithShortcut}
  429. />
  430. </div>
  431. <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
  432. <Preview
  433. ref={previewRef}
  434. rendererOptions={rendererOptions}
  435. markdown={markdownToPreview}
  436. pagePath={currentPagePath}
  437. onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)}
  438. />
  439. </div>
  440. <ConflictDiffModal
  441. isOpen={conflictDiffModalStatus?.isOpened}
  442. onClose={() => closeConflictDiffModal()}
  443. markdownOnEdit={markdownToPreview}
  444. optionsToSave={optionsToSave}
  445. afterResolvedHandler={afterResolvedHandler}
  446. />
  447. </div>
  448. );
  449. });
  450. PageEditor.displayName = 'PageEditor';
  451. export default PageEditor;