CommentForm.js 8.5 KB

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