repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/web/components/code-block.js.ts

Raw
export function renderPlainCodeBlock(language: string, code: string): string {
	return `<pre class="ui-code" data-language="${escapeAttr(language)}"><code>${escapeHtml(code)}</code></pre>`;
}

export function renderCodeBlockComponentJs(): string {
	return `const highlightCache = new Map();
function renderCodeBlock(container, language, code) {
	const pre = document.createElement('pre');
	pre.className = 'ui-code';
	pre.dataset.language = language || 'text';
	const codeNode = document.createElement('code');
	codeNode.textContent = code;
	pre.append(codeNode);
	container.append(pre);
	queueMicrotask(() => upgradeHighlight(pre, language || 'text', code));
}
async function upgradeHighlight(pre, language, code) {
	try {
		let highlighter = highlightCache.get('highlighter');
		if (!highlighter) {
			const shiki = await import('shiki');
			highlighter = await shiki.createHighlighter({ themes: ['github-dark'], langs: [language, 'text'] });
			highlightCache.set('highlighter', highlighter);
		}
		pre.innerHTML = highlighter.codeToHtml(code, { lang: language, theme: 'github-dark' });
	} catch (_) {
		/* plaintext stays visible */
	}
}
`;
}

function escapeAttr(value: string): string {
	return escapeHtml(value).replaceAll('"', "&quot;");
}

function escapeHtml(value: string): string {
	return value
		.replaceAll("&", "&amp;")
		.replaceAll("<", "&lt;")
		.replaceAll(">", "&gt;");
}