CommentEditor.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import type { ReactNode, JSX } from 'react';
  2. import React, {
  3. useCallback, useState, useEffect, useLayoutEffect,
  4. useMemo,
  5. } from 'react';
  6. import { GlobalCodeMirrorEditorKey, useResolvedThemeActions } 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 { UserPicture } from '@growi/ui/dist/components';
  10. import { useAtomValue } from 'jotai';
  11. import { useTranslation } from 'next-i18next';
  12. import dynamic from 'next/dynamic';
  13. import {
  14. TabContent, TabPane,
  15. } from 'reactstrap';
  16. import { uploadAttachments } from '~/client/services/upload-attachments';
  17. import { toastError } from '~/client/util/toastr';
  18. import { useCurrentUser } from '~/states/global';
  19. import { useCurrentPagePath } from '~/states/page';
  20. import { isSlackConfiguredAtom, useAcceptedUploadFileType } from '~/states/server-configurations';
  21. import { useIsSlackEnabled } from '~/states/ui/editor';
  22. import { useCommentEditorsDirtyMap } from '~/states/ui/unsaved-warning';
  23. import { useNextThemes } from '~/stores-universal/use-next-themes';
  24. import { useSWRxPageComment } from '~/stores/comment';
  25. import { useSWRxSlackChannels, useEditorSettings } from '~/stores/editor';
  26. import loggerFactory from '~/utils/logger';
  27. import { NotAvailableForGuest } from '../NotAvailableForGuest';
  28. import { NotAvailableIfReadOnlyUserNotAllowedToComment } 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. const CommentEditorLayout = ({ children }: { children: ReactNode }): JSX.Element => {
  36. return (
  37. <div className={`${styles['comment-editor-styles']} form`}>
  38. <div className="comment-form">
  39. <div className="bg-comment rounded">
  40. {children}
  41. </div>
  42. </div>
  43. </div>
  44. );
  45. };
  46. type CommentEditorProps = {
  47. pageId: string,
  48. replyTo?: string,
  49. revisionId: string,
  50. currentCommentId?: string,
  51. commentBody?: string,
  52. onCanceled?: () => void,
  53. onCommented?: () => void,
  54. }
  55. export const CommentEditor = (props: CommentEditorProps): JSX.Element => {
  56. const {
  57. pageId, replyTo, revisionId,
  58. currentCommentId, commentBody, onCanceled, onCommented,
  59. } = props;
  60. const currentUser = useCurrentUser();
  61. const currentPagePath = useCurrentPagePath();
  62. const { update: updateComment, post: postComment } = useSWRxPageComment(pageId);
  63. const [isSlackEnabled, setIsSlackEnabled] = useIsSlackEnabled();
  64. const acceptedUploadFileType = useAcceptedUploadFileType();
  65. const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
  66. const isSlackConfigured = useAtomValue(isSlackConfiguredAtom);
  67. const { data: editorSettings } = useEditorSettings();
  68. const { markDirty, markClean } = useCommentEditorsDirtyMap();
  69. const { mutateResolvedTheme } = useResolvedThemeActions();
  70. const { resolvedTheme } = useNextThemes();
  71. mutateResolvedTheme(resolvedTheme);
  72. const editorKey = useMemo(() => {
  73. if (replyTo != null) {
  74. return `comment_replyTo_${replyTo}`;
  75. }
  76. if (currentCommentId != null) {
  77. return `comment_edit_${currentCommentId}`;
  78. }
  79. return GlobalCodeMirrorEditorKey.COMMENT_NEW;
  80. }, [currentCommentId, replyTo]);
  81. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(editorKey);
  82. const [showPreview, setShowPreview] = useState(false);
  83. const [error, setError] = useState();
  84. const [slackChannels, setSlackChannels] = useState<string>('');
  85. const { t } = useTranslation('');
  86. const handleSelect = useCallback((showPreview: boolean) => {
  87. setShowPreview(showPreview);
  88. }, []);
  89. // DO NOT dependent on slackChannelsData directly: https://github.com/growilabs/growi/pull/7332
  90. const slackChannelsDataString = slackChannelsData?.toString();
  91. const initializeSlackEnabled = useCallback(() => {
  92. setSlackChannels(slackChannelsDataString ?? '');
  93. setIsSlackEnabled(false);
  94. }, [setIsSlackEnabled, slackChannelsDataString]);
  95. useEffect(() => {
  96. initializeSlackEnabled();
  97. }, [initializeSlackEnabled]);
  98. const isSlackEnabledToggleHandler = (isSlackEnabled: boolean) => {
  99. setIsSlackEnabled(isSlackEnabled);
  100. };
  101. const slackChannelsChangedHandler = useCallback((slackChannels: string) => {
  102. setSlackChannels(slackChannels);
  103. }, []);
  104. const initializeEditor = useCallback(() => {
  105. markClean(editorKey);
  106. setShowPreview(false);
  107. setError(undefined);
  108. initializeSlackEnabled();
  109. }, [editorKey, markClean, initializeSlackEnabled]);
  110. const cancelButtonClickedHandler = useCallback(() => {
  111. initializeEditor();
  112. onCanceled?.();
  113. }, [onCanceled, initializeEditor]);
  114. const postCommentHandler = useCallback(async () => {
  115. const commentBodyToPost = codeMirrorEditor?.getDocString() ?? '';
  116. try {
  117. if (currentCommentId != null) {
  118. // update current comment
  119. await updateComment(commentBodyToPost, revisionId, currentCommentId);
  120. }
  121. else {
  122. // post new comment
  123. const postCommentArgs = {
  124. commentForm: {
  125. comment: commentBodyToPost,
  126. revisionId,
  127. replyTo,
  128. },
  129. slackNotificationForm: {
  130. isSlackEnabled,
  131. slackChannels,
  132. },
  133. };
  134. await postComment(postCommentArgs);
  135. }
  136. initializeEditor();
  137. onCommented?.();
  138. // Insert empty string as new comment editor is opened after comment
  139. codeMirrorEditor?.initDoc('');
  140. }
  141. catch (err) {
  142. const errorMessage = err.message || 'An unknown error occured when posting comment';
  143. setError(errorMessage);
  144. }
  145. // eslint-disable-next-line max-len
  146. }, [currentCommentId, initializeEditor, onCommented, codeMirrorEditor, updateComment, revisionId, replyTo, isSlackEnabled, slackChannels, postComment]);
  147. // the upload event handler
  148. const uploadHandler = useCallback((files: File[]) => {
  149. uploadAttachments(pageId, files, {
  150. onUploaded: (attachment) => {
  151. const fileName = attachment.originalName;
  152. const prefix = attachment.fileFormat.startsWith('image/')
  153. ? '!' // use "![fileName](url)" syntax when image
  154. : '';
  155. const insertText = `${prefix}[${fileName}](${attachment.filePathProxied})\n`;
  156. codeMirrorEditor?.insertText(insertText);
  157. },
  158. onError: (error) => {
  159. toastError(error);
  160. },
  161. });
  162. }, [codeMirrorEditor, pageId]);
  163. const cmProps = useMemo(() => ({
  164. onChange: (value: string) => {
  165. markDirty(editorKey, value);
  166. },
  167. }), [editorKey, markDirty]);
  168. // initialize CodeMirrorEditor
  169. useEffect(() => {
  170. if (commentBody == null) {
  171. return;
  172. }
  173. codeMirrorEditor?.initDoc(commentBody);
  174. }, [codeMirrorEditor, commentBody]);
  175. // set handler to focus
  176. useLayoutEffect(() => {
  177. if (showPreview) return;
  178. codeMirrorEditor?.focus();
  179. }, [codeMirrorEditor, showPreview]);
  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. onSave={postCommentHandler}
  218. onUpload={uploadHandler}
  219. editorSettings={editorSettings}
  220. cmProps={cmProps}
  221. />
  222. </TabPane>
  223. <TabPane tabId="comment_preview">
  224. <div className="comment-preview-container">
  225. <CommentPreview markdown={codeMirrorEditor?.getDocString() ?? ''} />
  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 { onCommented, onCanceled, ...rest } = props;
  263. const currentUser = useCurrentUser();
  264. const { mutateResolvedTheme } = useResolvedThemeActions();
  265. const { resolvedTheme } = useNextThemes();
  266. mutateResolvedTheme(resolvedTheme);
  267. const [isReadyToUse, setIsReadyToUse] = useState(false);
  268. const { t } = useTranslation('');
  269. const render = useCallback((): JSX.Element => {
  270. return (
  271. <CommentEditorLayout>
  272. <NotAvailableForGuest>
  273. <NotAvailableIfReadOnlyUserNotAllowedToComment>
  274. <button
  275. type="button"
  276. className="btn btn-outline-primary w-100 text-start py-3"
  277. onClick={() => setIsReadyToUse(true)}
  278. data-testid="open-comment-editor-button"
  279. >
  280. <UserPicture user={currentUser} noLink noTooltip className="me-3" />
  281. <span className="material-symbols-outlined me-1 fs-5">add_comment</span>
  282. <small>{t('page_comment.add_a_comment')}...</small>
  283. </button>
  284. </NotAvailableIfReadOnlyUserNotAllowedToComment>
  285. </NotAvailableForGuest>
  286. </CommentEditorLayout>
  287. );
  288. }, [currentUser, t]);
  289. return isReadyToUse
  290. ? (
  291. <CommentEditor
  292. onCommented={() => {
  293. onCommented?.();
  294. setIsReadyToUse(false);
  295. }}
  296. onCanceled={() => {
  297. onCanceled?.();
  298. setIsReadyToUse(false);
  299. }}
  300. {...rest}
  301. />
  302. )
  303. : render();
  304. };