PageEditor.tsx 14 KB

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