PageEditor.tsx 15 KB

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