Skip to content

Commit

Permalink
Fix issue with mutated code block
Browse files Browse the repository at this point in the history
  • Loading branch information
andyrichardson committed Sep 24, 2020
1 parent 472075c commit 281f211
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions src/panel/components/CodeHighlight.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,29 @@ 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 (
<StyledCodeBlock
{...props}
ref={handleRef}
className={`language language-${language} ${props.className || ""}`}
>
<code />
</StyledCodeBlock>
/>
);
};

Expand All @@ -41,25 +44,30 @@ export const InlineCodeHighlight: FC<
} & ComponentPropsWithoutRef<typeof StyledCodeBlock>
> = ({ 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 (
<StyledInlineBlock
{...props}
ref={handleRef}
className={`language language-${language} ${props.className || ""}`}
>
<code>{code}</code>
</StyledInlineBlock>
/>
);
};

Expand Down

0 comments on commit 281f211

Please sign in to comment.