CommentForm.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import ReactUtils from '../ReactUtils';
  4. import Button from 'react-bootstrap/es/Button';
  5. import Tab from 'react-bootstrap/es/Tab';
  6. import Tabs from 'react-bootstrap/es/Tabs';
  7. import UserPicture from '../User/UserPicture';
  8. import * as toastr from 'toastr';
  9. import GrowiRenderer from '../../util/GrowiRenderer';
  10. import Editor from '../PageEditor/Editor';
  11. import CommentPreview from '../PageComment/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. comment: '',
  29. isMarkdown: true,
  30. html: '',
  31. key: 1,
  32. isUploadable,
  33. isUploadableFile,
  34. errorMessage: undefined,
  35. hasSlackConfig: config.hasSlackConfig,
  36. };
  37. this.growiRenderer = new GrowiRenderer(this.props.crowi, this.props.crowiOriginRenderer, {mode: 'comment'});
  38. this.updateState = this.updateState.bind(this);
  39. this.updateStateCheckbox = this.updateStateCheckbox.bind(this);
  40. this.postComment = this.postComment.bind(this);
  41. this.renderHtml = this.renderHtml.bind(this);
  42. this.handleSelect = this.handleSelect.bind(this);
  43. this.apiErrorHandler = this.apiErrorHandler.bind(this);
  44. this.onUpload = this.onUpload.bind(this);
  45. }
  46. updateState(value) {
  47. this.setState({comment: value});
  48. }
  49. updateStateCheckbox(event) {
  50. const value = event.target.checked;
  51. this.setState({isMarkdown: value});
  52. // changeMode
  53. this.refs.editor.setGfmMode(value);
  54. }
  55. handleSelect(key) {
  56. this.setState({ key });
  57. this.renderHtml(this.state.comment);
  58. }
  59. /**
  60. * Load data of comments and rerender <PageComments />
  61. */
  62. postComment(event) {
  63. if (event != null) {
  64. event.preventDefault();
  65. }
  66. this.props.crowi.apiPost('/comments.add', {
  67. commentForm: {
  68. comment: this.state.comment,
  69. _csrf: this.props.crowi.csrfToken,
  70. page_id: this.props.pageId,
  71. revision_id: this.props.revisionId,
  72. is_markdown: this.state.isMarkdown,
  73. },
  74. slackNotificationForm: {
  75. isNotification: this.slackRef.state.isNotification,
  76. notifSlackChannel: this.slackRef.state.notifSlackChannel,
  77. }
  78. })
  79. .then((res) => {
  80. if (this.props.onPostComplete != null) {
  81. this.props.onPostComplete(res.comment);
  82. }
  83. this.setState({
  84. comment: '',
  85. isMarkdown: true,
  86. html: '',
  87. key: 1,
  88. errorMessage: undefined,
  89. });
  90. // reset value
  91. this.refs.editor.setValue('');
  92. })
  93. .catch(err => {
  94. const errorMessage = err.message || 'An unknown error occured when posting comment';
  95. this.setState({ errorMessage });
  96. });
  97. }
  98. getCommentHtml() {
  99. return (
  100. <CommentPreview
  101. html={this.state.html}
  102. inputRef={el => this.previewElement = el}/>
  103. );
  104. }
  105. renderHtml(markdown) {
  106. const context = {
  107. markdown,
  108. dom: this.previewElement,
  109. };
  110. const growiRenderer = this.growiRenderer;
  111. const interceptorManager = this.props.crowi.interceptorManager;
  112. interceptorManager.process('preRenderCommnetPreview', context)
  113. .then(() => interceptorManager.process('prePreProcess', context))
  114. .then(() => {
  115. context.markdown = growiRenderer.preProcess(context.markdown);
  116. })
  117. .then(() => interceptorManager.process('postPreProcess', context))
  118. .then(() => {
  119. const parsedHTML = growiRenderer.process(context.markdown);
  120. context['parsedHTML'] = parsedHTML;
  121. })
  122. .then(() => interceptorManager.process('prePostProcess', context))
  123. .then(() => {
  124. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML, context.dom);
  125. })
  126. .then(() => interceptorManager.process('postPostProcess', context))
  127. .then(() => interceptorManager.process('preRenderCommentPreviewHtml', context))
  128. .then(() => {
  129. this.setState({ html: context.parsedHTML });
  130. })
  131. // process interceptors for post rendering
  132. .then(() => interceptorManager.process('postRenderCommentPreviewHtml', context));
  133. }
  134. generateInnerHtml(html) {
  135. return {__html: html};
  136. }
  137. onUpload(file) {
  138. const endpoint = '/attachments.add';
  139. // create a FromData instance
  140. const formData = new FormData();
  141. formData.append('_csrf', this.props.crowi.csrfToken);
  142. formData.append('file', file);
  143. formData.append('path', this.props.pagePath);
  144. formData.append('page_id', this.props.pageId || 0);
  145. // post
  146. this.props.crowi.apiPost(endpoint, formData)
  147. .then((res) => {
  148. const url = res.url;
  149. const attachment = res.attachment;
  150. const fileName = attachment.originalName;
  151. let insertText = `[${fileName}](${url})`;
  152. // when image
  153. if (attachment.fileFormat.startsWith('image/')) {
  154. // modify to "![fileName](url)" syntax
  155. insertText = '!' + insertText;
  156. }
  157. this.refs.editor.insertText(insertText);
  158. })
  159. .catch(this.apiErrorHandler)
  160. // finally
  161. .then(() => {
  162. this.refs.editor.terminateUploadingState();
  163. });
  164. }
  165. apiErrorHandler(error) {
  166. toastr.error(error.message, 'Error occured', {
  167. closeButton: true,
  168. progressBar: true,
  169. newestOnTop: false,
  170. showDuration: '100',
  171. hideDuration: '100',
  172. timeOut: '3000',
  173. });
  174. }
  175. render() {
  176. const crowi = this.props.crowi;
  177. const username = crowi.me;
  178. const user = crowi.findUser(username);
  179. const creatorsPage = `/user/${username}`;
  180. const comment = this.state.comment;
  181. const commentPreview = this.state.isMarkdown ? this.getCommentHtml(): ReactUtils.nl2br(comment);
  182. const emojiStrategy = this.props.crowi.getEmojiStrategy();
  183. return (
  184. <div>
  185. <form className="form page-comment-form" id="page-comment-form" onSubmit={this.postComment}>
  186. { username &&
  187. <div className="comment-form">
  188. <div className="comment-form-user">
  189. <a href={creatorsPage}>
  190. <UserPicture user={user} />
  191. </a>
  192. </div>
  193. <div className="comment-form-main">
  194. <div className="comment-write">
  195. <Tabs activeKey={this.state.key} id="comment-form-tabs" onSelect={this.handleSelect} animation={false}>
  196. <Tab eventKey={1} title="Write">
  197. <Editor ref="editor"
  198. value={this.state.comment}
  199. isGfmMode={this.state.isMarkdown}
  200. editorOptions={this.props.editorOptions}
  201. lineNumbers={false}
  202. isMobile={this.props.crowi.isMobile}
  203. isUploadable={this.state.isUploadable}
  204. isUploadableFile={this.state.isUploadableFile}
  205. emojiStrategy={emojiStrategy}
  206. onChange={this.updateState}
  207. onUpload={this.onUpload}
  208. onCtrlEnter={this.postComment}
  209. />
  210. </Tab>
  211. { this.state.isMarkdown == true &&
  212. <Tab eventKey={2} title="Preview">
  213. <div className="comment-form-preview">
  214. {commentPreview}
  215. </div>
  216. </Tab>
  217. }
  218. </Tabs>
  219. </div>
  220. <div className="comment-submit d-flex">
  221. { this.state.key == 1 &&
  222. <label>
  223. <input type="checkbox" id="comment-form-is-markdown" name="isMarkdown" checked={this.state.isMarkdown} value="1" onChange={this.updateStateCheckbox} /> Markdown
  224. </label>
  225. }
  226. <div style={{flex: 1}}></div>{/* spacer */}
  227. { this.state.errorMessage &&
  228. <span className="text-danger text-right mr-2">{this.state.errorMessage}</span>
  229. }
  230. { this.state.hasSlackConfig &&
  231. <SlackNotification crowi={this.props.crowi} pageId={this.props.pageId} pagePath={this.props.pagePath} ref={(slackRef) => {this.slackRef = slackRef}} />
  232. }
  233. <Button type="submit" value="Submit" bsStyle="primary" className="fcbtn btn btn-sm btn-primary btn-outline btn-rounded btn-1b">
  234. Comment
  235. </Button>
  236. </div>
  237. </div>
  238. </div>
  239. }
  240. </form>
  241. </div>
  242. );
  243. }
  244. }
  245. CommentForm.propTypes = {
  246. crowi: PropTypes.object.isRequired,
  247. crowiOriginRenderer: PropTypes.object.isRequired,
  248. onPostComplete: PropTypes.func,
  249. pageId: PropTypes.string,
  250. revisionId: PropTypes.string,
  251. pagePath: PropTypes.string,
  252. editorOptions: PropTypes.object,
  253. };
  254. CommentForm.defaultProps = {
  255. editorOptions: {},
  256. };