PageEditor.tsx 15 KB

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