PageEditor.tsx 14 KB

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