RevisionRenderer.jsx 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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 normalizedKeywordsArray = [];
  52. // !!TODO!!: add test code refs: https://redmine.weseek.co.jp/issues/86841
  53. // Separate keywords
  54. // - Surrounded by double quotation
  55. // - Split by both full-width and half-width spaces
  56. // [...keywords.match(/"[^"]+"|[^\u{20}\u{3000}]+/ug)].forEach((keyword, i) => {
  57. keywords.forEach((keyword, i) => {
  58. if (keyword === '') {
  59. return;
  60. }
  61. const k = keyword
  62. .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // escape regex operators
  63. .replace(/(^"|"$)/g, ''); // for phrase (quoted) keyword
  64. normalizedKeywordsArray.push(k);
  65. });
  66. const normalizedKeywords = `(${normalizedKeywordsArray.join('|')})`;
  67. const keywordRegxp = new RegExp(`${normalizedKeywords}(?!(.*?"))`, 'ig'); // prior https://regex101.com/r/oX7dq5/1
  68. let keywordRegexp2 = keywordRegxp;
  69. // for non-chrome browsers compatibility
  70. try {
  71. // eslint-disable-next-line regex/invalid
  72. keywordRegexp2 = new RegExp(`(?<!<)${normalizedKeywords}(?!(.*?("|>)))`, 'ig'); // inferior (this doesn't work well when html tags exist a lot) https://regex101.com/r/Dfi61F/1
  73. }
  74. catch (err) {
  75. logger.debug('Failed to initialize regex:', err);
  76. }
  77. const highlighter = (str) => { return str.replace(keywordRegxp, '<em class="highlighted-keyword">$&</em>') }; // prior
  78. const highlighter2 = (str) => { return str.replace(keywordRegexp2, '<em class="highlighted-keyword">$&</em>') }; // inferior
  79. const insideTagRegex = /<[^<>]*>/g;
  80. const betweenTagRegex = />([^<>]*)</g; // use (group) to ignore >< around
  81. const insideTagStrs = body.match(insideTagRegex);
  82. const betweenTagMatches = Array.from(body.matchAll(betweenTagRegex));
  83. let returnBody = body;
  84. const isSafeHtml = insideTagStrs.length === betweenTagMatches.length + 1; // to check whether is safe to join
  85. if (isSafeHtml) {
  86. // highlight
  87. const betweenTagStrs = betweenTagMatches.map(match => highlighter(match[1])); // get only grouped part (exclude >< around)
  88. const arr = [];
  89. insideTagStrs.forEach((str, i) => {
  90. arr.push(str);
  91. arr.push(betweenTagStrs[i]);
  92. });
  93. returnBody = arr.join('');
  94. }
  95. else {
  96. // inferior highlighter
  97. returnBody = highlighter2(body);
  98. }
  99. return returnBody;
  100. }
  101. async renderHtml() {
  102. const {
  103. appContainer, growiRenderer,
  104. highlightKeywords,
  105. } = this.props;
  106. const { interceptorManager } = appContainer;
  107. const context = this.currentRenderingContext;
  108. await interceptorManager.process('preRender', context);
  109. await interceptorManager.process('prePreProcess', context);
  110. context.markdown = growiRenderer.preProcess(context.markdown);
  111. await interceptorManager.process('postPreProcess', context);
  112. context.parsedHTML = growiRenderer.process(context.markdown);
  113. await interceptorManager.process('prePostProcess', context);
  114. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML);
  115. const isMarkdownEmpty = context.markdown.trim().length === 0;
  116. if (highlightKeywords != null && highlightKeywords.length > 0 && !isMarkdownEmpty) {
  117. context.parsedHTML = this.getHighlightedBody(context.parsedHTML, highlightKeywords);
  118. }
  119. await interceptorManager.process('postPostProcess', context);
  120. await interceptorManager.process('preRenderHtml', context);
  121. this.setState({ html: context.parsedHTML });
  122. }
  123. render() {
  124. const config = this.props.appContainer.getConfig();
  125. const isMathJaxEnabled = !!config.env.MATHJAX;
  126. return (
  127. <RevisionBody
  128. html={this.state.html}
  129. isMathJaxEnabled={isMathJaxEnabled}
  130. additionalClassName={this.props.additionalClassName}
  131. renderMathJaxOnInit
  132. />
  133. );
  134. }
  135. }
  136. LegacyRevisionRenderer.propTypes = {
  137. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  138. growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
  139. markdown: PropTypes.string.isRequired,
  140. highlightKeywords: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  141. additionalClassName: PropTypes.string,
  142. };
  143. /**
  144. * Wrapper component for using unstated
  145. */
  146. const LegacyRevisionRendererWrapper = withUnstatedContainers(LegacyRevisionRenderer, [AppContainer]);
  147. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  148. const RevisionRenderer = (props) => {
  149. return <LegacyRevisionRendererWrapper {...props} />;
  150. };
  151. RevisionRenderer.propTypes = {
  152. growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
  153. markdown: PropTypes.string.isRequired,
  154. highlightKeywords: PropTypes.arrayOf(PropTypes.string),
  155. additionalClassName: PropTypes.string,
  156. };
  157. export default RevisionRenderer;