-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Perf: reuse Shiki highlighters per theme/lang (#3130)
* reuse Shiki highlighters per theme/lang * chore: adding changeset
- Loading branch information
Tony Sullivan
committed
Apr 18, 2022
1 parent
9e35758
commit 394ab90
Showing
3 changed files
with
28 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'astro': patch | ||
--- | ||
|
||
Updates `<Code />` component to cache and reuse Shiki highlighters |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import { getHighlighter as getShikiHighlighter } from 'shiki'; | ||
|
||
// Caches Promise<Highligher> for reuse when the same theme and langs are provided | ||
const _resolvedHighlighters = new Map(); | ||
|
||
function stringify(opts) { | ||
// Always sort keys before stringifying to make sure objects match regardless of parameter ordering | ||
return JSON.stringify(opts, Object.keys(opts).sort()); | ||
} | ||
|
||
export function getHighlighter(opts) { | ||
const key = stringify(opts); | ||
|
||
// Highlighter has already been requested, reuse the same instance | ||
if (_resolvedHighlighters.has(key)) { return _resolvedHighlighters.get(key) } | ||
|
||
// Start the async getHighlighter call and cache the Promise | ||
const highlighter = getShikiHighlighter(opts); | ||
_resolvedHighlighters.set(key, highlighter); | ||
|
||
return highlighter; | ||
} |