PageEditor.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. if (pageId == null && markdownToSave.current != null) {
  255. formData.append('page_body', markdownToSave.current);
  256. }
  257. res = await apiPostForm('/attachments.add', formData);
  258. const attachment = res.attachment;
  259. const fileName = attachment.originalName;
  260. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  261. // when image
  262. if (attachment.fileFormat.startsWith('image/')) {
  263. // modify to "![fileName](url)" syntax
  264. insertText = `!${insertText}`;
  265. }
  266. editorRef.current.insertText(insertText);
  267. // when if created newly
  268. if (res.pageCreated) {
  269. logger.info('Page is created', res.page._id);
  270. globalEmitter.emit('resetInitializedHackMdStatus');
  271. mutateGrant(res.page.grant);
  272. }
  273. }
  274. catch (e) {
  275. logger.error('failed to upload', e);
  276. toastError(e);
  277. }
  278. finally {
  279. editorRef.current.terminateUploadingState();
  280. }
  281. }, [currentPagePath, mutateGrant, pageId]);
  282. const scrollPreviewByEditorLine = useCallback((line: number) => {
  283. if (previewRef.current == null) {
  284. return;
  285. }
  286. // prevent circular invocation
  287. if (isOriginOfScrollSyncPreview) {
  288. isOriginOfScrollSyncPreview = false; // turn off the flag
  289. return;
  290. }
  291. // turn on the flag
  292. isOriginOfScrollSyncEditor = true;
  293. scrollSyncHelper.scrollPreview(previewRef.current, line);
  294. }, []);
  295. const scrollPreviewByEditorLineWithThrottle = useMemo(() => throttle(20, scrollPreviewByEditorLine), [scrollPreviewByEditorLine]);
  296. /**
  297. * the scroll event handler from codemirror
  298. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  299. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  300. * And data.line is also available that is added by Editor component
  301. * @see https://codemirror.net/doc/manual.html#events
  302. */
  303. const editorScrolledHandler = useCallback(({ line }: { line: number }) => {
  304. // prevent scrolling
  305. // if the elapsed time from last scroll with cursor is shorter than 40ms
  306. const now = new Date();
  307. if (lastScrolledDateWithCursor != null && now.getTime() - lastScrolledDateWithCursor.getTime() < 40) {
  308. return;
  309. }
  310. scrollPreviewByEditorLineWithThrottle(line);
  311. }, [scrollPreviewByEditorLineWithThrottle]);
  312. /**
  313. * scroll Preview element by cursor moving
  314. * @param {number} line
  315. */
  316. const scrollPreviewByCursorMoving = useCallback((line: number) => {
  317. if (previewRef.current == null) {
  318. return;
  319. }
  320. // prevent circular invocation
  321. if (isOriginOfScrollSyncPreview) {
  322. isOriginOfScrollSyncPreview = false; // turn off the flag
  323. return;
  324. }
  325. // turn on the flag
  326. isOriginOfScrollSyncEditor = true;
  327. if (previewRef.current != null) {
  328. scrollSyncHelper.scrollPreviewToRevealOverflowing(previewRef.current, line);
  329. }
  330. }, []);
  331. const scrollPreviewByCursorMovingWithThrottle = useMemo(() => throttle(20, scrollPreviewByCursorMoving), [scrollPreviewByCursorMoving]);
  332. /**
  333. * the scroll event handler from codemirror
  334. * @param {number} line
  335. * @see https://codemirror.net/doc/manual.html#events
  336. */
  337. const editorScrollCursorIntoViewHandler = useCallback((line: number) => {
  338. // record date
  339. lastScrolledDateWithCursor = new Date();
  340. scrollPreviewByCursorMovingWithThrottle(line);
  341. }, [scrollPreviewByCursorMovingWithThrottle]);
  342. /**
  343. * scroll Editor component by scroll event of Preview component
  344. * @param {number} offset
  345. */
  346. const scrollEditorByPreviewScroll = useCallback((offset: number) => {
  347. if (editorRef.current == null || previewRef.current == null) {
  348. return;
  349. }
  350. // prevent circular invocation
  351. if (isOriginOfScrollSyncEditor) {
  352. isOriginOfScrollSyncEditor = false; // turn off the flag
  353. return;
  354. }
  355. // turn on the flag
  356. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  357. isOriginOfScrollSyncPreview = true;
  358. scrollSyncHelper.scrollEditor(editorRef.current, previewRef.current, offset);
  359. }, []);
  360. const scrollEditorByPreviewScrollWithThrottle = useMemo(() => throttle(20, scrollEditorByPreviewScroll), [scrollEditorByPreviewScroll]);
  361. const afterResolvedHandler = useCallback(async() => {
  362. // get page data from db
  363. const pageData = await mutateCurrentPage();
  364. // update tag
  365. await mutateTagsInfo(); // get from DB
  366. syncTagsInfoForEditor(); // sync global state for client
  367. // clear isConflict
  368. mutateIsConflict(false);
  369. // set resolved markdown in editing markdown
  370. const markdown = pageData?.revision.body ?? '';
  371. mutateEditingMarkdown(markdown);
  372. }, [mutateCurrentPage, mutateEditingMarkdown, mutateIsConflict, mutateTagsInfo, syncTagsInfoForEditor]);
  373. // initialize
  374. useEffect(() => {
  375. if (initialValue == null) {
  376. return;
  377. }
  378. markdownToSave.current = initialValue;
  379. setMarkdownToPreview(initialValue);
  380. mutateIsEnabledUnsavedWarning(false);
  381. }, [initialValue, mutateIsEnabledUnsavedWarning]);
  382. // initial caret line
  383. useEffect(() => {
  384. if (editorRef.current != null) {
  385. editorRef.current.setCaretLine(0);
  386. }
  387. }, []);
  388. // set handler to set caret line
  389. useEffect(() => {
  390. const handler = (line) => {
  391. if (editorRef.current != null) {
  392. editorRef.current.setCaretLine(line);
  393. }
  394. if (previewRef.current != null) {
  395. scrollSyncHelper.scrollPreview(previewRef.current, line);
  396. }
  397. };
  398. globalEmitter.on('setCaretLine', handler);
  399. return function cleanup() {
  400. globalEmitter.removeListener('setCaretLine', handler);
  401. };
  402. }, []);
  403. // set handler to save and return to View
  404. useEffect(() => {
  405. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  406. return function cleanup() {
  407. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  408. };
  409. }, [saveAndReturnToViewHandler]);
  410. // set handler to focus
  411. useEffect(() => {
  412. if (editorRef.current != null && editorMode === EditorMode.Editor) {
  413. editorRef.current.forceToFocus();
  414. }
  415. }, [editorMode]);
  416. // Detect indent size from contents (only when users are allowed to change it)
  417. useEffect(() => {
  418. // do nothing if the indent size fixed
  419. if (isIndentSizeForced == null || isIndentSizeForced) {
  420. return;
  421. }
  422. // detect from markdown
  423. if (initialValue != null) {
  424. const detectedIndent = detectIndent(initialValue);
  425. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  426. mutateCurrentIndentSize(detectedIndent.amount);
  427. }
  428. }
  429. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  430. if (!isEditable) {
  431. return <></>;
  432. }
  433. if (rendererOptions == null) {
  434. return <></>;
  435. }
  436. const isUploadable = isUploadableImage || isUploadableFile;
  437. return (
  438. <div className="d-flex flex-wrap">
  439. <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
  440. <Editor
  441. ref={editorRef}
  442. value={initialValue}
  443. isUploadable={isUploadable}
  444. isUploadableFile={isUploadableFile}
  445. isTextlintEnabled={isTextlintEnabled}
  446. indentSize={currentIndentSize}
  447. onScroll={editorScrolledHandler}
  448. onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
  449. onChange={markdownChangedHandler}
  450. onUpload={uploadHandler}
  451. onSave={saveWithShortcut}
  452. />
  453. </div>
  454. <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
  455. <Preview
  456. ref={previewRef}
  457. rendererOptions={rendererOptions}
  458. markdown={markdownToPreview}
  459. pagePath={currentPagePath}
  460. onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)}
  461. />
  462. </div>
  463. <ConflictDiffModal
  464. isOpen={conflictDiffModalStatus?.isOpened}
  465. onClose={() => closeConflictDiffModal()}
  466. markdownOnEdit={markdownToPreview}
  467. optionsToSave={optionsToSave}
  468. afterResolvedHandler={afterResolvedHandler}
  469. />
  470. </div>
  471. );
  472. });
  473. PageEditor.displayName = 'PageEditor';
  474. export default PageEditor;