CommentEditor.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import React, {
  2. useCallback, useState, useRef, useEffect,
  3. } from 'react';
  4. import { UserPicture } from '@growi/ui';
  5. import dynamic from 'next/dynamic';
  6. import {
  7. Button, TabContent, TabPane,
  8. } from 'reactstrap';
  9. import * as toastr from 'toastr';
  10. import { apiPostForm } from '~/client/util/apiv1-client';
  11. import { IEditorMethods } from '~/interfaces/editor-methods';
  12. import { useSWRxPageComment } from '~/stores/comment';
  13. import {
  14. useCurrentUser, useIsSlackConfigured,
  15. useIsUploadableFile, useIsUploadableImage,
  16. } from '~/stores/context';
  17. import { useSWRxSlackChannels, useIsSlackEnabled } from '~/stores/editor';
  18. import { useCurrentPagePath } from '~/stores/page';
  19. import { CustomNavTab } from '../CustomNavigation/CustomNav';
  20. import NotAvailableForGuest from '../NotAvailableForGuest';
  21. import Editor from '../PageEditor/Editor';
  22. import { CommentPreview } from './CommentPreview';
  23. import styles from './CommentEditor.module.scss';
  24. const SlackNotification = dynamic(() => import('../SlackNotification').then(mod => mod.SlackNotification), { ssr: false });
  25. const navTabMapping = {
  26. comment_editor: {
  27. Icon: () => <i className="icon-settings" />,
  28. i18n: 'Write',
  29. index: 0,
  30. },
  31. comment_preview: {
  32. Icon: () => <i className="icon-settings" />,
  33. i18n: 'Preview',
  34. index: 1,
  35. },
  36. };
  37. export type CommentEditorProps = {
  38. pageId: string,
  39. isForNewComment?: boolean,
  40. replyTo?: string,
  41. revisionId: string,
  42. currentCommentId?: string,
  43. commentBody?: string,
  44. onCancelButtonClicked?: () => void,
  45. onCommentButtonClicked?: () => void,
  46. }
  47. export const CommentEditor = (props: CommentEditorProps): JSX.Element => {
  48. const {
  49. pageId, isForNewComment, replyTo, revisionId,
  50. currentCommentId, commentBody, onCancelButtonClicked, onCommentButtonClicked,
  51. } = props;
  52. const { data: currentUser } = useCurrentUser();
  53. const { data: currentPagePath } = useCurrentPagePath();
  54. const { update: updateComment, post: postComment } = useSWRxPageComment(pageId);
  55. const { data: isSlackEnabled, mutate: mutateIsSlackEnabled } = useIsSlackEnabled();
  56. const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
  57. const { data: isSlackConfigured } = useIsSlackConfigured();
  58. const { data: isUploadableFile } = useIsUploadableFile();
  59. const { data: isUploadableImage } = useIsUploadableImage();
  60. const [isReadyToUse, setIsReadyToUse] = useState(!isForNewComment);
  61. const [comment, setComment] = useState(commentBody ?? '');
  62. const [activeTab, setActiveTab] = useState('comment_editor');
  63. const [error, setError] = useState();
  64. const [slackChannels, setSlackChannels] = useState<string>('');
  65. const editorRef = useRef<IEditorMethods>(null);
  66. const handleSelect = useCallback((activeTab: string) => {
  67. setActiveTab(activeTab);
  68. }, []);
  69. useEffect(() => {
  70. if (slackChannelsData != null) {
  71. setSlackChannels(slackChannelsData.toString());
  72. mutateIsSlackEnabled(false);
  73. }
  74. }, [mutateIsSlackEnabled, slackChannelsData]);
  75. const isSlackEnabledToggleHandler = (isSlackEnabled: boolean) => {
  76. mutateIsSlackEnabled(isSlackEnabled, false);
  77. };
  78. const slackChannelsChangedHandler = useCallback((slackChannels: string) => {
  79. setSlackChannels(slackChannels);
  80. }, []);
  81. const initializeEditor = useCallback(() => {
  82. setComment('');
  83. setActiveTab('comment_editor');
  84. setError(undefined);
  85. // reset value
  86. if (editorRef.current == null) { return }
  87. editorRef.current.setValue('');
  88. }, []);
  89. const cancelButtonClickedHandler = useCallback(() => {
  90. // change state to not ready
  91. // when this editor is for the new comment mode
  92. if (isForNewComment) {
  93. setIsReadyToUse(false);
  94. }
  95. if (onCancelButtonClicked != null) {
  96. onCancelButtonClicked();
  97. }
  98. }, [isForNewComment, onCancelButtonClicked]);
  99. const postCommentHandler = useCallback(async() => {
  100. try {
  101. if (currentCommentId != null) {
  102. // update current comment
  103. await updateComment(comment, revisionId, currentCommentId);
  104. }
  105. else {
  106. // post new comment
  107. const postCommentArgs = {
  108. commentForm: {
  109. comment,
  110. revisionId,
  111. replyTo,
  112. },
  113. slackNotificationForm: {
  114. isSlackEnabled,
  115. slackChannels,
  116. },
  117. };
  118. await postComment(postCommentArgs);
  119. }
  120. initializeEditor();
  121. if (onCommentButtonClicked != null) {
  122. onCommentButtonClicked();
  123. }
  124. }
  125. catch (err) {
  126. const errorMessage = err.message || 'An unknown error occured when posting comment';
  127. setError(errorMessage);
  128. }
  129. }, [
  130. comment, currentCommentId, initializeEditor,
  131. isSlackEnabled, onCommentButtonClicked, replyTo, slackChannels,
  132. postComment, revisionId, updateComment,
  133. ]);
  134. const ctrlEnterHandler = useCallback((event) => {
  135. if (event != null) {
  136. event.preventDefault();
  137. }
  138. postCommentHandler();
  139. }, [postCommentHandler]);
  140. const apiErrorHandler = useCallback((error: Error) => {
  141. toastr.error(error.message, 'Error occured', {
  142. closeButton: true,
  143. progressBar: true,
  144. newestOnTop: false,
  145. showDuration: '100',
  146. hideDuration: '100',
  147. timeOut: '3000',
  148. });
  149. }, []);
  150. const uploadHandler = useCallback(async(file) => {
  151. if (editorRef.current == null) { return }
  152. const pagePath = currentPagePath;
  153. const endpoint = '/attachments.add';
  154. const formData = new FormData();
  155. formData.append('file', file);
  156. formData.append('path', pagePath ?? '');
  157. formData.append('page_id', pageId ?? '');
  158. try {
  159. // TODO: typescriptize res
  160. const res = await apiPostForm(endpoint, formData) as any;
  161. const attachment = res.attachment;
  162. const fileName = attachment.originalName;
  163. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  164. // when image
  165. if (attachment.fileFormat.startsWith('image/')) {
  166. // modify to "![fileName](url)" syntax
  167. insertText = `!${insertText}`;
  168. }
  169. editorRef.current.insertText(insertText);
  170. }
  171. catch (err) {
  172. apiErrorHandler(err);
  173. }
  174. finally {
  175. editorRef.current.terminateUploadingState();
  176. }
  177. }, [apiErrorHandler, currentPagePath, pageId]);
  178. const getCommentHtml = useCallback(() => {
  179. if (currentPagePath == null) {
  180. return <></>;
  181. }
  182. return <CommentPreview markdown={comment} />;
  183. }, [currentPagePath, comment]);
  184. const renderBeforeReady = useCallback((): JSX.Element => {
  185. return (
  186. <div className="text-center">
  187. <NotAvailableForGuest>
  188. <button
  189. type="button"
  190. className="btn btn-lg btn-link"
  191. onClick={() => setIsReadyToUse(true)}
  192. >
  193. <i className="icon-bubble"></i> Add Comment
  194. </button>
  195. </NotAvailableForGuest>
  196. </div>
  197. );
  198. }, []);
  199. const onChangeHandler = useCallback((newValue: string) => setComment(newValue), []);
  200. const renderReady = () => {
  201. const commentPreview = getCommentHtml();
  202. const errorMessage = <span className="text-danger text-right mr-2">{error}</span>;
  203. const cancelButton = (
  204. <Button
  205. outline
  206. color="danger"
  207. size="xs"
  208. className="btn btn-outline-danger rounded-pill"
  209. onClick={cancelButtonClickedHandler}
  210. >
  211. Cancel
  212. </Button>
  213. );
  214. const submitButton = (
  215. <Button
  216. outline
  217. color="primary"
  218. className="btn btn-outline-primary rounded-pill"
  219. onClick={postCommentHandler}
  220. >
  221. Comment
  222. </Button>
  223. );
  224. const isUploadable = isUploadableImage || isUploadableFile;
  225. return (
  226. <>
  227. <div className="comment-write">
  228. <CustomNavTab activeTab={activeTab} navTabMapping={navTabMapping} onNavSelected={handleSelect} hideBorderBottom />
  229. <TabContent activeTab={activeTab}>
  230. <TabPane tabId="comment_editor">
  231. <Editor
  232. ref={editorRef}
  233. value={commentBody ?? ''} // DO NOT use state
  234. isUploadable={isUploadable}
  235. isUploadableFile={isUploadableFile}
  236. onChange={onChangeHandler}
  237. onUpload={uploadHandler}
  238. onCtrlEnter={ctrlEnterHandler}
  239. isComment
  240. />
  241. {/*
  242. Note: <OptionsSelector /> is not optimized for ComentEditor in terms of responsive design.
  243. See a review comment in https://github.com/weseek/growi/pull/3473
  244. */}
  245. </TabPane>
  246. <TabPane tabId="comment_preview">
  247. <div className="comment-form-preview">
  248. {commentPreview}
  249. </div>
  250. </TabPane>
  251. </TabContent>
  252. </div>
  253. <div className="comment-submit">
  254. <div className="d-flex">
  255. <span className="flex-grow-1" />
  256. <span className="d-none d-sm-inline">{ errorMessage && errorMessage }</span>
  257. { isSlackConfigured && isSlackEnabled != null
  258. && (
  259. <div className="form-inline align-self-center mr-md-2">
  260. <SlackNotification
  261. isSlackEnabled={isSlackEnabled}
  262. slackChannels={slackChannels}
  263. onEnabledFlagChange={isSlackEnabledToggleHandler}
  264. onChannelChange={slackChannelsChangedHandler}
  265. id="idForComment"
  266. />
  267. </div>
  268. )
  269. }
  270. <div className="d-none d-sm-block">
  271. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  272. </div>
  273. </div>
  274. <div className="d-block d-sm-none mt-2">
  275. <div className="d-flex justify-content-end">
  276. { error && errorMessage }
  277. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  278. </div>
  279. </div>
  280. </div>
  281. </>
  282. );
  283. };
  284. return (
  285. <div className={`${styles['comment-editor-styles']} form page-comment-form`}>
  286. <div className="comment-form">
  287. <div className="comment-form-user">
  288. <UserPicture user={currentUser} noLink noTooltip />
  289. </div>
  290. <div className="comment-form-main">
  291. { isReadyToUse
  292. ? renderReady()
  293. : renderBeforeReady()
  294. }
  295. </div>
  296. </div>
  297. </div>
  298. );
  299. };