RevisionRenderer.jsx 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. const { isRenderable } = this.props;
  28. if (isRenderable) {
  29. this.initCurrentRenderingContext();
  30. this.renderHtml();
  31. }
  32. }
  33. componentDidUpdate(prevProps) {
  34. const { markdown: prevMarkdown, highlightKeywords: prevHighlightKeywords } = prevProps;
  35. const { markdown, isRenderable, highlightKeywords } = this.props;
  36. // render only when props.markdown is updated
  37. if ((markdown !== prevMarkdown || highlightKeywords !== prevHighlightKeywords) && isRenderable) {
  38. this.initCurrentRenderingContext();
  39. this.renderHtml();
  40. return;
  41. }
  42. const HeaderLink = document.getElementsByClassName('revision-head-link');
  43. const HeaderLinkArray = Array.from(HeaderLink);
  44. addSmoothScrollEvent(HeaderLinkArray, blinkElem);
  45. const { interceptorManager } = this.props.appContainer;
  46. interceptorManager.process('postRenderHtml', this.currentRenderingContext);
  47. }
  48. /**
  49. * transplanted from legacy code -- Yuki Takei
  50. * @param {string} body html strings
  51. * @param {string} keywords
  52. */
  53. getHighlightedBody(body, 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. const isMarkdownEmpty = context.markdown.trim().length === 0;
  119. if (highlightKeywords != null && highlightKeywords.length > 0 && !isMarkdownEmpty) {
  120. context.parsedHTML = this.getHighlightedBody(context.parsedHTML, highlightKeywords);
  121. }
  122. await interceptorManager.process('postPostProcess', context);
  123. await interceptorManager.process('preRenderHtml', context);
  124. this.setState({ html: context.parsedHTML });
  125. }
  126. render() {
  127. const config = this.props.appContainer.getConfig();
  128. const isMathJaxEnabled = !!config.env.MATHJAX;
  129. return (
  130. <RevisionBody
  131. html={this.state.html}
  132. isMathJaxEnabled={isMathJaxEnabled}
  133. additionalClassName={this.props.additionalClassName}
  134. renderMathJaxOnInit
  135. />
  136. );
  137. }
  138. }
  139. LegacyRevisionRenderer.propTypes = {
  140. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  141. growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
  142. markdown: PropTypes.string.isRequired,
  143. isRenderable: PropTypes.bool,
  144. highlightKeywords: PropTypes.arrayOf(PropTypes.string),
  145. additionalClassName: PropTypes.string,
  146. };
  147. /**
  148. * Wrapper component for using unstated
  149. */
  150. const LegacyRevisionRendererWrapper = withUnstatedContainers(LegacyRevisionRenderer, [AppContainer]);
  151. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  152. const RevisionRenderer = (props) => {
  153. return <LegacyRevisionRendererWrapper {...props} />;
  154. };
  155. RevisionRenderer.propTypes = {
  156. growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
  157. markdown: PropTypes.string.isRequired,
  158. isRenderable: PropTypes.bool,
  159. highlightKeywords: PropTypes.arrayOf(PropTypes.string),
  160. additionalClassName: PropTypes.string,
  161. };
  162. export default RevisionRenderer;