CommentEditor.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. useEditorConfig,
  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: editorConfig } = useEditorConfig();
  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. if (editorConfig === undefined) {
  229. return <></>;
  230. }
  231. const isUploadable = editorConfig.upload.isImageUploaded || editorConfig.upload.isFileUploaded;
  232. const isUploadableFile = editorConfig.upload.isFileUploaded;
  233. return (
  234. <>
  235. <div className="comment-write">
  236. <CustomNavTab activeTab={activeTab} navTabMapping={navTabMapping} onNavSelected={handleSelect} hideBorderBottom />
  237. <TabContent activeTab={activeTab}>
  238. <TabPane tabId="comment_editor">
  239. {/* <AnyEditor
  240. ref={editorRef}
  241. value={comment}
  242. lineNumbers={false}
  243. isMobile={isMobile}
  244. // isUploadable={isUploadable}
  245. // isUploadableFile={isUploadableFile}
  246. onChange={setComment}
  247. onUpload={uploadHandler}
  248. onCtrlEnter={ctrlEnterHandler}
  249. isComment
  250. /> */}
  251. {/*
  252. Note: <OptionsSelector /> is not optimized for ComentEditor in terms of responsive design.
  253. See a review comment in https://github.com/weseek/growi/pull/3473
  254. */}
  255. </TabPane>
  256. <TabPane tabId="comment_preview">
  257. <div className="comment-form-preview">
  258. {commentPreview}
  259. </div>
  260. </TabPane>
  261. </TabContent>
  262. </div>
  263. <div className="comment-submit">
  264. <div className="d-flex">
  265. <span className="flex-grow-1" />
  266. <span className="d-none d-sm-inline">{ errorMessage && errorMessage }</span>
  267. { isSlackConfigured
  268. && (
  269. <div className="form-inline align-self-center mr-md-2">
  270. <SlackNotification
  271. isSlackEnabled
  272. slackChannels={slackChannelsData?.toString() ?? ''}
  273. onEnabledFlagChange={isSlackEnabled => mutateIsSlackEnabled(isSlackEnabled, false)}
  274. onChannelChange={setSlackChannels}
  275. id="idForComment"
  276. />
  277. </div>
  278. )
  279. }
  280. <div className="d-none d-sm-block">
  281. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  282. </div>
  283. </div>
  284. <div className="d-block d-sm-none mt-2">
  285. <div className="d-flex justify-content-end">
  286. { error && errorMessage }
  287. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  288. </div>
  289. </div>
  290. </div>
  291. </>
  292. );
  293. };
  294. return (
  295. <div className="form page-comment-form">
  296. <div className={`${styles['comment-form']}`}>
  297. <div className="comment-form-user">
  298. <UserPicture user={currentUser} noLink noTooltip />
  299. </div>
  300. <div className="comment-form-main">
  301. { isReadyToUse
  302. ? renderReady()
  303. : renderBeforeReady()
  304. }
  305. </div>
  306. </div>
  307. </div>
  308. );
  309. };