PageEditor.tsx 15 KB

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