PageEditor.tsx 17 KB

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