PageEditor.tsx 18 KB

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