CommentEditor.tsx 12 KB

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