CommentEditor.tsx 12 KB

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