( code: string, language: BundledLanguage, // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-callbacks) callback?: (result: TokenizedCode) => void )
| 173 | |
| 174 | // Synchronous highlight with callback for async results |
| 175 | export const highlightCode = ( |
| 176 | code: string, |
| 177 | language: BundledLanguage, |
| 178 | // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-callbacks) |
| 179 | callback?: (result: TokenizedCode) => void |
| 180 | ): TokenizedCode | null => { |
| 181 | const tokensCacheKey = getTokensCacheKey(code, language); |
| 182 | |
| 183 | // Return cached result if available |
| 184 | const cached = tokensCache.get(tokensCacheKey); |
| 185 | if (cached) { |
| 186 | return cached; |
| 187 | } |
| 188 | |
| 189 | // Subscribe callback if provided |
| 190 | if (callback) { |
| 191 | if (!subscribers.has(tokensCacheKey)) { |
| 192 | subscribers.set(tokensCacheKey, new Set()); |
| 193 | } |
| 194 | subscribers.get(tokensCacheKey)?.add(callback); |
| 195 | } |
| 196 | |
| 197 | // Start highlighting in background - fire-and-forget async pattern |
| 198 | getHighlighter(language) |
| 199 | // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-then) |
| 200 | .then((highlighter) => { |
| 201 | const availableLangs = highlighter.getLoadedLanguages(); |
| 202 | const langToUse = availableLangs.includes(language) ? language : "text"; |
| 203 | |
| 204 | const result = highlighter.codeToTokens(code, { |
| 205 | lang: langToUse, |
| 206 | themes: { |
| 207 | dark: "github-dark", |
| 208 | light: "github-light", |
| 209 | }, |
| 210 | }); |
| 211 | |
| 212 | const tokenized: TokenizedCode = { |
| 213 | bg: result.bg ?? "transparent", |
| 214 | fg: result.fg ?? "inherit", |
| 215 | tokens: result.tokens, |
| 216 | }; |
| 217 | |
| 218 | // Cache the result |
| 219 | tokensCache.set(tokensCacheKey, tokenized); |
| 220 | |
| 221 | // Notify all subscribers |
| 222 | const subs = subscribers.get(tokensCacheKey); |
| 223 | if (subs) { |
| 224 | for (const sub of subs) { |
| 225 | sub(tokenized); |
| 226 | } |
| 227 | subscribers.delete(tokensCacheKey); |
| 228 | } |
| 229 | }) |
| 230 | // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-then), eslint-plugin-promise(prefer-await-to-callbacks) |
| 231 | .catch((error) => { |
| 232 | console.error("Failed to highlight code:", error); |
no test coverage detected