RevisionRenderer.jsx 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import AppContainer from '~/client/services/AppContainer';
  4. import GrowiRenderer from '~/client/util/GrowiRenderer';
  5. import { blinkElem } from '~/client/util/blink-section-header';
  6. import { addSmoothScrollEvent } from '~/client/util/smooth-scroll';
  7. import { useEditorSettings } from '~/stores/editor';
  8. import { withUnstatedContainers } from '../UnstatedUtils';
  9. import RevisionBody from './RevisionBody';
  10. import { loggerFactory } from '^/../codemirror-textlint/src/utils/logger';
  11. const logger = loggerFactory('components:Page:RevisionRenderer');
  12. class LegacyRevisionRenderer extends React.PureComponent {
  13. constructor(props) {
  14. super(props);
  15. this.state = {
  16. html: '',
  17. };
  18. this.renderHtml = this.renderHtml.bind(this);
  19. this.getHighlightedBody = this.getHighlightedBody.bind(this);
  20. }
  21. initCurrentRenderingContext() {
  22. this.currentRenderingContext = {
  23. markdown: this.props.markdown,
  24. pagePath: this.props.pagePath,
  25. renderDrawioInRealtime: this.props.editorSettings?.renderDrawioInRealtime,
  26. currentPathname: decodeURIComponent(window.location.pathname),
  27. };
  28. }
  29. componentDidMount() {
  30. this.initCurrentRenderingContext();
  31. this.renderHtml();
  32. }
  33. componentDidUpdate(prevProps) {
  34. const { markdown: prevMarkdown, highlightKeywords: prevHighlightKeywords } = prevProps;
  35. const { markdown, highlightKeywords } = this.props;
  36. // render only when props.markdown is updated
  37. if (markdown !== prevMarkdown || highlightKeywords !== prevHighlightKeywords) {
  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 } = window;
  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 } = window;
  110. const context = this.currentRenderingContext;
  111. await interceptorManager.process('preRender', context);
  112. await interceptorManager.process('prePreProcess', context);
  113. context.markdown = growiRenderer.preProcess(context.markdown, context);
  114. await interceptorManager.process('postPreProcess', context);
  115. context.parsedHTML = growiRenderer.process(context.markdown, context);
  116. await interceptorManager.process('prePostProcess', context);
  117. context.parsedHTML = growiRenderer.postProcess(context.parsedHTML, context);
  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. pagePath: PropTypes.string.isRequired,
  144. highlightKeywords: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  145. additionalClassName: PropTypes.string,
  146. editorSettings: PropTypes.any,
  147. };
  148. /**
  149. * Wrapper component for using unstated
  150. */
  151. const LegacyRevisionRendererWrapper = withUnstatedContainers(LegacyRevisionRenderer, [AppContainer]);
  152. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  153. const RevisionRenderer = (props) => {
  154. const { data: editorSettings } = useEditorSettings();
  155. return <LegacyRevisionRendererWrapper {...props} editorSettings={editorSettings} />;
  156. };
  157. RevisionRenderer.propTypes = {
  158. growiRenderer: PropTypes.instanceOf(GrowiRenderer).isRequired,
  159. markdown: PropTypes.string.isRequired,
  160. pagePath: PropTypes.string.isRequired,
  161. highlightKeywords: PropTypes.arrayOf(PropTypes.string),
  162. additionalClassName: PropTypes.string,
  163. };
  164. export default RevisionRenderer;