CommentForm.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import Button from 'react-bootstrap/es/Button';
  4. import Tab from 'react-bootstrap/es/Tab';
  5. import Tabs from 'react-bootstrap/es/Tabs';
  6. import * as toastr from 'toastr';
  7. import UserPicture from '../User/UserPicture';
  8. import ReactUtils from '../ReactUtils';
  9. import GrowiRenderer from '../../util/GrowiRenderer';
  10. import Editor from '../PageEditor/Editor';
  11. import CommentPreview from './CommentPreview';
  12. import SlackNotification from '../SlackNotification';
  13. /**
  14. *
  15. * @author Yuki Takei <yuki@weseek.co.jp>
  16. *
  17. * @export
  18. * @class Comment
  19. * @extends {React.Component}
  20. */
  21. export default class CommentForm extends React.Component {
  22. constructor(props) {
  23. super(props);
  24. const config = this.props.crowi.getConfig();
  25. const isUploadable = config.upload.image || config.upload.file;
  26. const isUploadableFile = config.upload.file;
  27. this.state = {
  28. isLayoutTypeGrowi: false,
  29. isFormShown: false,
  30. comment: '',
  31. isMarkdown: true,
  32. html: '',
  33. key: 1,
  34. isUploadable,
  35. isUploadableFile,
  36. errorMessage: undefined,
  37. hasSlackConfig: config.hasSlackConfig,
  38. isSlackEnabled: false,
  39. slackChannels: this.props.slackChannels,
  40. };
  41. this.growiRenderer = new GrowiRenderer(this.props.crowi, this.props.crowiOriginRenderer, { mode: 'comment' });
  42. this.updateState = this.updateState.bind(this);
  43. this.updateStateCheckbox = this.updateStateCheckbox.bind(this);
  44. this.postComment = this.postComment.bind(this);
  45. this.renderHtml = this.renderHtml.bind(this);
  46. this.handleSelect = this.handleSelect.bind(this);
  47. this.apiErrorHandler = this.apiErrorHandler.bind(this);
  48. this.onUpload = this.onUpload.bind(this);
  49. this.onSlackEnabledFlagChange = this.onSlackEnabledFlagChange.bind(this);
  50. this.onSlackChannelsChange = this.onSlackChannelsChange.bind(this);
  51. this.showCommentFormBtnClickHandler = this.showCommentFormBtnClickHandler.bind(this);
  52. }
  53. componentWillMount() {
  54. this.init();
  55. }
  56. init() {
  57. if (!this.props.pageId) {
  58. return;
  59. }
  60. const layoutType = this.props.crowi.getConfig().layoutType;
  61. this.setState({ isLayoutTypeGrowi: layoutType === 'crowi-plus' || layoutType === 'growi' });
  62. }
  63. updateState(value) {
  64. this.setState({ comment: value });
  65. }
  66. updateStateCheckbox(event) {
  67. const value = event.target.checked;
  68. this.setState({ isMarkdown: value });
  69. // changeMode
  70. this.editor.setGfmMode(value);
  71. }
  72. handleSelect(key) {
  73. this.setState({ key });
  74. this.renderHtml(this.state.comment);
  75. }
  76. onSlackEnabledFlagChange(value) {
  77. this.setState({ isSlackEnabled: value });
  78. }
  79. onSlackChannelsChange(value) {
  80. this.setState({ slackChannels: value });
  81. }
  82. /**
  83. * Load data of comments and rerender <PageComments />
  84. */
  85. postComment(event) {
  86. if (event != null) {
  87. event.preventDefault();
  88. }
  89. this.props.crowi.apiPost('/comments.add', {
  90. commentForm: {
  91. comment: this.state.comment,
  92. _csrf: this.props.crowi.csrfToken,
  93. page_id: this.props.pageId,
  94. revision_id: this.props.revisionId,
  95. is_markdown: this.state.isMarkdown,
  96. },
  97. slackNotificationForm: {
  98. isSlackEnabled: this.state.isSlackEnabled,
  99. slackChannels: this.state.slackChannels,
  100. },
  101. })
  102. .then((res) => {
  103. if (this.props.onPostComplete != null) {
  104. this.props.onPostComplete(res.comment);
  105. }
  106. this.setState({
  107. comment: '',
  108. isMarkdown: true,
  109. html: '',
  110. key: 1,
  111. errorMessage: undefined,
  112. isSlackEnabled: false,
  113. });
  114. // reset value
  115. this.editor.setValue('');
  116. })
  117. .catch((err) => {
  118. const errorMessage = err.message || 'An unknown error occured when posting comment';
  119. this.setState({ errorMessage });
  120. });
  121. }
  122. getCommentHtml() {
  123. return (
  124. <CommentPreview
  125. inputRef={(el) => { this.previewElement = el }}
  126. html={this.state.html}
  127. />
  128. );
  129. }
  130. renderHtml(markdown) {
  131. const context = {
  132. markdown,
  133. };
  134. const growiRenderer = this.growiRenderer;
  135. const interceptorManager = this.props.crowi.interceptorManager;
  136. interceptorManager.process('preRenderCommnetPreview', context)
  137. .then(() => { return interceptorManager.process('prePreProcess', context) })
  138. .then(() => {
  139. context.markdown = growiRenderer.preProcess(context.markdown);
  140. })
  141. .then(() => { return interceptorManager.process('postPreProcess', context) })
  142. .then(() => {
  143. const parsedHTML = growiRenderer.process(context.markdown);
  144. context.parsedHTML = parsedHTML;
  145. })
  146. .then(() => { return interceptorManager.process('prePostProcess', context) })
  147. .then(() => {
  148. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
  149. })
  150. .then(() => { return interceptorManager.process('postPostProcess', context) })
  151. .then(() => { return interceptorManager.process('preRenderCommentPreviewHtml', context) })
  152. .then(() => {
  153. this.setState({ html: context.parsedHTML });
  154. })
  155. // process interceptors for post rendering
  156. .then(() => { return interceptorManager.process('postRenderCommentPreviewHtml', context) });
  157. }
  158. generateInnerHtml(html) {
  159. return { __html: html };
  160. }
  161. onUpload(file) {
  162. const endpoint = '/attachments.add';
  163. // create a FromData instance
  164. const formData = new FormData();
  165. formData.append('_csrf', this.props.crowi.csrfToken);
  166. formData.append('file', file);
  167. formData.append('path', this.props.pagePath);
  168. formData.append('page_id', this.props.pageId || 0);
  169. // post
  170. this.props.crowi.apiPost(endpoint, formData)
  171. .then((res) => {
  172. const attachment = res.attachment;
  173. const fileName = attachment.originalName;
  174. let insertText = `[${fileName}](${attachment.filePathProxied})`;
  175. // when image
  176. if (attachment.fileFormat.startsWith('image/')) {
  177. // modify to "![fileName](url)" syntax
  178. insertText = `!${insertText}`;
  179. }
  180. this.editor.insertText(insertText);
  181. })
  182. .catch(this.apiErrorHandler)
  183. // finally
  184. .then(() => {
  185. this.editor.terminateUploadingState();
  186. });
  187. }
  188. apiErrorHandler(error) {
  189. toastr.error(error.message, 'Error occured', {
  190. closeButton: true,
  191. progressBar: true,
  192. newestOnTop: false,
  193. showDuration: '100',
  194. hideDuration: '100',
  195. timeOut: '3000',
  196. });
  197. }
  198. showCommentFormBtnClickHandler() {
  199. this.setState({ isFormShown: true });
  200. }
  201. renderControls() {
  202. }
  203. render() {
  204. const crowi = this.props.crowi;
  205. const username = crowi.me;
  206. const user = crowi.findUser(username);
  207. const creatorsPage = `/user/${username}`;
  208. const comment = this.state.comment;
  209. const commentPreview = this.state.isMarkdown ? this.getCommentHtml() : ReactUtils.nl2br(comment);
  210. const emojiStrategy = this.props.crowi.getEmojiStrategy();
  211. const isLayoutTypeGrowi = this.state.isLayoutTypeGrowi;
  212. const errorMessage = <span className="text-danger text-right mr-2">{this.state.errorMessage}</span>;
  213. const submitButton = (
  214. <Button type="submit" bsStyle="primary" className="fcbtn btn btn-sm btn-primary btn-outline btn-rounded btn-1b">
  215. Comment
  216. </Button>
  217. );
  218. return (
  219. <div>
  220. <form className="form page-comment-form" id="page-comment-form" onSubmit={this.postComment}>
  221. { username
  222. && (
  223. <div className="comment-form">
  224. { isLayoutTypeGrowi
  225. && (
  226. <div className="comment-form-user">
  227. <UserPicture user={user} />
  228. </div>
  229. )
  230. }
  231. <div className="comment-form-main">
  232. {/* Add Comment Button */}
  233. { !this.state.isFormShown
  234. && (
  235. <button
  236. type="button"
  237. className={`btn btn-lg ${isLayoutTypeGrowi ? 'btn-link' : 'btn-primary'} center-block`}
  238. onClick={this.showCommentFormBtnClickHandler}
  239. >
  240. <i className="icon-bubble"></i> Add Comment
  241. </button>
  242. )
  243. }
  244. {/* Editor */}
  245. { this.state.isFormShown
  246. && (
  247. <React.Fragment>
  248. <div className="comment-write">
  249. <Tabs activeKey={this.state.key} id="comment-form-tabs" onSelect={this.handleSelect} animation={false}>
  250. <Tab eventKey={1} title="Write">
  251. <Editor
  252. ref={(c) => { this.editor = c }}
  253. value={this.state.comment}
  254. isGfmMode={this.state.isMarkdown}
  255. editorOptions={this.props.editorOptions}
  256. lineNumbers={false}
  257. isMobile={this.props.crowi.isMobile}
  258. isUploadable={this.state.isUploadable && this.state.isLayoutTypeGrowi} // enable only when GROWI layout
  259. isUploadableFile={this.state.isUploadableFile}
  260. emojiStrategy={emojiStrategy}
  261. onChange={this.updateState}
  262. onUpload={this.onUpload}
  263. onCtrlEnter={this.postComment}
  264. />
  265. </Tab>
  266. { this.state.isMarkdown
  267. && (
  268. <Tab eventKey={2} title="Preview">
  269. <div className="comment-form-preview">
  270. {commentPreview}
  271. </div>
  272. </Tab>
  273. )
  274. }
  275. </Tabs>
  276. </div>
  277. <div className="comment-submit">
  278. <div className="d-flex">
  279. <label style={{ flex: 1 }}>
  280. { isLayoutTypeGrowi && this.state.key === 1
  281. && (
  282. <span>
  283. <input
  284. type="checkbox"
  285. id="comment-form-is-markdown"
  286. name="isMarkdown"
  287. checked={this.state.isMarkdown}
  288. value="1"
  289. onChange={this.updateStateCheckbox}
  290. />
  291. <span className="ml-2">Markdown</span>
  292. </span>
  293. )
  294. }
  295. </label>
  296. <span className="hidden-xs">{ this.state.errorMessage && errorMessage }</span>
  297. { this.state.hasSlackConfig
  298. && (
  299. <div className="form-inline align-self-center mr-md-2">
  300. <SlackNotification
  301. isSlackEnabled={this.state.isSlackEnabled}
  302. slackChannels={this.state.slackChannels}
  303. onEnabledFlagChange={this.onSlackEnabledFlagChange}
  304. onChannelChange={this.onSlackChannelsChange}
  305. />
  306. </div>
  307. )
  308. }
  309. <div className="hidden-xs">{submitButton}</div>
  310. </div>
  311. <div className="visible-xs mt-2">
  312. <div className="d-flex justify-content-end">
  313. { this.state.errorMessage && errorMessage }
  314. <div>{submitButton}</div>
  315. </div>
  316. </div>
  317. </div>
  318. </React.Fragment>
  319. )
  320. }
  321. </div>
  322. </div>
  323. )
  324. }
  325. </form>
  326. </div>
  327. );
  328. }
  329. }
  330. CommentForm.propTypes = {
  331. crowi: PropTypes.object.isRequired,
  332. crowiOriginRenderer: PropTypes.object.isRequired,
  333. onPostComplete: PropTypes.func,
  334. pageId: PropTypes.string,
  335. revisionId: PropTypes.string,
  336. pagePath: PropTypes.string,
  337. editorOptions: PropTypes.object,
  338. slackChannels: PropTypes.string,
  339. };
  340. CommentForm.defaultProps = {
  341. editorOptions: {},
  342. };