Skip to content

Commit

Permalink
Merge pull request #314 from FormidableLabs/312-fix-code-block
Browse files Browse the repository at this point in the history
Fix issue with mutated code block
  • Loading branch information
andyrichardson authored Sep 24, 2020
2 parents 3e2ce5b + 24fec2a commit 4a2fdf9
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions src/panel/components/CodeHighlight.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,30 @@ 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;
// 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 element (in web worker/async)
// when code is a chonker
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 +45,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 4a2fdf9

Please sign in to comment.