CommentEditor.tsx 10 KB

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