CommentEditor.tsx 10 KB

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