CommentEditor.tsx 12 KB

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