CommentEditor.tsx 12 KB

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