RevisionRenderer.jsx 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { withUnstatedContainers } from '../UnstatedUtils';
  4. import AppContainer from '~/client/services/AppContainer';
  5. import GrowiRenderer from '~/client/util/GrowiRenderer';
  6. import { addSmoothScrollEvent } from '~/client/util/smooth-scroll';
  7. import { blinkElem } from '~/client/util/blink-section-header';
  8. import RevisionBody from './RevisionBody';
  9. import { loggerFactory } from '^/../codemirror-textlint/src/utils/logger';
  10. const logger = loggerFactory('components:Page:RevisionRenderer');
  11. class LegacyRevisionRenderer extends React.PureComponent {
  12. constructor(props) {
  13. super(props);
  14. this.state = {
  15. html: '',
  16. };
  17. this.renderHtml = this.renderHtml.bind(this);
  18. this.getHighlightedBody = this.getHighlightedBody.bind(this);
  19. }
  20. initCurrentRenderingContext() {
  21. this.currentRenderingContext = {
  22. markdown: this.props.markdown,
  23. currentPagePath: decodeURIComponent(window.location.pathname),
  24. };
  25. }
  26. componentDidMount() {
  27. this.initCurrentRenderingContext();
  28. this.renderHtml();
  29. }
  30. componentDidUpdate(prevProps) {
  31. const { markdown: prevMarkdown, highlightKeywords: prevHighlightKeywords } = prevProps;
  32. const { markdown, highlightKeywords } = this.props;
  33. // render only when props.markdown is updated
  34. if (markdown !== prevMarkdown || highlightKeywords !== prevHighlightKeywords) {
  35. this.initCurrentRenderingContext();
  36. this.renderHtml();
  37. return;
  38. }
  39. const HeaderLink = document.getElementsByClassName('revision-head-link');
  40. const HeaderLinkArray = Array.from(HeaderLink);
  41. addSmoothScrollEvent(HeaderLinkArray, blinkElem);
  42. const { interceptorManager } = this.props.appContainer;
  43. interceptorManager.process('postRenderHtml', this.currentRenderingContext);
  44. }
  45. /**
  46. * transplanted from legacy code -- Yuki Takei
  47. * @param {string} body html strings
  48. * @param {string} keywords
  49. */
  50. getHighlightedBody(body, _keywords) {
  51. const keywords = Array.isArray(_keywords)
  52. ? _keywords
  53. : [_keywords];
  54. const normalizedKeywordsArray = [];
  55. // !!TODO!!: add test code refs: https://redmine.weseek.co.jp/issues/86841
  56. // Separate keywords
  57. // - Surrounded by double quotation
  58. // - Split by both full-width and half-width spaces
  59. // [...keywords.match(/"[^"]+"|[^\u{20}\u{3000}]+/ug)].forEach((keyword, i) => {
  60. keywords.forEach((keyword, i) => {
  61. if (keyword === '') {
  62. return;
  63. }
  64. const k = keyword
  65. .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // escape regex operators
  66. .replace(/(^"|"$)/g, ''); // for phrase (quoted) keyword
  67. normalizedKeywordsArray.push(k);
  68. });
  69. const normalizedKeywords = `(${normalizedKeywordsArray.join('|')})`;
  70. const keywordRegxp = new RegExp(`${normalizedKeywords}(?!(.*?"))`, 'ig'); // prior https://regex101.com/r/oX7dq5/1
  71. let keywordRegexp2 = keywordRegxp;
  72. // for non-chrome browsers compatibility
  73. try {
  74. // eslint-disable-next-line regex/invalid
  75. keywordRegexp2 = new RegExp(`(?<!<)${normalizedKeywords}(?!(.*?("|>)))`, 'ig'); // inferior (this doesn't work well when html tags exist a lot) https://regex101.com/r/Dfi61F/1
  76. }
  77. catch (err) {
  78. logger.debug('Failed to initialize regex:', err);
  79. }
  80. const highlighter = (str) => { return str.replace(keywordRegxp, '<em class="highlighted-keyword">$&</em>') }; // prior
  81. const highlighter2 = (str) => { return str.replace(keywordRegexp2, '<em class="highlighted-keyword">$&</em>') }; // inferior
  82. const insideTagRegex = /<[^<>]*>/g;
  83. const betweenTagRegex = />([^<>]*)</g; // use (group) to ignore >< around
  84. const insideTagStrs = body.match(insideTagRegex);
  85. const betweenTagMatches = Array.from(body.matchAll(betweenTagRegex));
  86. let returnBody = body;
  87. const isSafeHtml = insideTagStrs.length === betweenTagMatches.length + 1; // to check whether is safe to join
  88. if (isSafeHtml) {
  89. // highlight
  90. const betweenTagStrs = betweenTagMatches.map(match => highlighter(match[1])); // get only grouped part (exclude >< around)
  91. const arr = [];
  92. insideTagStrs.forEach((str, i) => {
  93. arr.push(str);
  94. arr.push(betweenTagStrs[i]);
  95. });
  96. returnBody = arr.join('');
  97. }
  98. else {
  99. // inferior highlighter
  100. returnBody = highlighter2(body);
  101. }
  102. return returnBody;
  103. }
  104. async renderHtml() {
  105. const {
  106. appContainer, growiRenderer,
  107. highlightKeywords,
  108. } = this.props;
  109. const { interceptorManager } = appContainer;
  110. const context = this.currentRenderingContext;
  111. await interceptorManager.process('preRender', context);
  112. await interceptorManager.process('prePreProcess', context);
  113. context.markdown = growiRenderer.preProcess(context.markdown);
  114. await interceptorManager.process('postPreProcess', context);
  115. context.parsedHTML = growiRenderer.process(context.markdown);
  116. await interceptorManager.process('prePostProcess', context);
  117. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
  118. if (highlightKeywords != null && highlightKeywords.length > 0) {
  119. context.parsedHTML = this.getHighlightedBody(context.parsedHTML, highlightKeywords);
  120. }
  121. await interceptorManager.process('postPostProcess', context);
  122. await interceptorManager.process('preRenderHtml', context);
  123. this.setState({ html: context.parsedHTML });
  124. }
  125. render() {
  126. const config = this.props.appContainer.getConfig();
  127. const isMathJaxEnabled = !!config.env.MATHJAX;
  128. return (
  129. <RevisionBody
  130. html={this.state.html}
  131. isMathJaxEnabled={isMathJaxEnabled}
  132. additionalClassName={this.props.additionalClassName}
  133. renderMathJaxOnInit
  134. />
  135. );
  136. }
  137. }
  138. LegacyRevisionRenderer.propTypes = {
  139. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  140. growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
  141. markdown: PropTypes.string.isRequired,
  142. highlightKeywords: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  143. additionalClassName: PropTypes.string,
  144. };
  145. /**
  146. * Wrapper component for using unstated
  147. */
  148. const LegacyRevisionRendererWrapper = withUnstatedContainers(LegacyRevisionRenderer, [AppContainer]);
  149. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  150. const RevisionRenderer = (props) => {
  151. return <LegacyRevisionRendererWrapper {...props} />;
  152. };
  153. RevisionRenderer.propTypes = {
  154. growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
  155. markdown: PropTypes.string.isRequired,
  156. highlightKeywords: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  157. additionalClassName: PropTypes.string,
  158. };
  159. export default RevisionRenderer;