PageEditor.tsx 15 KB

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