From a5d5ed7f81a071675f0f20ff614f439faf525af6 Mon Sep 17 00:00:00 2001 From: Jeremy Davis Date: Tue, 15 Aug 2023 15:52:42 +0200 Subject: [PATCH] SONAR-20161 Fix broken rule description --- .../src/components/CodeSyntaxHighlighter.tsx | 8 +++++--- .../__tests__/CodeSyntaxHighlighter-test.tsx | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/server/sonar-web/design-system/src/components/CodeSyntaxHighlighter.tsx b/server/sonar-web/design-system/src/components/CodeSyntaxHighlighter.tsx index 9ae139c9f8d..f6fda7072a1 100644 --- a/server/sonar-web/design-system/src/components/CodeSyntaxHighlighter.tsx +++ b/server/sonar-web/design-system/src/components/CodeSyntaxHighlighter.tsx @@ -20,7 +20,7 @@ import styled from '@emotion/styled'; import classNames from 'classnames'; -import hljs from 'highlight.js'; +import hljs, { HighlightResult } from 'highlight.js'; import apex from 'highlightjs-apex'; import abap from 'highlightjs-sap-abap'; import tw from 'twin.macro'; @@ -64,7 +64,7 @@ export function CodeSyntaxHighlighter(props: Props) { const unescapedCode = htmlDecode(code); - let highlightedCode; + let highlightedCode: HighlightResult; try { highlightedCode = hljs.highlight(unescapedCode, { @@ -80,7 +80,9 @@ export function CodeSyntaxHighlighter(props: Props) { highlightedHtmlAsString = highlightedHtmlAsString.replace( codeBlock, - `<${tag}${attributes}>${highlightedCode.value}` + // Use a function to avoid triggering special replacement patterns + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement + () => `<${tag}${attributes}>${highlightedCode.value}` ); }); diff --git a/server/sonar-web/design-system/src/components/__tests__/CodeSyntaxHighlighter-test.tsx b/server/sonar-web/design-system/src/components/__tests__/CodeSyntaxHighlighter-test.tsx index a55e079b885..5728f784a4d 100644 --- a/server/sonar-web/design-system/src/components/__tests__/CodeSyntaxHighlighter-test.tsx +++ b/server/sonar-web/design-system/src/components/__tests__/CodeSyntaxHighlighter-test.tsx @@ -51,3 +51,18 @@ it('renders correctly with code', () => { // eslint-disable-next-line testing-library/no-node-access expect(container.getElementsByClassName('hljs-string').length).toBe(1); }); + +/* + * This test reproduces a breaking case for https://sonarsource.atlassian.net/browse/SONAR-20161 + */ +it('handles html code snippets', () => { + const { container } = render( + + ); + + expect(container.querySelectorAll('pre')).toHaveLength(2); +}); -- 2.39.5