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