PageEditor.tsx 18 KB

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