PageEditor.tsx 18 KB

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