CommentForm.js 8.6 KB

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