chore: add resource worker

This commit is contained in:
jialin
2024-07-21 18:27:22 +08:00
parent 3842006f6e
commit 177ebd1bbe
16 changed files with 280 additions and 40 deletions
@@ -0,0 +1,76 @@
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';
import CopyButton from '../copy-button';
import { escapeHtml } from './utils';
interface CodeViewerProps {
code: string;
lang: string;
autodetect?: boolean;
ignoreIllegals?: boolean;
copyable?: boolean;
}
const CodeViewer: React.FC<CodeViewerProps> = (props) => {
const {
code,
lang,
autodetect = true,
ignoreIllegals = true,
copyable = true
} = props || {};
const renderCode = () => {
const autodetectLang = autodetect && !lang;
const cannotDetectLanguage = !autodetectLang && !hljs.getLanguage(lang);
let className = '';
if (!cannotDetectLanguage) {
className = `hljs ${lang}`;
}
// No idea what language to use, return raw code
if (cannotDetectLanguage) {
console.warn(`The language "${lang}" you specified could not be found.`);
return {
value: escapeHtml(code),
className: className
};
}
if (autodetectLang) {
const result = hljs.highlightAuto(code);
return {
value: result.value,
className: className
};
}
const result = hljs.highlight(code, {
language: lang,
ignoreIllegals: ignoreIllegals
});
return {
value: result.value,
className: className
};
};
const highlightedCode = renderCode();
return (
<pre className="code-pre">
<code
className={highlightedCode.className}
dangerouslySetInnerHTML={{
__html: highlightedCode.value
}}
></code>
<CopyButton
text={highlightedCode.value}
size="small"
style={{ color: '#abb2bf' }}
></CopyButton>
</pre>
);
};
export default CodeViewer;
+17
View File
@@ -0,0 +1,17 @@
import CodeViewer from './code-viewer';
import './style.less';
const HighlightCode: React.FC<{
code: string;
lang?: string;
}> = (props) => {
const { code, lang = 'bash' } = props;
return (
<div className="high-light-wrapper">
<CodeViewer lang={lang} code={code} />
</div>
);
};
export default HighlightCode;
+22
View File
@@ -0,0 +1,22 @@
.high-light-wrapper {
text-align: left;
.hljs {
font-weight: var(--font-weight-normal);
padding-inline: 0;
padding-block: 1.2em;
}
.code-pre {
padding-inline: 12px 32px;
position: relative;
background-color: #282c34;
border-radius: var(--border-radius-mini);
.copy-button {
position: absolute;
top: 6px;
right: 6px;
}
}
}
+8
View File
@@ -0,0 +1,8 @@
export function escapeHtml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#x27;');
}