PageEditor.tsx 14 KB

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