CommentEditor.tsx 12 KB

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