PageEditor.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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, mutate: mutateCurrentPageId } = 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: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
  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 { data: rendererOptions, mutate: mutateRendererOptions } = usePreviewOptions();
  78. const { mutate: mutateIsEnabledUnsavedWarning } = useIsEnabledUnsavedWarning();
  79. const saveOrUpdate = useSaveOrUpdate();
  80. const updateStateAfterSave = useUpdateStateAfterSave();
  81. const currentRevisionId = currentPage?.revision?._id;
  82. const initialValue = useMemo(() => {
  83. if (!isNotFound) {
  84. return editingMarkdown ?? '';
  85. }
  86. let initialValue = '';
  87. if (isEnabledAttachTitleHeader && currentPathname != null) {
  88. initialValue += `${pathUtils.attachTitleHeader(currentPathname)}\n`;
  89. }
  90. if (templateBodyData != null) {
  91. initialValue += `${templateBodyData}\n`;
  92. }
  93. return initialValue;
  94. }, [isNotFound, currentPathname, editingMarkdown, isEnabledAttachTitleHeader, templateBodyData]);
  95. const markdownToSave = useRef<string>(initialValue);
  96. const [markdownToPreview, setMarkdownToPreview] = useState<string>(initialValue);
  97. const slackChannels = useMemo(() => (slackChannelsData ? slackChannelsData.toString() : ''), [slackChannelsData]);
  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(() => {
  119. // if (grantData == null) {
  120. // return;
  121. // }
  122. // const slackChannels = slackChannelsData ? slackChannelsData.toString() : '';
  123. // const optionsToSave = getOptionsToSave(
  124. // isSlackEnabled ?? false, slackChannels,
  125. // grantData.grant, grantData.grantedGroup?.id, grantData.grantedGroup?.name,
  126. // pageTags || [],
  127. // );
  128. // return optionsToSave;
  129. // }, [grantData, isSlackEnabled, pageTags, slackChannelsData]);
  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?: {overwriteScopesOfDescendants: boolean}): Promise<IPageHasId | null> => {
  151. if (grantData == null || isSlackEnabled == null || currentPathname == 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 grant = grantData.grant || PageGrant.GRANT_PUBLIC;
  156. const grantedGroup = grantData?.grantedGroup;
  157. const optionsToSave: OptionsToSave = {
  158. isSlackEnabled,
  159. slackChannels,
  160. grant: grant || 1,
  161. pageTags: pageTags || [],
  162. grantUserGroupId: grantedGroup?.id,
  163. grantUserGroupName: grantedGroup?.name,
  164. ...opts,
  165. };
  166. try {
  167. const { page } = await saveOrUpdate(
  168. markdownToSave.current,
  169. { pageId, path: currentPagePath || currentPathname, revisionId: currentRevisionId },
  170. optionsToSave,
  171. );
  172. return page;
  173. }
  174. catch (error) {
  175. logger.error('failed to save', error);
  176. toastError(error);
  177. if (error.code === 'conflict') {
  178. // pageContainer.setState({
  179. // remoteRevisionId: error.data.revisionId,
  180. // remoteRevisionBody: error.data.revisionBody,
  181. // remoteRevisionUpdateAt: error.data.createdAt,
  182. // lastUpdateUser: error.data.user,
  183. // });
  184. }
  185. return null;
  186. }
  187. // eslint-disable-next-line max-len
  188. }, [grantData, isSlackEnabled, currentPathname, slackChannels, pageTags, saveOrUpdate, pageId, currentPagePath, currentRevisionId]);
  189. const saveAndReturnToViewHandler = useCallback(async(opts?: {overwriteScopesOfDescendants: boolean}) => {
  190. if (editorMode !== EditorMode.Editor) {
  191. return;
  192. }
  193. const page = await save(opts);
  194. if (page == null) {
  195. return;
  196. }
  197. if (isNotFound) {
  198. await router.push(`/${page._id}`);
  199. }
  200. else {
  201. updateStateAfterSave(page._id);
  202. }
  203. mutateEditorMode(EditorMode.View);
  204. }, [editorMode, save, isNotFound, mutateEditorMode, router, useUpdateStateAfterSave]);
  205. const saveWithShortcut = useCallback(async() => {
  206. if (editorMode !== EditorMode.Editor) {
  207. return;
  208. }
  209. const page = await save();
  210. if (page != null) {
  211. updateStateAfterSave(page._id);
  212. toastSuccess(t('toaster.save_succeeded'));
  213. }
  214. }, [editorMode, save, t, useUpdateStateAfterSave]);
  215. /**
  216. * the upload event handler
  217. * @param {any} file
  218. */
  219. const uploadHandler = useCallback(async(file) => {
  220. if (editorRef.current == null) {
  221. return;
  222. }
  223. try {
  224. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  225. let res: any = await apiGet('/attachments.limit', {
  226. fileSize: file.size,
  227. });
  228. if (!res.isUploadable) {
  229. throw new Error(res.errorMessage);
  230. }
  231. const formData = new FormData();
  232. // const { pageId, path } = pageContainer.state;
  233. formData.append('file', file);
  234. if (currentPagePath != null) {
  235. formData.append('path', currentPagePath);
  236. }
  237. if (pageId != null) {
  238. formData.append('page_id', pageId);
  239. }
  240. res = await apiPostForm('/attachments.add', formData);
  241. const attachment = res.attachment;
  242. const fileName = attachment.originalName;
  243. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  244. // when image
  245. if (attachment.fileFormat.startsWith('image/')) {
  246. // modify to "![fileName](url)" syntax
  247. insertText = `!${insertText}`;
  248. }
  249. editorRef.current.insertText(insertText);
  250. // when if created newly
  251. if (res.pageCreated) {
  252. logger.info('Page is created', res.page._id);
  253. globalEmitter.emit('resetInitializedHackMdStatus');
  254. mutateGrant(res.page.grant);
  255. }
  256. }
  257. catch (e) {
  258. logger.error('failed to upload', e);
  259. toastError(e);
  260. }
  261. finally {
  262. editorRef.current.terminateUploadingState();
  263. }
  264. }, [currentPagePath, mutateGrant, pageId]);
  265. const scrollPreviewByEditorLine = useCallback((line: number) => {
  266. if (previewRef.current == null) {
  267. return;
  268. }
  269. // prevent circular invocation
  270. if (isOriginOfScrollSyncPreview) {
  271. isOriginOfScrollSyncPreview = false; // turn off the flag
  272. return;
  273. }
  274. // turn on the flag
  275. isOriginOfScrollSyncEditor = true;
  276. scrollSyncHelper.scrollPreview(previewRef.current, line);
  277. }, []);
  278. const scrollPreviewByEditorLineWithThrottle = useMemo(() => throttle(20, scrollPreviewByEditorLine), [scrollPreviewByEditorLine]);
  279. /**
  280. * the scroll event handler from codemirror
  281. * @param {any} data {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position,
  282. * the size of the scrollable area, and the size of the visible area (minus scrollbars).
  283. * And data.line is also available that is added by Editor component
  284. * @see https://codemirror.net/doc/manual.html#events
  285. */
  286. const editorScrolledHandler = useCallback(({ line }: { line: number }) => {
  287. // prevent scrolling
  288. // if the elapsed time from last scroll with cursor is shorter than 40ms
  289. const now = new Date();
  290. if (lastScrolledDateWithCursor != null && now.getTime() - lastScrolledDateWithCursor.getTime() < 40) {
  291. return;
  292. }
  293. scrollPreviewByEditorLineWithThrottle(line);
  294. }, [scrollPreviewByEditorLineWithThrottle]);
  295. /**
  296. * scroll Preview element by cursor moving
  297. * @param {number} line
  298. */
  299. const scrollPreviewByCursorMoving = useCallback((line: number) => {
  300. if (previewRef.current == null) {
  301. return;
  302. }
  303. // prevent circular invocation
  304. if (isOriginOfScrollSyncPreview) {
  305. isOriginOfScrollSyncPreview = false; // turn off the flag
  306. return;
  307. }
  308. // turn on the flag
  309. isOriginOfScrollSyncEditor = true;
  310. if (previewRef.current != null) {
  311. scrollSyncHelper.scrollPreviewToRevealOverflowing(previewRef.current, line);
  312. }
  313. }, []);
  314. const scrollPreviewByCursorMovingWithThrottle = useMemo(() => throttle(20, scrollPreviewByCursorMoving), [scrollPreviewByCursorMoving]);
  315. /**
  316. * the scroll event handler from codemirror
  317. * @param {number} line
  318. * @see https://codemirror.net/doc/manual.html#events
  319. */
  320. const editorScrollCursorIntoViewHandler = useCallback((line: number) => {
  321. // record date
  322. lastScrolledDateWithCursor = new Date();
  323. scrollPreviewByCursorMovingWithThrottle(line);
  324. }, [scrollPreviewByCursorMovingWithThrottle]);
  325. /**
  326. * scroll Editor component by scroll event of Preview component
  327. * @param {number} offset
  328. */
  329. const scrollEditorByPreviewScroll = useCallback((offset: number) => {
  330. if (editorRef.current == null || previewRef.current == null) {
  331. return;
  332. }
  333. // prevent circular invocation
  334. if (isOriginOfScrollSyncEditor) {
  335. isOriginOfScrollSyncEditor = false; // turn off the flag
  336. return;
  337. }
  338. // turn on the flag
  339. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  340. isOriginOfScrollSyncPreview = true;
  341. scrollSyncHelper.scrollEditor(editorRef.current, previewRef.current, offset);
  342. }, []);
  343. const scrollEditorByPreviewScrollWithThrottle = useMemo(() => throttle(20, scrollEditorByPreviewScroll), [scrollEditorByPreviewScroll]);
  344. const afterResolvedHandler = useCallback(async() => {
  345. // get page data from db
  346. const pageData = await mutateCurrentPage();
  347. // update tag
  348. await mutateTagsInfo(); // get from DB
  349. syncTagsInfoForEditor(); // sync global state for client
  350. // clear isConflict
  351. mutateIsConflict(false);
  352. // set resolved markdown in editing markdown
  353. const markdown = pageData?.revision.body ?? '';
  354. mutateEditingMarkdown(markdown);
  355. }, [mutateCurrentPage, mutateEditingMarkdown, mutateIsConflict, mutateTagsInfo, syncTagsInfoForEditor]);
  356. // initialize
  357. useEffect(() => {
  358. if (initialValue == null) {
  359. return;
  360. }
  361. markdownToSave.current = initialValue;
  362. setMarkdownToPreview(initialValue);
  363. mutateIsEnabledUnsavedWarning(false);
  364. }, [initialValue, mutateIsEnabledUnsavedWarning]);
  365. // initial caret line
  366. useEffect(() => {
  367. if (editorRef.current != null) {
  368. editorRef.current.setCaretLine(0);
  369. }
  370. }, []);
  371. // set handler to set caret line
  372. useEffect(() => {
  373. const handler = (line) => {
  374. if (editorRef.current != null) {
  375. editorRef.current.setCaretLine(line);
  376. }
  377. if (previewRef.current != null) {
  378. scrollSyncHelper.scrollPreview(previewRef.current, line);
  379. }
  380. };
  381. globalEmitter.on('setCaretLine', handler);
  382. return function cleanup() {
  383. globalEmitter.removeListener('setCaretLine', handler);
  384. };
  385. }, []);
  386. // set handler to save and return to View
  387. useEffect(() => {
  388. globalEmitter.on('saveAndReturnToView', saveAndReturnToViewHandler);
  389. return function cleanup() {
  390. globalEmitter.removeListener('saveAndReturnToView', saveAndReturnToViewHandler);
  391. };
  392. }, [saveAndReturnToViewHandler]);
  393. // set handler to focus
  394. useEffect(() => {
  395. if (editorRef.current != null && editorMode === EditorMode.Editor) {
  396. editorRef.current.forceToFocus();
  397. }
  398. }, [editorMode]);
  399. // Detect indent size from contents (only when users are allowed to change it)
  400. useEffect(() => {
  401. // do nothing if the indent size fixed
  402. if (isIndentSizeForced == null || isIndentSizeForced) {
  403. return;
  404. }
  405. // detect from markdown
  406. if (initialValue != null) {
  407. const detectedIndent = detectIndent(initialValue);
  408. if (detectedIndent.type === 'space' && new Set([2, 4]).has(detectedIndent.amount)) {
  409. mutateCurrentIndentSize(detectedIndent.amount);
  410. }
  411. }
  412. }, [initialValue, isIndentSizeForced, mutateCurrentIndentSize]);
  413. if (!isEditable) {
  414. return <></>;
  415. }
  416. if (rendererOptions == null) {
  417. return <></>;
  418. }
  419. const isUploadable = isUploadableImage || isUploadableFile;
  420. return (
  421. <div className="d-flex flex-wrap">
  422. <div className="page-editor-editor-container flex-grow-1 flex-basis-0 mw-0">
  423. <Editor
  424. ref={editorRef}
  425. value={initialValue}
  426. isUploadable={isUploadable}
  427. isUploadableFile={isUploadableFile}
  428. isTextlintEnabled={isTextlintEnabled}
  429. indentSize={currentIndentSize}
  430. onScroll={editorScrolledHandler}
  431. onScrollCursorIntoView={editorScrollCursorIntoViewHandler}
  432. onChange={markdownChangedHandler}
  433. onUpload={uploadHandler}
  434. onSave={saveWithShortcut}
  435. />
  436. </div>
  437. <div className="d-none d-lg-block page-editor-preview-container flex-grow-1 flex-basis-0 mw-0">
  438. <Preview
  439. ref={previewRef}
  440. rendererOptions={rendererOptions}
  441. markdown={markdownToPreview}
  442. pagePath={currentPagePath}
  443. onScroll={offset => scrollEditorByPreviewScrollWithThrottle(offset)}
  444. />
  445. </div>
  446. <ConflictDiffModal
  447. isOpen={conflictDiffModalStatus?.isOpened}
  448. onClose={() => closeConflictDiffModal()}
  449. markdownOnEdit={markdownToPreview}
  450. optionsToSave={undefined} // replace undefined
  451. afterResolvedHandler={afterResolvedHandler}
  452. />
  453. </div>
  454. );
  455. });
  456. PageEditor.displayName = 'PageEditor';
  457. export default PageEditor;