~james/core

core/web/src/lib/components/search/highlight.ts -rw-r--r-- 1.2 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import type { Chunk } from "#lib/api/lexicons/types/org/tangled/temp/search/searchCode.ts";
import { languageForPath } from "#lib/components/repo/languageColors.ts";
import type { ThemedToken } from "#lib/components/search/chunks.ts";

export const resolveLanguage = (lang?: string | null, path?: string): string | null => {
	const candidate = lang || (path ? languageForPath(path) : null);
	return candidate ? candidate.toLowerCase() : null;
};

// an unknown language renders as text with highlights, and throws on load with shiki
export const highlightChunks = async (
	chunks: Chunk[],
	lang: string
): Promise<ThemedToken[][][] | null> => {
	if (chunks.length === 0) return null;
	try {
		// lazy: keeps the highlighter out of search pages until a result needs it
		const { SYNTAX_THEME_NAME, getSharedHighlighter } = await import("#lib/syntax.ts");
		const hl = await getSharedHighlighter({ themes: [SYNTAX_THEME_NAME], langs: [lang] });
		return chunks.map((chunk) => {
			const res = hl.codeToTokens(chunk.content.replace(/\n$/, ""), {
				lang,
				theme: SYNTAX_THEME_NAME,
				defaultColor: false,
				cssVariablePrefix: "--diffs-token-"
			});
			return res.tokens as ThemedToken[][];
		});
	} catch {
		return null;
	}
};