CommentEditor.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. import React, {
  2. useCallback, useState, useRef, useEffect,
  3. } from 'react';
  4. import { UserPicture } from '@growi/ui';
  5. import {
  6. Button, TabContent, TabPane,
  7. } from 'reactstrap';
  8. import * as toastr from 'toastr';
  9. import { apiPostForm } from '~/client/util/apiv1-client';
  10. import { RendererOptions } from '~/services/renderer/renderer';
  11. import { useSWRxPageComment } from '~/stores/comment';
  12. import {
  13. useCurrentPagePath, useCurrentPageId, useCurrentUser, useRevisionId, useIsSlackConfigured,
  14. useIsUploadableFile, useIsUploadableImage,
  15. } from '~/stores/context';
  16. import { useSWRxSlackChannels, useIsSlackEnabled } from '~/stores/editor';
  17. import { CustomNavTab } from '../CustomNavigation/CustomNav';
  18. import NotAvailableForGuest from '../NotAvailableForGuest';
  19. import Editor from '../PageEditor/Editor';
  20. import { SlackNotification } from '../SlackNotification';
  21. import { CommentPreview } from './CommentPreview';
  22. import styles from './CommentEditor.module.scss';
  23. const navTabMapping = {
  24. comment_editor: {
  25. Icon: () => <i className="icon-settings" />,
  26. i18n: 'Write',
  27. index: 0,
  28. },
  29. comment_preview: {
  30. Icon: () => <i className="icon-settings" />,
  31. i18n: 'Preview',
  32. index: 1,
  33. },
  34. };
  35. export type CommentEditorProps = {
  36. rendererOptions: RendererOptions,
  37. isForNewComment?: boolean,
  38. replyTo?: string,
  39. currentCommentId?: string,
  40. commentBody?: string,
  41. onCancelButtonClicked?: () => void,
  42. onCommentButtonClicked?: () => void,
  43. }
  44. type EditorRef = {
  45. setValue: (value: string) => void,
  46. insertText: (text: string) => void,
  47. terminateUploadingState: () => void,
  48. }
  49. export const CommentEditor = (props: CommentEditorProps): JSX.Element => {
  50. const {
  51. rendererOptions, isForNewComment, replyTo,
  52. currentCommentId, commentBody, onCancelButtonClicked, onCommentButtonClicked,
  53. } = props;
  54. const { data: currentUser } = useCurrentUser();
  55. const { data: currentPagePath } = useCurrentPagePath();
  56. const { data: currentPageId } = useCurrentPageId();
  57. const { update: updateComment, post: postComment } = useSWRxPageComment(currentPageId);
  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<EditorRef>(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 pageId = currentPageId;
  150. const endpoint = '/attachments.add';
  151. const formData = new FormData();
  152. formData.append('file', file);
  153. formData.append('path', pagePath ?? '');
  154. formData.append('page_id', pageId ?? '');
  155. try {
  156. // TODO: typescriptize res
  157. const res = await apiPostForm(endpoint, formData) as any;
  158. const attachment = res.attachment;
  159. const fileName = attachment.originalName;
  160. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  161. // when image
  162. if (attachment.fileFormat.startsWith('image/')) {
  163. // modify to "![fileName](url)" syntax
  164. insertText = `!${insertText}`;
  165. }
  166. editorRef.current.insertText(insertText);
  167. }
  168. catch (err) {
  169. apiErrorHandler(err);
  170. }
  171. finally {
  172. editorRef.current.terminateUploadingState();
  173. }
  174. }, [apiErrorHandler, currentPageId, currentPagePath]);
  175. const getCommentHtml = useCallback(() => {
  176. if (currentPagePath == null) {
  177. return <></>;
  178. }
  179. return (
  180. <CommentPreview
  181. rendererOptions={rendererOptions}
  182. markdown={comment}
  183. path={currentPagePath}
  184. />
  185. );
  186. }, [currentPagePath, comment, rendererOptions]);
  187. const renderBeforeReady = useCallback((): JSX.Element => {
  188. return (
  189. <div className="text-center">
  190. <NotAvailableForGuest>
  191. <button
  192. type="button"
  193. className="btn btn-lg btn-link"
  194. onClick={() => setIsReadyToUse(true)}
  195. >
  196. <i className="icon-bubble"></i> Add Comment
  197. </button>
  198. </NotAvailableForGuest>
  199. </div>
  200. );
  201. }, []);
  202. const renderReady = () => {
  203. const commentPreview = getCommentHtml();
  204. const errorMessage = <span className="text-danger text-right mr-2">{error}</span>;
  205. const cancelButton = (
  206. <Button outline color="danger" size="xs" className="btn btn-outline-danger rounded-pill" onClick={cancelButtonClickedHandler}>
  207. Cancel
  208. </Button>
  209. );
  210. const submitButton = (
  211. <Button
  212. outline
  213. color="primary"
  214. className="btn btn-outline-primary rounded-pill"
  215. onClick={postCommentHandler}
  216. >
  217. Comment
  218. </Button>
  219. );
  220. const isUploadable = isUploadableImage || isUploadableFile;
  221. return (
  222. <>
  223. <div className="comment-write">
  224. <CustomNavTab activeTab={activeTab} navTabMapping={navTabMapping} onNavSelected={handleSelect} hideBorderBottom />
  225. <TabContent activeTab={activeTab}>
  226. <TabPane tabId="comment_editor">
  227. <Editor
  228. ref={editorRef}
  229. value={comment}
  230. isUploadable={isUploadable}
  231. isUploadableFile={isUploadableFile}
  232. onChange={setComment}
  233. onUpload={uploadHandler}
  234. onCtrlEnter={ctrlEnterHandler}
  235. isComment
  236. />
  237. {/*
  238. Note: <OptionsSelector /> is not optimized for ComentEditor in terms of responsive design.
  239. See a review comment in https://github.com/weseek/growi/pull/3473
  240. */}
  241. </TabPane>
  242. <TabPane tabId="comment_preview">
  243. <div className="comment-form-preview">
  244. {commentPreview}
  245. </div>
  246. </TabPane>
  247. </TabContent>
  248. </div>
  249. <div className="comment-submit">
  250. <div className="d-flex">
  251. <span className="flex-grow-1" />
  252. <span className="d-none d-sm-inline">{ errorMessage && errorMessage }</span>
  253. { isSlackConfigured
  254. && (
  255. <div className="form-inline align-self-center mr-md-2">
  256. <SlackNotification
  257. isSlackEnabled
  258. slackChannels={slackChannelsData?.toString() ?? ''}
  259. onEnabledFlagChange={isSlackEnabled => mutateIsSlackEnabled(isSlackEnabled, false)}
  260. onChannelChange={setSlackChannels}
  261. id="idForComment"
  262. />
  263. </div>
  264. )
  265. }
  266. <div className="d-none d-sm-block">
  267. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  268. </div>
  269. </div>
  270. <div className="d-block d-sm-none mt-2">
  271. <div className="d-flex justify-content-end">
  272. { error && errorMessage }
  273. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  274. </div>
  275. </div>
  276. </div>
  277. </>
  278. );
  279. };
  280. return (
  281. <div className={`${styles['comment-editor-styles']} form page-comment-form`}>
  282. <div className="comment-form">
  283. <div className="comment-form-user">
  284. <UserPicture user={currentUser} noLink noTooltip />
  285. </div>
  286. <div className="comment-form-main">
  287. { isReadyToUse
  288. ? renderReady()
  289. : renderBeforeReady()
  290. }
  291. </div>
  292. </div>
  293. </div>
  294. );
  295. };