CommentEditor.tsx 13 KB

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