CommentEditor.tsx 11 KB

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