CommentEditor.tsx 12 KB

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