CommentForm.js 8.4 KB

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