PageBody.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. export default class PageBody extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. this.crowiRenderer = window.crowiRenderer; // FIXME
  7. this.getMarkupHTML = this.getMarkupHTML.bind(this);
  8. this.getHighlightBody = this.getHighlightBody.bind(this);
  9. }
  10. getHighlightBody(body, keywords) {
  11. let returnBody = body;
  12. keywords.replace(/"/g, '').split(' ').forEach((keyword) => {
  13. if (keyword === '') {
  14. return;
  15. }
  16. const k = keyword
  17. .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
  18. .replace(/(^"|"$)/g, ''); // for phrase (quoted) keyword
  19. const keywordExp = new RegExp(`(${k}(?!(.*?")))`, 'ig');
  20. returnBody = returnBody.replace(keywordExp, '<em class="highlighted">$&</em>');
  21. });
  22. return returnBody;
  23. }
  24. getMarkupHTML() {
  25. let body = this.props.pageBody;
  26. if (body === '') {
  27. body = this.props.page.revision.body;
  28. }
  29. body = this.crowiRenderer.render(body, undefined, this.props.rendererOptions);
  30. if (this.props.highlightKeywords) {
  31. body = this.getHighlightBody(body, this.props.highlightKeywords);
  32. }
  33. return { __html: body };
  34. }
  35. render() {
  36. let parsedBody = this.getMarkupHTML();
  37. return (
  38. <div
  39. className="content"
  40. dangerouslySetInnerHTML={parsedBody}
  41. />
  42. );
  43. }
  44. }
  45. PageBody.propTypes = {
  46. page: PropTypes.object.isRequired,
  47. highlightKeywords: PropTypes.string,
  48. pageBody: PropTypes.string,
  49. rendererOptions: PropTypes.object,
  50. };
  51. PageBody.defaultProps = {
  52. page: {},
  53. pageBody: '',
  54. rendererOptions: {},
  55. };