PageEditor.tsx 15 KB

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