From 281f211ef7de43210b219492d6e5c498b9257b87 Mon Sep 17 00:00:00 2001 From: Andy Richardson Date: Thu, 24 Sep 2020 11:01:59 +0100 Subject: [PATCH 1/2] Fix issue with mutated code block --- src/panel/components/CodeHighlight.tsx | 38 ++++++++++++++++---------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/src/panel/components/CodeHighlight.tsx b/src/panel/components/CodeHighlight.tsx index 23c88695..381bd079 100644 --- a/src/panel/components/CodeHighlight.tsx +++ b/src/panel/components/CodeHighlight.tsx @@ -11,16 +11,21 @@ export const CodeHighlight: FC< > = ({ code, language, ...props }) => { const handleRef = useCallback( (ref: HTMLPreElement | null) => { - if (ref === null) { + if (!ref) { return; } - (ref.children[0] as HTMLElement).textContent = code; - // Run prism on element (in web worker/async) - // when code is a chonker + // Create new child node with text + const child = document.createElement("code"); + child.textContent = code; + ref.firstChild + ? ref.replaceChild(child, ref.firstChild) + : ref.appendChild(child); + + // Run prism on pre Prism.highlightElement(ref, code.length > 600); }, - [code, language] + [language, code] ); return ( @@ -28,9 +33,7 @@ export const CodeHighlight: FC< {...props} ref={handleRef} className={`language language-${language} ${props.className || ""}`} - > - - + /> ); }; @@ -41,15 +44,22 @@ export const InlineCodeHighlight: FC< } & ComponentPropsWithoutRef > = ({ code, language, ...props }) => { const handleRef = useCallback( - (ref) => { - if (ref === null) { + (ref: HTMLPreElement | null) => { + if (!ref) { return; } - // Run prism on element (sync) + // Create new child node with text + const child = document.createElement("code"); + child.textContent = code; + ref.firstChild + ? ref.replaceChild(child, ref.firstChild) + : ref.appendChild(child); + + // Run prism on pre Prism.highlightElement(ref, false); }, - [code, language] + [language, code] ); return ( @@ -57,9 +67,7 @@ export const InlineCodeHighlight: FC< {...props} ref={handleRef} className={`language language-${language} ${props.className || ""}`} - > - {code} - + /> ); }; From 24fec2ac0b69fcb30d6f900106462b96d390f61f Mon Sep 17 00:00:00 2001 From: Andy Richardson Date: Thu, 24 Sep 2020 11:08:05 +0100 Subject: [PATCH 2/2] Update CodeHighlight.tsx --- src/panel/components/CodeHighlight.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/panel/components/CodeHighlight.tsx b/src/panel/components/CodeHighlight.tsx index 381bd079..95f313fb 100644 --- a/src/panel/components/CodeHighlight.tsx +++ b/src/panel/components/CodeHighlight.tsx @@ -22,7 +22,8 @@ export const CodeHighlight: FC< ? ref.replaceChild(child, ref.firstChild) : ref.appendChild(child); - // Run prism on pre + // Run prism on element (in web worker/async) + // when code is a chonker Prism.highlightElement(ref, code.length > 600); }, [language, code]