From 8598662310ecc77934cb851fe9da6b7182b0e65b Mon Sep 17 00:00:00 2001 From: Jan Shanel Date: Tue, 8 Aug 2023 10:58:45 +0200 Subject: [PATCH] Shiki perf (#197) * shiki cache + no explanation * Remove dev optimization With includeExplanation fix gain become negligible * Add doc * fix codestyle --- src/docs/lib/shiki.ts | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/src/docs/lib/shiki.ts b/src/docs/lib/shiki.ts index 80b70635..9b72c034 100644 --- a/src/docs/lib/shiki.ts +++ b/src/docs/lib/shiki.ts @@ -11,35 +11,44 @@ const theme: Theme = "github-dark"; const defaultlangs: Lang[] = ["html", "tsx"]; const bg: React.CSSProperties["backgroundColor"] = "#011627"; +const highlighterCache = new Map>(); + +/** + * Get a shiki highlighter instance. + * Cached by theme and languages. + */ export async function getHighlighter({ langs = defaultlangs, }: { langs?: Lang[]; -} = {}) { - /** Preload NO languages in development */ - const isDevelopment = process.env.NODE_ENV === "development"; +} = {}): Promise { + const key = [theme, ...langs].join("-"); + + const highlighter = highlighterCache.get(key); + if (highlighter) return await highlighter; /* ✅ Create a highlighter instance with a theme */ - return await getHighlighterFromShiki({ + const highlighterPromise = getHighlighterFromShiki({ theme, - langs: isDevelopment ? [] : langs, + langs, }); + highlighterCache.set(key, highlighterPromise); + return await highlighterPromise; } +/** + * Highlight code string with provided shiki highlighter. + * includeExplanation turned off to increase performance. + */ export async function highlight( highlighter: Highlighter, code: string, lang: Lang = "tsx" ) { - /** Request NO languages in development */ - const isDevelopment = process.env.NODE_ENV === "development"; - /* ✅ Highlight your code using the right syntax */ - const tokens = highlighter.codeToThemedTokens( - code, - isDevelopment ? "" : lang, - theme - ); + const tokens = highlighter.codeToThemedTokens(code, lang, theme, { + includeExplanation: false, + }); /* ⚠️ Optional: Custom rendering of code blocks */ return renderToHtml(tokens, { bg,