tfrere's picture
tfrere HF Staff
Cursor
perf(frontend): load Mermaid, Shiki grammars and language detection on demand
d840d7c
Raw History Blame Contribute Delete
2.8 kB
import { useEffect, useState } from "react";
import { Check, Copy, Download } from "lucide-react";
import { SHIKI_THEMES } from "#shared/shiki-langs";
import { getEditorHighlighter, loadLanguage } from "../../editor/editor-highlighter";
interface EmbedCodeViewProps {
html: string;
filename: string;
/** Rendered instead of the code when set (diff view). */
children?: React.ReactNode;
}
// Above this size Shiki takes long enough to stall typing in the chat.
const MAX_HIGHLIGHT_CHARS = 200_000;
export function EmbedCodeView({ html, filename, children }: EmbedCodeViewProps) {
const [highlighted, setHighlighted] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
useEffect(() => {
let cancelled = false;
setHighlighted(null);
if (!html || html.length > MAX_HIGHLIGHT_CHARS) return;
getEditorHighlighter()
.then(async (hl) => {
await loadLanguage(hl, "html");
if (cancelled) return;
setHighlighted(
hl.codeToHtml(html, {
lang: "html",
themes: { light: SHIKI_THEMES.light, dark: SHIKI_THEMES.dark },
defaultColor: false,
}),
);
})
.catch(() => {});
return () => {
cancelled = true;
};
}, [html]);
const copy = async () => {
try {
await navigator.clipboard.writeText(html);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
// Clipboard blocked (permissions, insecure context): nothing to do.
}
};
const download = () => {
const blob = new Blob([html], { type: "text/html" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename || "embed.html";
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
};
return (
<div className="es-code">
<div className="es-code__actions">
<span className="es-code__meta">
{html ? `${html.split("\n").length} lines` : "No code yet"}
</span>
<button type="button" className="embed-btn" onClick={copy} disabled={!html}>
{copied ? <Check size={13} /> : <Copy size={13} />}
{copied ? "Copied" : "Copy"}
</button>
<button type="button" className="embed-btn" onClick={download} disabled={!html}>
<Download size={13} />
Download
</button>
</div>
<div className="es-code__body">
{children ??
(highlighted ? (
<div className="es-code__shiki" dangerouslySetInnerHTML={{ __html: highlighted }} />
) : (
<pre className="es-preview__pre">
<code>{html || "// No chart HTML yet"}</code>
</pre>
))}
</div>
</div>
);
}