CommentEditor.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import {
  4. Button,
  5. TabContent, TabPane, Nav, NavItem, NavLink,
  6. } from 'reactstrap';
  7. import * as toastr from 'toastr';
  8. import AppContainer from '../../services/AppContainer';
  9. import PageContainer from '../../services/PageContainer';
  10. import CommentContainer from '../../services/CommentContainer';
  11. import EditorContainer from '../../services/EditorContainer';
  12. import GrowiRenderer from '../../util/GrowiRenderer';
  13. import { createSubscribedElement } from '../UnstatedUtils';
  14. import UserPicture from '../User/UserPicture';
  15. import Editor from '../PageEditor/Editor';
  16. import SlackNotification from '../SlackNotification';
  17. import CommentPreview from './CommentPreview';
  18. /**
  19. *
  20. * @author Yuki Takei <yuki@weseek.co.jp>
  21. *
  22. * @extends {React.Component}
  23. */
  24. class CommentEditor extends React.Component {
  25. constructor(props) {
  26. super(props);
  27. const config = this.props.appContainer.getConfig();
  28. const isUploadable = config.upload.image || config.upload.file;
  29. const isUploadableFile = config.upload.file;
  30. this.state = {
  31. comment: this.props.commentBody || '',
  32. isMarkdown: true,
  33. html: '',
  34. activeTab: 1,
  35. isUploadable,
  36. isUploadableFile,
  37. errorMessage: undefined,
  38. hasSlackConfig: config.hasSlackConfig,
  39. };
  40. this.updateState = this.updateState.bind(this);
  41. this.updateStateCheckbox = this.updateStateCheckbox.bind(this);
  42. this.postHandler = this.postHandler.bind(this);
  43. this.uploadHandler = this.uploadHandler.bind(this);
  44. this.renderHtml = this.renderHtml.bind(this);
  45. this.handleSelect = this.handleSelect.bind(this);
  46. this.onSlackEnabledFlagChange = this.onSlackEnabledFlagChange.bind(this);
  47. this.onSlackChannelsChange = this.onSlackChannelsChange.bind(this);
  48. this.toggleEditor = this.toggleEditor.bind(this);
  49. }
  50. updateState(value) {
  51. this.setState({ comment: value });
  52. }
  53. updateStateCheckbox(event) {
  54. const value = event.target.checked;
  55. this.setState({ isMarkdown: value });
  56. // changeMode
  57. this.editor.setGfmMode(value);
  58. }
  59. handleSelect(activeTab) {
  60. this.setState({ activeTab });
  61. this.renderHtml(this.state.comment);
  62. }
  63. onSlackEnabledFlagChange(isSlackEnabled) {
  64. this.props.commentContainer.setState({ isSlackEnabled });
  65. }
  66. onSlackChannelsChange(slackChannels) {
  67. this.props.commentContainer.setState({ slackChannels });
  68. }
  69. toggleEditor() {
  70. const targetId = this.props.replyTo || this.props.currentCommentId;
  71. this.props.commentButtonClickedHandler(targetId);
  72. }
  73. initializeEditor() {
  74. this.setState({
  75. comment: '',
  76. isMarkdown: true,
  77. html: '',
  78. activeTab: 1,
  79. errorMessage: undefined,
  80. });
  81. // reset value
  82. this.editor.setValue('');
  83. this.toggleEditor();
  84. }
  85. /**
  86. * Post comment with CommentContainer and update state
  87. */
  88. async postHandler(event) {
  89. if (event != null) {
  90. event.preventDefault();
  91. }
  92. try {
  93. if (this.props.currentCommentId != null) {
  94. await this.props.commentContainer.putComment(
  95. this.state.comment,
  96. this.state.isMarkdown,
  97. this.props.currentCommentId,
  98. this.props.commentCreator,
  99. );
  100. }
  101. else {
  102. await this.props.commentContainer.postComment(
  103. this.state.comment,
  104. this.state.isMarkdown,
  105. this.props.replyTo,
  106. this.props.commentContainer.state.isSlackEnabled,
  107. this.props.commentContainer.state.slackChannels,
  108. );
  109. }
  110. this.initializeEditor();
  111. }
  112. catch (err) {
  113. const errorMessage = err.message || 'An unknown error occured when posting comment';
  114. this.setState({ errorMessage });
  115. }
  116. }
  117. uploadHandler(file) {
  118. this.props.commentContainer.uploadAttachment(file)
  119. .then((res) => {
  120. const attachment = res.attachment;
  121. const fileName = attachment.originalName;
  122. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  123. // when image
  124. if (attachment.fileFormat.startsWith('image/')) {
  125. // modify to "![fileName](url)" syntax
  126. insertText = `!${insertText}`;
  127. }
  128. this.editor.insertText(insertText);
  129. })
  130. .catch(this.apiErrorHandler)
  131. // finally
  132. .then(() => {
  133. this.editor.terminateUploadingState();
  134. });
  135. }
  136. apiErrorHandler(error) {
  137. toastr.error(error.message, 'Error occured', {
  138. closeButton: true,
  139. progressBar: true,
  140. newestOnTop: false,
  141. showDuration: '100',
  142. hideDuration: '100',
  143. timeOut: '3000',
  144. });
  145. }
  146. getCommentHtml() {
  147. return (
  148. <CommentPreview
  149. inputRef={(el) => { this.previewElement = el }}
  150. html={this.state.html}
  151. />
  152. );
  153. }
  154. renderHtml(markdown) {
  155. const context = {
  156. markdown,
  157. };
  158. const { growiRenderer } = this.props;
  159. const interceptorManager = this.props.appContainer.interceptorManager;
  160. interceptorManager.process('preRenderCommnetPreview', context)
  161. .then(() => { return interceptorManager.process('prePreProcess', context) })
  162. .then(() => {
  163. context.markdown = growiRenderer.preProcess(context.markdown);
  164. })
  165. .then(() => { return interceptorManager.process('postPreProcess', context) })
  166. .then(() => {
  167. const parsedHTML = growiRenderer.process(context.markdown);
  168. context.parsedHTML = parsedHTML;
  169. })
  170. .then(() => { return interceptorManager.process('prePostProcess', context) })
  171. .then(() => {
  172. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
  173. })
  174. .then(() => { return interceptorManager.process('postPostProcess', context) })
  175. .then(() => { return interceptorManager.process('preRenderCommentPreviewHtml', context) })
  176. .then(() => {
  177. this.setState({ html: context.parsedHTML });
  178. })
  179. // process interceptors for post rendering
  180. .then(() => { return interceptorManager.process('postRenderCommentPreviewHtml', context) });
  181. }
  182. generateInnerHtml(html) {
  183. return { __html: html };
  184. }
  185. render() {
  186. const { appContainer, commentContainer } = this.props;
  187. const { activeTab } = this.state;
  188. const commentPreview = this.state.isMarkdown ? this.getCommentHtml() : null;
  189. const emojiStrategy = appContainer.getEmojiStrategy();
  190. const layoutType = this.props.appContainer.getConfig().layoutType;
  191. const isBaloonStyle = layoutType.match(/crowi-plus|growi|kibela/);
  192. const errorMessage = <span className="text-danger text-right mr-2">{this.state.errorMessage}</span>;
  193. const cancelButton = (
  194. <Button outline color="danger" size="xs" className="btn-fill rounded-pill" onClick={this.toggleEditor}>
  195. Cancel
  196. </Button>
  197. );
  198. const submitButton = (
  199. <Button
  200. outline
  201. color="primary"
  202. className="btn-fill rounded-pill btn-1b"
  203. onClick={this.postHandler}
  204. >
  205. Comment
  206. </Button>
  207. );
  208. return (
  209. <div className="form page-comment-form">
  210. <div className="comment-form">
  211. { isBaloonStyle && (
  212. <div className="comment-form-user">
  213. <UserPicture user={appContainer.currentUser} />
  214. </div>
  215. ) }
  216. <div className="comment-form-main">
  217. <div className="comment-write">
  218. <Nav tabs>
  219. <NavItem>
  220. <NavLink type="button" className={activeTab === 1 ? 'active' : ''} onClick={() => this.handleSelect(1)}>
  221. Write
  222. </NavLink>
  223. </NavItem>
  224. { this.state.isMarkdown && (
  225. <NavItem>
  226. <NavLink type="button" className={activeTab === 2 ? 'active' : ''} onClick={() => this.handleSelect(2)}>
  227. Preview
  228. </NavLink>
  229. </NavItem>
  230. ) }
  231. </Nav>
  232. <TabContent activeTab={activeTab}>
  233. <TabPane tabId={1}>
  234. <Editor
  235. ref={(c) => { this.editor = c }}
  236. value={this.state.comment}
  237. isGfmMode={this.state.isMarkdown}
  238. lineNumbers={false}
  239. isMobile={appContainer.isMobile}
  240. isUploadable={this.state.isUploadable && layoutType !== 'crowi'} // disabled upload with crowi layout
  241. isUploadableFile={this.state.isUploadableFile}
  242. emojiStrategy={emojiStrategy}
  243. onChange={this.updateState}
  244. onUpload={this.uploadHandler}
  245. onCtrlEnter={this.postHandler}
  246. />
  247. </TabPane>
  248. <TabPane tabId={2}>
  249. <div className="comment-form-preview">
  250. {commentPreview}
  251. </div>
  252. </TabPane>
  253. </TabContent>
  254. </div>
  255. <div className="comment-submit">
  256. <div className="d-flex">
  257. <label className="mr-2">
  258. { isBaloonStyle && activeTab === 1 && (
  259. <span className="custom-control custom-checkbox">
  260. <input
  261. type="checkbox"
  262. className="custom-control-input"
  263. id="comment-form-is-markdown"
  264. name="isMarkdown"
  265. checked={this.state.isMarkdown}
  266. value="1"
  267. onChange={this.updateStateCheckbox}
  268. />
  269. <label
  270. className="ml-2 custom-control-label"
  271. htmlFor="comment-form-is-markdown"
  272. >
  273. Markdown
  274. </label>
  275. </span>
  276. ) }
  277. </label>
  278. <span className="flex-grow-1" />
  279. <span className="d-none d-sm-inline">{ this.state.errorMessage && errorMessage }</span>
  280. { this.state.hasSlackConfig
  281. && (
  282. <div className="form-inline align-self-center mr-md-2">
  283. <SlackNotification
  284. isSlackEnabled={commentContainer.state.isSlackEnabled}
  285. slackChannels={commentContainer.state.slackChannels}
  286. onEnabledFlagChange={this.onSlackEnabledFlagChange}
  287. onChannelChange={this.onSlackChannelsChange}
  288. />
  289. </div>
  290. )
  291. }
  292. <div className="d-none d-sm-block">
  293. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  294. </div>
  295. </div>
  296. <div className="d-block d-sm-none mt-2">
  297. <div className="d-flex justify-content-end">
  298. { this.state.errorMessage && errorMessage }
  299. <span className="mr-2">{cancelButton}</span><span>{submitButton}</span>
  300. </div>
  301. </div>
  302. </div>
  303. </div>
  304. </div>
  305. </div>
  306. );
  307. }
  308. }
  309. /**
  310. * Wrapper component for using unstated
  311. */
  312. const CommentEditorWrapper = (props) => {
  313. return createSubscribedElement(CommentEditor, props, [AppContainer, PageContainer, EditorContainer, CommentContainer]);
  314. };
  315. CommentEditor.propTypes = {
  316. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  317. pageContainer: PropTypes.instanceOf(PageContainer).isRequired,
  318. editorContainer: PropTypes.instanceOf(EditorContainer).isRequired,
  319. commentContainer: PropTypes.instanceOf(CommentContainer).isRequired,
  320. growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
  321. replyTo: PropTypes.string,
  322. currentCommentId: PropTypes.string,
  323. commentBody: PropTypes.string,
  324. commentCreator: PropTypes.string,
  325. commentButtonClickedHandler: PropTypes.func.isRequired,
  326. };
  327. export default CommentEditorWrapper;