mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat: implement web worker for syntax highlighting using highlight.js
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import hljs from 'highlight.js';
|
||||
|
||||
type HighlightRequest = {
|
||||
id: number;
|
||||
code: string;
|
||||
lang: string;
|
||||
};
|
||||
|
||||
type HighlightResponse = {
|
||||
id: number;
|
||||
html: string;
|
||||
};
|
||||
|
||||
const escapeHtml = (value: string) =>
|
||||
value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
self.onmessage = (event: MessageEvent<HighlightRequest>) => {
|
||||
const { id, code, lang } = event.data;
|
||||
let html = '';
|
||||
try {
|
||||
if (lang === 'plaintext') {
|
||||
html = escapeHtml(code);
|
||||
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
|
||||
html = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
|
||||
} else {
|
||||
html = hljs.highlightAuto(code).value;
|
||||
}
|
||||
} catch {
|
||||
if (lang === 'plaintext') {
|
||||
html = escapeHtml(code);
|
||||
} else {
|
||||
html = hljs.highlightAuto(code).value;
|
||||
}
|
||||
}
|
||||
const response: HighlightResponse = { id, html };
|
||||
self.postMessage(response);
|
||||
};
|
||||
Reference in New Issue
Block a user