CommentEditor.tsx 12 KB

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