PageEditor.tsx 18 KB

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