PageEditor.tsx 17 KB

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