CommentEditor.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. import React, {
  2. useCallback, useState, useRef, useEffect,
  3. } from 'react';
  4. import {
  5. CodeMirrorEditorComment, GlobalCodeMirrorEditorKey, useCodeMirrorEditorIsolated, useResolvedThemeForEditor,
  6. } from '@growi/editor';
  7. import { UserPicture } from '@growi/ui/dist/components';
  8. import dynamic from 'next/dynamic';
  9. import { useRouter } from 'next/router';
  10. import {
  11. Button, TabContent, TabPane,
  12. } from 'reactstrap';
  13. import { apiv3Get, apiv3PostForm } from '~/client/util/apiv3-client';
  14. import { toastError } from '~/client/util/toastr';
  15. import type { IEditorMethods } from '~/interfaces/editor-methods';
  16. import { useSWRxPageComment, useSWRxEditingCommentsNum } from '~/stores/comment';
  17. import {
  18. useCurrentUser, useIsSlackConfigured, useAcceptedUploadFileType,
  19. } from '~/stores/context';
  20. import {
  21. useSWRxSlackChannels, useIsSlackEnabled, useIsEnabledUnsavedWarning,
  22. } from '~/stores/editor';
  23. import { useCurrentPagePath } from '~/stores/page';
  24. import { useNextThemes } from '~/stores/use-next-themes';
  25. import loggerFactory from '~/utils/logger';
  26. import { CustomNavTab } from '../CustomNavigation/CustomNav';
  27. import { NotAvailableForGuest } from '../NotAvailableForGuest';
  28. import { NotAvailableForReadOnlyUser } from '../NotAvailableForReadOnlyUser';
  29. import { CommentPreview } from './CommentPreview';
  30. import '@growi/editor/dist/style.css';
  31. import styles from './CommentEditor.module.scss';
  32. const logger = loggerFactory('growi:components:CommentEditor');
  33. const SlackNotification = dynamic(() => import('../SlackNotification').then(mod => mod.SlackNotification), { ssr: false });
  34. const navTabMapping = {
  35. comment_editor: {
  36. Icon: () => <span className="material-symbols-outlined">edit_square</span>,
  37. i18n: 'Write',
  38. },
  39. comment_preview: {
  40. Icon: () => <span className="material-symbols-outlined">play_arrow</span>,
  41. i18n: 'Preview',
  42. },
  43. };
  44. export type CommentEditorProps = {
  45. pageId: string,
  46. isForNewComment?: boolean,
  47. replyTo?: string,
  48. revisionId: string,
  49. currentCommentId?: string,
  50. commentBody?: string,
  51. onCancelButtonClicked?: () => void,
  52. onCommentButtonClicked?: () => void,
  53. }
  54. export const CommentEditor = (props: CommentEditorProps): JSX.Element => {
  55. const {
  56. pageId, isForNewComment, replyTo, revisionId,
  57. currentCommentId, commentBody, onCancelButtonClicked, onCommentButtonClicked,
  58. } = props;
  59. const { data: currentUser } = useCurrentUser();
  60. const { data: currentPagePath } = useCurrentPagePath();
  61. const { update: updateComment, post: postComment } = useSWRxPageComment(pageId);
  62. const { data: isSlackEnabled, mutate: mutateIsSlackEnabled } = useIsSlackEnabled();
  63. const { data: acceptedUploadFileType } = useAcceptedUploadFileType();
  64. const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
  65. const { data: isSlackConfigured } = useIsSlackConfigured();
  66. const { mutate: mutateIsEnabledUnsavedWarning } = useIsEnabledUnsavedWarning();
  67. const {
  68. increment: incrementEditingCommentsNum,
  69. decrement: decrementEditingCommentsNum,
  70. } = useSWRxEditingCommentsNum();
  71. const { mutate: mutateResolvedTheme } = useResolvedThemeForEditor();
  72. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.COMMENT);
  73. const { resolvedTheme } = useNextThemes();
  74. mutateResolvedTheme({ themeData: resolvedTheme });
  75. const [isReadyToUse, setIsReadyToUse] = useState(!isForNewComment);
  76. const [comment, setComment] = useState(commentBody ?? '');
  77. const [activeTab, setActiveTab] = useState('comment_editor');
  78. const [error, setError] = useState();
  79. const [slackChannels, setSlackChannels] = useState<string>('');
  80. const [incremented, setIncremented] = useState(false);
  81. const editorRef = useRef<IEditorMethods>(null);
  82. const router = useRouter();
  83. // UnControlled CodeMirror value is not reset on page transition, so explicitly set the value to the initial value
  84. const onRouterChangeComplete = useCallback(() => {
  85. editorRef.current?.setValue('');
  86. }, []);
  87. useEffect(() => {
  88. router.events.on('routeChangeComplete', onRouterChangeComplete);
  89. return () => {
  90. router.events.off('routeChangeComplete', onRouterChangeComplete);
  91. };
  92. }, [onRouterChangeComplete, router.events]);
  93. const handleSelect = useCallback((activeTab: string) => {
  94. setActiveTab(activeTab);
  95. }, []);
  96. // DO NOT dependent on slackChannelsData directly: https://github.com/weseek/growi/pull/7332
  97. const slackChannelsDataString = slackChannelsData?.toString();
  98. const initializeSlackEnabled = useCallback(() => {
  99. setSlackChannels(slackChannelsDataString ?? '');
  100. mutateIsSlackEnabled(false);
  101. }, [mutateIsSlackEnabled, slackChannelsDataString]);
  102. useEffect(() => {
  103. initializeSlackEnabled();
  104. }, [initializeSlackEnabled]);
  105. const isSlackEnabledToggleHandler = (isSlackEnabled: boolean) => {
  106. mutateIsSlackEnabled(isSlackEnabled, false);
  107. };
  108. const slackChannelsChangedHandler = useCallback((slackChannels: string) => {
  109. setSlackChannels(slackChannels);
  110. }, []);
  111. const initializeEditor = useCallback(async() => {
  112. const editingCommentsNum = comment !== '' ? await decrementEditingCommentsNum() : undefined;
  113. setComment('');
  114. setActiveTab('comment_editor');
  115. setError(undefined);
  116. initializeSlackEnabled();
  117. // reset value
  118. if (editorRef.current == null) { return }
  119. editorRef.current.setValue('');
  120. if (editingCommentsNum != null && editingCommentsNum === 0) {
  121. mutateIsEnabledUnsavedWarning(false); // must be after clearing comment or else onChange will override bool
  122. }
  123. }, [initializeSlackEnabled, comment, decrementEditingCommentsNum, mutateIsEnabledUnsavedWarning]);
  124. const cancelButtonClickedHandler = useCallback(() => {
  125. // change state to not ready
  126. // when this editor is for the new comment mode
  127. if (isForNewComment) {
  128. setIsReadyToUse(false);
  129. }
  130. initializeEditor();
  131. if (onCancelButtonClicked != null) {
  132. onCancelButtonClicked();
  133. }
  134. }, [isForNewComment, onCancelButtonClicked, initializeEditor]);
  135. const postCommentHandler = useCallback(async() => {
  136. try {
  137. if (currentCommentId != null) {
  138. // update current comment
  139. await updateComment(comment, revisionId, currentCommentId);
  140. }
  141. else {
  142. // post new comment
  143. const postCommentArgs = {
  144. commentForm: {
  145. comment,
  146. revisionId,
  147. replyTo,
  148. },
  149. slackNotificationForm: {
  150. isSlackEnabled,
  151. slackChannels,
  152. },
  153. };
  154. await postComment(postCommentArgs);
  155. }
  156. initializeEditor();
  157. if (onCommentButtonClicked != null) {
  158. onCommentButtonClicked();
  159. }
  160. // Insert empty string as new comment editor is opened after comment
  161. codeMirrorEditor?.initDoc('');
  162. }
  163. catch (err) {
  164. const errorMessage = err.message || 'An unknown error occured when posting comment';
  165. setError(errorMessage);
  166. }
  167. }, [
  168. currentCommentId, initializeEditor, onCommentButtonClicked, codeMirrorEditor,
  169. updateComment, comment, revisionId, replyTo, isSlackEnabled, slackChannels, postComment,
  170. ]);
  171. // the upload event handler
  172. const uploadHandler = useCallback((files: File[]) => {
  173. files.forEach(async(file) => {
  174. try {
  175. const { data: resLimit } = await apiv3Get('/attachment/limit', { fileSize: file.size });
  176. if (!resLimit.isUploadable) {
  177. throw new Error(resLimit.errorMessage);
  178. }
  179. const formData = new FormData();
  180. formData.append('file', file);
  181. if (pageId != null) {
  182. formData.append('page_id', pageId);
  183. }
  184. const { data: resAdd } = await apiv3PostForm('/attachment', formData);
  185. const attachment = resAdd.attachment;
  186. const fileName = attachment.originalName;
  187. let insertText = `[${fileName}](${attachment.filePathProxied})\n`;
  188. // when image
  189. if (attachment.fileFormat.startsWith('image/')) {
  190. // modify to "![fileName](url)" syntax
  191. insertText = `!${insertText}`;
  192. }
  193. codeMirrorEditor?.insertText(insertText);
  194. }
  195. catch (e) {
  196. logger.error('failed to upload', e);
  197. toastError(e);
  198. }
  199. });
  200. }, [codeMirrorEditor, pageId]);
  201. const getCommentHtml = useCallback(() => {
  202. if (currentPagePath == null) {
  203. return <></>;
  204. }
  205. return <CommentPreview markdown={comment} />;
  206. }, [currentPagePath, comment]);
  207. const renderBeforeReady = useCallback((): JSX.Element => {
  208. return (
  209. <div className="text-center">
  210. <NotAvailableForGuest>
  211. <NotAvailableForReadOnlyUser>
  212. <button
  213. type="button"
  214. className="btn btn-lg btn-link"
  215. onClick={() => setIsReadyToUse(true)}
  216. data-testid="open-comment-editor-button"
  217. >
  218. <span className="material-symbols-outlined">comment</span> Add Comment
  219. </button>
  220. </NotAvailableForReadOnlyUser>
  221. </NotAvailableForGuest>
  222. </div>
  223. );
  224. }, []);
  225. // const onChangeHandler = useCallback((newValue: string, isClean: boolean) => {
  226. // setComment(newValue);
  227. // if (!isClean && !incremented) {
  228. // incrementEditingCommentsNum();
  229. // setIncremented(true);
  230. // }
  231. // mutateIsEnabledUnsavedWarning(!isClean);
  232. // }, [mutateIsEnabledUnsavedWarning, incrementEditingCommentsNum, incremented]);
  233. const onChangeHandler = useCallback((newValue: string) => {
  234. setComment(newValue);
  235. if (!incremented) {
  236. incrementEditingCommentsNum();
  237. setIncremented(true);
  238. }
  239. }, [incrementEditingCommentsNum, incremented]);
  240. // initialize CodeMirrorEditor
  241. useEffect(() => {
  242. if (commentBody == null) {
  243. return;
  244. }
  245. codeMirrorEditor?.initDoc(commentBody);
  246. }, [codeMirrorEditor, commentBody]);
  247. const renderReady = () => {
  248. const commentPreview = getCommentHtml();
  249. const errorMessage = <span className="text-danger text-end me-2">{error}</span>;
  250. const cancelButton = (
  251. <Button
  252. outline
  253. color="danger"
  254. size="xs"
  255. className="btn btn-outline-danger rounded-pill"
  256. onClick={cancelButtonClickedHandler}
  257. >
  258. Cancel
  259. </Button>
  260. );
  261. const submitButton = (
  262. <Button
  263. data-testid="comment-submit-button"
  264. outline
  265. color="primary"
  266. className="btn btn-outline-primary rounded-pill"
  267. onClick={postCommentHandler}
  268. >
  269. Comment
  270. </Button>
  271. );
  272. return (
  273. <>
  274. <div className="comment-write">
  275. <CustomNavTab activeTab={activeTab} navTabMapping={navTabMapping} onNavSelected={handleSelect} hideBorderBottom />
  276. <TabContent activeTab={activeTab}>
  277. <TabPane tabId="comment_editor">
  278. <CodeMirrorEditorComment
  279. acceptedUploadFileType={acceptedUploadFileType}
  280. onChange={onChangeHandler}
  281. onSave={postCommentHandler}
  282. onUpload={uploadHandler}
  283. />
  284. {/* <Editor
  285. ref={editorRef}
  286. value={commentBody ?? ''} // DO NOT use state
  287. isUploadable={isUploadable}
  288. isUploadAllFileAllowed={isUploadAllFileAllowed}
  289. onChange={onChangeHandler}
  290. onUpload={uploadHandler}
  291. onCtrlEnter={ctrlEnterHandler}
  292. isComment
  293. /> */}
  294. {/*
  295. Note: <OptionsSelector /> is not optimized for ComentEditor in terms of responsive design.
  296. See a review comment in https://github.com/weseek/growi/pull/3473
  297. */}
  298. </TabPane>
  299. <TabPane tabId="comment_preview">
  300. <div className="comment-form-preview">
  301. {commentPreview}
  302. </div>
  303. </TabPane>
  304. </TabContent>
  305. </div>
  306. <div className="comment-submit">
  307. <div className="d-flex">
  308. <span className="flex-grow-1" />
  309. <span className="d-none d-sm-inline">{errorMessage && errorMessage}</span>
  310. {isSlackConfigured && isSlackEnabled != null
  311. && (
  312. <div className="align-self-center me-md-2">
  313. <SlackNotification
  314. isSlackEnabled={isSlackEnabled}
  315. slackChannels={slackChannels}
  316. onEnabledFlagChange={isSlackEnabledToggleHandler}
  317. onChannelChange={slackChannelsChangedHandler}
  318. id="idForComment"
  319. />
  320. </div>
  321. )
  322. }
  323. <div className="d-none d-sm-block">
  324. <span className="me-2">{cancelButton}</span><span>{submitButton}</span>
  325. </div>
  326. </div>
  327. <div className="d-block d-sm-none mt-2">
  328. <div className="d-flex justify-content-end">
  329. {error && errorMessage}
  330. <span className="me-2">{cancelButton}</span><span>{submitButton}</span>
  331. </div>
  332. </div>
  333. </div>
  334. </>
  335. );
  336. };
  337. return (
  338. <div className={`${styles['comment-editor-styles']} form page-comment-form`}>
  339. <div className="comment-form">
  340. <div className="comment-form-user">
  341. <UserPicture user={currentUser} noLink noTooltip />
  342. </div>
  343. <div className="comment-form-main">
  344. {isReadyToUse
  345. ? renderReady()
  346. : renderBeforeReady()
  347. }
  348. </div>
  349. </div>
  350. </div>
  351. );
  352. };