PageEditor.tsx 18 KB

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