on-codemerge
Version:
A WYSIWYG editor for on-codemerge is a user-friendly interface that allows users to edit and view their code in real time, exactly as it will appear in the final product
57 lines (56 loc) • 1.76 kB
JavaScript
import { TokenType as o } from "../types.mjs";
import { getLanguageDefinition as p } from "../utils/languages/index.mjs";
class m {
highlight(t) {
const n = t.textContent || "", s = this.getLanguage(t), e = p(s);
{
const c = this.tokenize(n, e);
t.innerHTML = this.renderTokens(c);
}
}
getLanguage(t) {
const s = t.className.match(/language-(\w+)/);
return s ? s[1] : "plaintext";
}
tokenize(t, n) {
const s = [];
let e = t;
for (; e; ) {
const c = e.match(/^\s+/);
if (c) {
s.push({ type: o.Text, value: c[0] }), e = e.slice(c[0].length);
continue;
}
if (n.keywords) {
const l = e.match(/^\b\w+\b/);
if (l && n.keywords.includes(l[0])) {
s.push({ type: o.Keyword, value: l[0] }), e = e.slice(l[0].length);
continue;
}
}
let a = { length: 0, type: null, value: "" };
for (const [l, g] of Object.entries(n.patterns)) {
if (!g) continue;
const i = new RegExp(g.source, "y");
i.lastIndex = 0;
const r = i.exec(e);
r && r[0].length > a.length && (a = {
length: r[0].length,
type: l,
value: r[0]
});
}
a.type ? (s.push({ type: a.type, value: a.value }), e = e.slice(a.length)) : (s.push({ type: o.Text, value: e[0] }), e = e.slice(1));
}
return s;
}
renderTokens(t) {
return t.map((n) => n.type === o.Text ? this.escapeHtml(n.value) : `<span class="token ${n.type}">${this.escapeHtml(n.value)}</span>`).join("");
}
escapeHtml(t) {
return t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
}
export {
m as SyntaxHighlighter
};