CommentEditor.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import React, {
  2. useCallback, useState, useRef, useEffect,
  3. } from 'react';
  4. import { UserPicture } from '@growi/ui';
  5. import {
  6. Button,
  7. TabContent, TabPane,
  8. } from 'reactstrap';
  9. import * as toastr from 'toastr';
  10. import AppContainer from '~/client/services/AppContainer';
  11. import EditorContainer from '~/client/services/EditorContainer';
  12. import PageContainer from '~/client/services/PageContainer';
  13. import GrowiRenderer from '~/client/util/GrowiRenderer';
  14. import { apiPostForm } from '~/client/util/apiv1-client';
  15. import { CustomWindow } from '~/interfaces/global';
  16. import { IInterceptorManager } from '~/interfaces/interceptor-manager';
  17. import { useSWRxPageComment } from '~/stores/comment';
  18. import {
  19. useCurrentPagePath, useCurrentPageId, useCurrentUser, useRevisionId,
  20. } from '~/stores/context';
  21. import { useSWRxSlackChannels, useIsSlackEnabled } from '~/stores/editor';
  22. import { useIsMobile } from '~/stores/ui';
  23. import { CustomNavTab } from '../CustomNavigation/CustomNav';
  24. import NotAvailableForGuest from '../NotAvailableForGuest';
  25. import Editor from '../PageEditor/Editor';
  26. import { SlackNotification } from '../SlackNotification';
  27. import { withUnstatedContainers } from '../UnstatedUtils';
  28. import CommentPreview from './CommentPreview';
  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. type PropsType = {
  42. appContainer: AppContainer,
  43. growiRenderer: GrowiRenderer,
  44. isForNewComment?: boolean,
  45. replyTo?: string,
  46. currentCommentId?: string,
  47. commentBody?: string,
  48. commentCreator?: string,
  49. onCancelButtonClicked?: () => void,
  50. onCommentButtonClicked?: () => void,
  51. }
  52. type EditorRef = {
  53. setValue: (value: string) => void,
  54. insertText: (text: string) => void,
  55. terminateUploadingState: () => void,
  56. }
  57. const CommentEditor = (props: PropsType): JSX.Element => {
  58. const {
  59. appContainer, growiRenderer, isForNewComment, replyTo,
  60. currentCommentId, commentBody, commentCreator, onCancelButtonClicked, onCommentButtonClicked,
  61. } = props;
  62. const { data: currentUser } = useCurrentUser();
  63. const { data: currentPagePath } = useCurrentPagePath();
  64. const { data: currentPageId } = useCurrentPageId();
  65. const { update: updateComment, post: postComment } = useSWRxPageComment(currentPageId);
  66. const { data: revisionId } = useRevisionId();
  67. const { data: isMobile } = useIsMobile();
  68. const { data: isSlackEnabled, mutate: mutateIsSlackEnabled } = useIsSlackEnabled();
  69. const { data: slackChannelsData } = useSWRxSlackChannels(currentPagePath);
  70. const config = appContainer.getConfig();
  71. const isUploadable = config.upload.image || config.upload.file;
  72. const isUploadableFile = config.upload.file;
  73. const isSlackConfigured = config.isSlackConfigured;
  74. const [isReadyToUse, setIsReadyToUse] = useState(!isForNewComment);
  75. const [comment, setComment] = useState(commentBody ?? '');
  76. const [html, setHtml] = useState('');
  77. const [activeTab, setActiveTab] = useState('comment_editor');
  78. const [error, setError] = useState();
  79. const [slackChannels, setSlackChannels] = useState(slackChannelsData?.toString());
  80. const editorRef = useRef<EditorRef>(null);
  81. const renderHtml = useCallback((markdown: string) => {
  82. const context = {
  83. markdown,
  84. parsedHTML: '',
  85. };
  86. const interceptorManager: IInterceptorManager = (window as CustomWindow).interceptorManager;
  87. interceptorManager.process('preRenderCommnetPreview', context)
  88. .then(() => { return interceptorManager.process('prePreProcess', context) })
  89. .then(() => {
  90. context.markdown = growiRenderer.preProcess(context.markdown, context);
  91. })
  92. .then(() => { return interceptorManager.process('postPreProcess', context) })
  93. .then(() => {
  94. const parsedHTML = growiRenderer.process(context.markdown, context);
  95. context.parsedHTML = parsedHTML;
  96. })
  97. .then(() => { return interceptorManager.process('prePostProcess', context) })
  98. .then(() => {
  99. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML, context);
  100. })
  101. .then(() => { return interceptorManager.process('postPostProcess', context) })
  102. .then(() => { return interceptorManager.process('preRenderCommentPreviewHtml', context) })
  103. .then(() => {
  104. setHtml(context.parsedHTML);
  105. })
  106. // process interceptors for post rendering
  107. .then(() => { return interceptorManager.process('postRenderCommentPreviewHtml', context) });
  108. }, [growiRenderer]);
  109. const handleSelect = useCallback((activeTab: string) => {
  110. setActiveTab(activeTab);
  111. renderHtml(comment);
  112. }, [comment, renderHtml]);
  113. useEffect(() => {
  114. if (slackChannels === undefined) { return }
  115. setSlackChannels(slackChannelsData?.toString());
  116. }, [slackChannelsData, slackChannels]);
  117. const initializeEditor = useCallback(() => {
  118. setComment('');
  119. setHtml('');
  120. setActiveTab('comment_editor');
  121. setError(undefined);
  122. // reset value
  123. if (editorRef.current == null) { return }
  124. editorRef.current.setValue('');
  125. }, []);
  126. const cancelButtonClickedHandler = useCallback(() => {
  127. // change state to not ready
  128. // when this editor is for the new comment mode
  129. if (isForNewComment) {
  130. setIsReadyToUse(false);
  131. }
  132. if (onCancelButtonClicked != null) {
  133. onCancelButtonClicked();
  134. }
  135. }, [isForNewComment, onCancelButtonClicked]);
  136. const postCommentHandler = useCallback(async() => {
  137. try {
  138. if (currentCommentId != null) {
  139. // update current comment
  140. await updateComment(comment, revisionId, currentCommentId);
  141. }
  142. else {
  143. // post new comment
  144. const postCommentArgs = {
  145. commentForm: {
  146. comment,
  147. revisionId,
  148. replyTo,
  149. },
  150. slackNotificationForm: {
  151. isSlackEnabled,
  152. slackChannels,
  153. },
  154. };
  155. await postComment(postCommentArgs);
  156. }
  157. initializeEditor();
  158. if (onCommentButtonClicked != null) {
  159. onCommentButtonClicked();
  160. }
  161. }
  162. catch (err) {
  163. const errorMessage = err.message || 'An unknown error occured when posting comment';
  164. setError(errorMessage);
  165. }
  166. }, [
  167. comment, currentCommentId, initializeEditor,
  168. isSlackEnabled, onCommentButtonClicked, replyTo, slackChannels,
  169. postComment, revisionId, updateComment,
  170. ]);
  171. const ctrlEnterHandler = useCallback((event) => {
  172. if (event != null) {
  173. event.preventDefault();
  174. }
  175. postCommentHandler();
  176. }, [postCommentHandler]);
  177. const apiErrorHandler = useCallback((error: Error) => {
  178. toastr.error(error.message, 'Error occured', {
  179. closeButton: true,
  180. progressBar: true,
  181. newestOnTop: false,
  182. showDuration: '100',
  183. hideDuration: '100',
  184. timeOut: '3000',
  185. });
  186. }, []);
  187. const uploadHandler = useCallback(async(file) => {
  188. if (editorRef.current == null) { return }
  189. const pagePath = currentPagePath;
  190. const pageId = currentPageId;
  191. const endpoint = '/attachments.add';
  192. const formData = new FormData();
  193. formData.append('file', file);
  194. formData.append('path', pagePath ?? '');
  195. formData.append('page_id', pageId ?? '');
  196. try {
  197. // TODO: typescriptize res
  198. const res = await apiPostForm(endpoint, formData) as any;
  199. const attachment = res.attachment;
  200. const fileName = attachment.originalName;
  201. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  202. // when image
  203. if (attachment.fileFormat.startsWith('image/')) {
  204. // modify to "![fileName](url)" syntax
  205. insertText = `!${insertText}`;
  206. }
  207. editorRef.current.insertText(insertText);
  208. }
  209. catch (err) {
  210. apiErrorHandler(err);
  211. }
  212. finally {
  213. editorRef.current.terminateUploadingState();
  214. }
  215. }, [apiErrorHandler, currentPageId, currentPagePath]);
  216. const getCommentHtml = useCallback(() => {
  217. return (
  218. <CommentPreview
  219. html={html}
  220. />
  221. );
  222. }, [html]);
  223. const renderBeforeReady = useCallback((): JSX.Element => {
  224. return (
  225. <div className="text-center">
  226. <NotAvailableForGuest>
  227. <button
  228. type="button"
  229. className="btn btn-lg btn-link"
  230. onClick={() => setIsReadyToUse(true)}
  231. >
  232. <i className="icon-bubble"></i> Add Comment
  233. </button>
  234. </NotAvailableForGuest>
  235. </div>
  236. );
  237. }, []);
  238. const renderReady = () => {
  239. const commentPreview = getCommentHtml();
  240. const errorMessage = <span className="text-danger text-right mr-2">{error}</span>;
  241. const cancelButton = (
  242. <Button outline color="danger" size="xs" className="btn btn-outline-danger rounded-pill" onClick={cancelButtonClickedHandler}>
  243. Cancel
  244. </Button>
  245. );
  246. const submitButton = (
  247. <Button
  248. outline
  249. color="primary"
  250. className="btn btn-outline-primary rounded-pill"
  251. onClick={postCommentHandler}
  252. >
  253. Comment
  254. </Button>
  255. );
  256. // TODO: typescriptize Editor
  257. const AnyEditor = Editor as any;
  258. return (
  259. <>
  260. <div className="comment-write">
  261. <CustomNavTab activeTab={activeTab} navTabMapping={navTabMapping} onNavSelected={handleSelect} hideBorderBottom />
  262. <TabContent activeTab={activeTab}>
  263. <TabPane tabId="comment_editor">
  264. <AnyEditor
  265. ref={editorRef}
  266. value={comment}
  267. lineNumbers={false}
  268. isMobile={isMobile}
  269. isUploadable={isUploadable}
  270. isUploadableFile={isUploadableFile}
  271. onChange={setComment}
  272. onUpload={uploadHandler}
  273. onCtrlEnter={ctrlEnterHandler}
  274. isComment
  275. />
  276. {/*
  277. Note: <OptionsSelector /> is not optimized for ComentEditor in terms of responsive design.
  278. See a review comment in https://github.com/weseek/growi/pull/3473
  279. */}
  280. </TabPane>
  281. <TabPane tabId="comment_preview">
  282. <div className="comment-form-preview">
  283. {commentPreview}
  284. </div>
  285. </TabPane>
  286. </TabContent>
  287. </div>
  288. <div className="comment-submit">
  289. <div className="d-flex">
  290. <span className="flex-grow-1" />
  291. <span className="d-none d-sm-inline">{ errorMessage && errorMessage }</span>
  292. { isSlackConfigured
  293. && (
  294. <div className="form-inline align-self-center mr-md-2">
  295. <SlackNotification
  296. isSlackEnabled
  297. slackChannels={slackChannelsData?.toString() ?? ''}
  298. onEnabledFlagChange={isSlackEnabled => mutateIsSlackEnabled(isSlackEnabled, false)}
  299. onChannelChange={setSlackChannels}
  300. id="idForComment"
  301. />
  302. </div>
  303. )
  304. }
  305. <div className="d-none d-sm-block">
  306. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  307. </div>
  308. </div>
  309. <div className="d-block d-sm-none mt-2">
  310. <div className="d-flex justify-content-end">
  311. { error && errorMessage }
  312. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  313. </div>
  314. </div>
  315. </div>
  316. </>
  317. );
  318. };
  319. return (
  320. <div className="form page-comment-form">
  321. <div className="comment-form">
  322. <div className="comment-form-user">
  323. <UserPicture user={currentUser} noLink noTooltip />
  324. </div>
  325. <div className="comment-form-main">
  326. { isReadyToUse
  327. ? renderReady()
  328. : renderBeforeReady()
  329. }
  330. </div>
  331. </div>
  332. </div>
  333. );
  334. };
  335. /**
  336. * Wrapper component for using unstated
  337. */
  338. const CommentEditorWrapper = withUnstatedContainers<unknown, Partial<PropsType>>(
  339. CommentEditor, [AppContainer, PageContainer, EditorContainer],
  340. );
  341. export default CommentEditorWrapper;