CommentEditor.tsx 13 KB

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