react-shiki 0.9.2 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -19
- package/dist/component-C5lsWZSq.mjs +345 -0
- package/dist/component-C5lsWZSq.mjs.map +1 -0
- package/dist/component-CjpuWrgO.d.mts +515 -0
- package/dist/{core.d.ts → core.d.mts} +10 -11
- package/dist/core.mjs +64 -0
- package/dist/core.mjs.map +1 -0
- package/dist/index.d.mts +38 -0
- package/dist/index.mjs +53 -0
- package/dist/index.mjs.map +1 -0
- package/dist/style.css +55 -0
- package/dist/web.d.mts +38 -0
- package/dist/web.mjs +54 -0
- package/dist/web.mjs.map +1 -0
- package/package.json +35 -27
- package/src/styles/css.d.ts +1 -0
- package/src/styles/features.css +51 -0
- package/dist/chunk-QPJZGYHO.js +0 -416
- package/dist/chunk-QPJZGYHO.js.map +0 -1
- package/dist/component-CoSKNtmy.d.ts +0 -204
- package/dist/core.js +0 -53
- package/dist/core.js.map +0 -1
- package/dist/index.d.ts +0 -38
- package/dist/index.js +0 -53
- package/dist/index.js.map +0 -1
- package/dist/web.d.ts +0 -39
- package/dist/web.js +0 -53
- package/dist/web.js.map +0 -1
- package/src/lib/styles.css +0 -55
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# 🎨
|
|
1
|
+
# 🎨 react-shiki
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
A performant client-side syntax highlighting component and hook for React, built with [Shiki](https://shiki.matsu.io/).
|
|
@@ -6,7 +6,7 @@ A performant client-side syntax highlighting component and hook for React, built
|
|
|
6
6
|
[See the demo page with highlighted code blocks showcasing several Shiki themes!](https://react-shiki.vercel.app/)
|
|
7
7
|
|
|
8
8
|
<!--toc:start-->
|
|
9
|
-
- 🎨
|
|
9
|
+
- [🎨 react-shiki](#🎨-react-shiki)
|
|
10
10
|
- [Features](#features)
|
|
11
11
|
- [Installation](#installation)
|
|
12
12
|
- [Usage](#usage)
|
|
@@ -15,9 +15,13 @@ A performant client-side syntax highlighting component and hook for React, built
|
|
|
15
15
|
- [`react-shiki/web` (Web Bundle)](#react-shikiweb-web-bundle)
|
|
16
16
|
- [`react-shiki/core` (Minimal Bundle)](#react-shikicore-minimal-bundle)
|
|
17
17
|
- [RegExp Engines](#regexp-engines)
|
|
18
|
+
- [Using Engines with Full and Web Bundles](#using-engines-with-full-and-web-bundles)
|
|
19
|
+
- [Using Engines with Core Bundle](#using-engines-with-core-bundle)
|
|
20
|
+
- [Engine Options](#engine-options)
|
|
18
21
|
- [Configuration](#configuration)
|
|
19
22
|
- [Common Configuration Options](#common-configuration-options)
|
|
20
23
|
- [Component-specific Props](#component-specific-props)
|
|
24
|
+
- [Embedded Language Highlighting](#embedded-language-highlighting)
|
|
21
25
|
- [Multi-theme Support](#multi-theme-support)
|
|
22
26
|
- [Making Themes Reactive](#making-themes-reactive)
|
|
23
27
|
- [Option 1: Using `light-dark()` Function (Recommended)](#option-1-using-light-dark-function-recommended)
|
|
@@ -34,7 +38,6 @@ A performant client-side syntax highlighting component and hook for React, built
|
|
|
34
38
|
- [Performance](#performance)
|
|
35
39
|
- [Throttling Real-time Highlighting](#throttling-real-time-highlighting)
|
|
36
40
|
- [Output Format Optimization](#output-format-optimization)
|
|
37
|
-
- [Streaming and LLM Chat UI](#streaming-and-llm-chat-ui)
|
|
38
41
|
<!--toc:end-->
|
|
39
42
|
|
|
40
43
|
## Features
|
|
@@ -43,6 +46,7 @@ A performant client-side syntax highlighting component and hook for React, built
|
|
|
43
46
|
- 🔐 Flexible output: Choose between React elements (no `dangerouslySetInnerHTML`) or HTML strings for better performance
|
|
44
47
|
- 📦 Multiple bundle options: Full bundle (~1.2MB gz), web bundle (~695KB gz), or minimal core bundle for fine-grained bundle control
|
|
45
48
|
- 🖌️ Full support for custom TextMate themes and languages
|
|
49
|
+
- 🧬 Automatic highlighting of embedded languages (e.g. TypeScript fenced inside Markdown) via Shiki's `guessEmbeddedLanguages`
|
|
46
50
|
- 🔧 Supports passing custom Shiki transformers to the highlighter, in addition to all other options supported by `codeToHast`
|
|
47
51
|
- 🚰 Performant highlighting of streamed code, with optional throttling
|
|
48
52
|
- 📚 Includes minimal default styles for code blocks
|
|
@@ -234,12 +238,16 @@ The `ShikiHighlighter` component offers minimal built-in styling and customizati
|
|
|
234
238
|
| ------------------ | --------- | ------- | ---------------------------------------------------------- |
|
|
235
239
|
| `showLanguage` | `boolean` | `true` | Displays language label in top-right corner |
|
|
236
240
|
| `addDefaultStyles` | `boolean` | `true` | Adds minimal default styling to the highlighted code block |
|
|
237
|
-
| `as` | `string` | `'
|
|
241
|
+
| `as` | `string` | `'div'` | Component's Root HTML element |
|
|
238
242
|
| `className` | `string` | - | Custom class name for the code block |
|
|
239
243
|
| `langClassName` | `string` | - | Class name for styling the language label |
|
|
240
244
|
| `style` | `object` | - | Inline style object for the code block |
|
|
241
245
|
| `langStyle` | `object` | - | Inline style object for the language label |
|
|
242
246
|
|
|
247
|
+
### Embedded Language Highlighting
|
|
248
|
+
|
|
249
|
+
react-shiki uses Shiki's [`guessEmbeddedLanguages`](https://shiki.style) to automatically detect, load, and highlight languages nested inside other languages — for example, a TypeScript fenced code block inside a Markdown document will be highlighted as TypeScript without any extra configuration. Embedded languages are dynamically loaded on demand, as long as they exist in your bundle.
|
|
250
|
+
|
|
243
251
|
### Multi-theme Support
|
|
244
252
|
|
|
245
253
|
To use multiple theme modes, pass an object with your multi-theme configuration to the `theme` prop in the `ShikiHighlighter` component:
|
|
@@ -346,7 +354,6 @@ const highlightedCode = useShikiHighlighter(code, "tsx", tokyoNight);
|
|
|
346
354
|
### Custom Languages
|
|
347
355
|
|
|
348
356
|
Custom languages should be passed as a TextMate grammar in JavaScript object. For example, [it should look like this](https://github.com/shikijs/textmate-grammars-themes/blob/main/packages/tm-grammars/grammars/typescript.json)
|
|
349
|
-
|
|
350
357
|
```tsx
|
|
351
358
|
import mcfunction from "../langs/mcfunction.tmLanguage.json";
|
|
352
359
|
|
|
@@ -361,8 +368,7 @@ const highlightedCode = useShikiHighlighter(code, mcfunction, "github-dark");
|
|
|
361
368
|
|
|
362
369
|
#### Preloading Languages
|
|
363
370
|
|
|
364
|
-
|
|
365
|
-
`preloadLanguages` can also preload bundled language IDs, not just custom grammars.
|
|
371
|
+
If highlighting is dynamic at runtime, preload custom languages.
|
|
366
372
|
|
|
367
373
|
```tsx
|
|
368
374
|
import mcfunction from "../langs/mcfunction.tmLanguage.json";
|
|
@@ -383,9 +389,12 @@ const highlightedCode = useShikiHighlighter(code, "typescript", "github-dark", {
|
|
|
383
389
|
});
|
|
384
390
|
```
|
|
385
391
|
|
|
392
|
+
> [!NOTE]
|
|
393
|
+
> Bundled language are dynamically loaded as needed, and do not need to be preloaded as long as they exist in your bundle.
|
|
394
|
+
|
|
386
395
|
### Language Aliases
|
|
387
396
|
|
|
388
|
-
You can define custom aliases for languages using the `langAlias` option. This is useful when you
|
|
397
|
+
You can define custom aliases for languages using the `langAlias` option. This is useful when you need to support alternative names for languages:
|
|
389
398
|
|
|
390
399
|
```tsx
|
|
391
400
|
// Component
|
|
@@ -452,21 +461,26 @@ const highlightedCode = useShikiHighlighter(code, "javascript", "github-dark", {
|
|
|
452
461
|
```
|
|
453
462
|
|
|
454
463
|
> [!NOTE]
|
|
455
|
-
> When using the hook with line numbers, import the CSS file
|
|
464
|
+
> When using the hook with line numbers, import the CSS file or provide your own CSS
|
|
465
|
+
> for `.rs-line-number` (line `span`) and `.rs-has-line-numbers` (container `code` element). <!-- TODO: The CSS vars/classes/selectors are poorly documented -->
|
|
456
466
|
> ```tsx
|
|
457
467
|
> import 'react-shiki/css';
|
|
458
468
|
> ```
|
|
459
|
-
|
|
469
|
+
|
|
470
|
+
> [!WARNING]
|
|
471
|
+
> Legacy `.line-numbers` / `.has-line-numbers` selectors and unprefixed line-number CSS variables are still supported for this release cycle, but are deprecated and will be removed in the next major.
|
|
472
|
+
|
|
473
|
+
Component-internal default classes are namespaced under `rs-*` and shipped inside `@layer base` so app-level utilities can override them more predictably.
|
|
460
474
|
|
|
461
475
|
Available CSS variables for customization:
|
|
462
476
|
```css
|
|
463
|
-
--line-numbers-foreground: rgba(107, 114, 128, 0.5);
|
|
464
|
-
--line-numbers-width: 2ch;
|
|
465
|
-
--line-numbers-padding-left: 0ch;
|
|
466
|
-
--line-numbers-padding-right: 2ch;
|
|
467
|
-
--line-numbers-font-size: inherit;
|
|
468
|
-
--line-numbers-font-weight: inherit;
|
|
469
|
-
--line-numbers-opacity: 1;
|
|
477
|
+
--rs-line-numbers-foreground: rgba(107, 114, 128, 0.5);
|
|
478
|
+
--rs-line-numbers-width: 2ch;
|
|
479
|
+
--rs-line-numbers-padding-left: 0ch;
|
|
480
|
+
--rs-line-numbers-padding-right: 2ch;
|
|
481
|
+
--rs-line-numbers-font-size: inherit;
|
|
482
|
+
--rs-line-numbers-font-weight: inherit;
|
|
483
|
+
--rs-line-numbers-opacity: 1;
|
|
470
484
|
```
|
|
471
485
|
|
|
472
486
|
You can customize them in your own CSS or by using the style prop on the component:
|
|
@@ -476,8 +490,8 @@ You can customize them in your own CSS or by using the style prop on the compone
|
|
|
476
490
|
theme="github-dark"
|
|
477
491
|
showLineNumbers
|
|
478
492
|
style={{
|
|
479
|
-
'--line-numbers-foreground': '#60a5fa',
|
|
480
|
-
'--line-numbers-width': '3ch'
|
|
493
|
+
'--rs-line-numbers-foreground': '#60a5fa',
|
|
494
|
+
'--rs-line-numbers-width': '3ch'
|
|
481
495
|
}}
|
|
482
496
|
>
|
|
483
497
|
{code}
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import './style.css';
|
|
2
|
+
import { forwardRef, useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
4
|
+
import { toJsxRuntime } from "hast-util-to-jsx-runtime";
|
|
5
|
+
import { dequal } from "dequal";
|
|
6
|
+
import { guessEmbeddedLanguages, isSpecialLang } from "shiki/core";
|
|
7
|
+
import { visit } from "unist-util-visit";
|
|
8
|
+
import { clsx } from "clsx";
|
|
9
|
+
//#region src/lib/utils.ts
|
|
10
|
+
/**
|
|
11
|
+
* Returns a referentially stable version of `value` that only updates when content changes.
|
|
12
|
+
* Uses reference equality as a fast path and deep comparison to prevent unnecessary updates.
|
|
13
|
+
*/
|
|
14
|
+
const useStableValue = (value) => {
|
|
15
|
+
const ref = useRef(value);
|
|
16
|
+
if (value !== ref.current && !dequal(value, ref.current)) ref.current = value;
|
|
17
|
+
return ref.current;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Optionally throttles rapid sequential highlighting operations
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* const timeoutControl = useRef<TimeoutState>({
|
|
24
|
+
* nextAllowedTime: 0,
|
|
25
|
+
* timeoutId: undefined
|
|
26
|
+
* });
|
|
27
|
+
*
|
|
28
|
+
* throttleHighlighting(highlightCode, timeoutControl, 1000);
|
|
29
|
+
*/
|
|
30
|
+
const throttleHighlighting = (performHighlight, timeoutControl, throttleMs) => {
|
|
31
|
+
clearTimeout(timeoutControl.current.timeoutId);
|
|
32
|
+
const delay = Math.max(0, timeoutControl.current.nextAllowedTime - Date.now());
|
|
33
|
+
timeoutControl.current.timeoutId = setTimeout(() => {
|
|
34
|
+
performHighlight();
|
|
35
|
+
timeoutControl.current.nextAllowedTime = Date.now() + throttleMs;
|
|
36
|
+
}, delay);
|
|
37
|
+
};
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/lib/language.ts
|
|
40
|
+
const FALLBACK_LANGUAGE = "plaintext";
|
|
41
|
+
const getEmbeddedLanguages = (code, languageId, highlighter) => {
|
|
42
|
+
const bundled = highlighter.getBundledLanguages();
|
|
43
|
+
return guessEmbeddedLanguages(code, languageId).flatMap((language) => bundled[language] ?? []);
|
|
44
|
+
};
|
|
45
|
+
const toArray = (value) => value == null ? [] : Array.isArray(value) ? value : [value];
|
|
46
|
+
const languageKey = (lang) => {
|
|
47
|
+
if (lang == null) return null;
|
|
48
|
+
if (typeof lang === "string") return `s:${lang}`;
|
|
49
|
+
return `o:${lang.name}::${lang.scopeName}`;
|
|
50
|
+
};
|
|
51
|
+
const dedupeLanguages = (langs) => {
|
|
52
|
+
const seen = /* @__PURE__ */ new Set();
|
|
53
|
+
const deduped = [];
|
|
54
|
+
for (const lang of langs) {
|
|
55
|
+
const key = languageKey(lang);
|
|
56
|
+
if (key == null || seen.has(key)) continue;
|
|
57
|
+
seen.add(key);
|
|
58
|
+
deduped.push(lang);
|
|
59
|
+
}
|
|
60
|
+
return deduped;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Used in factories to check if language is supported.
|
|
64
|
+
* Objects are validated as grammar registrations (name + scopeName).
|
|
65
|
+
*/
|
|
66
|
+
const isLoadableLanguage = (lang, bundledLanguages) => {
|
|
67
|
+
if (lang == null) return false;
|
|
68
|
+
if (typeof lang === "string") return lang in bundledLanguages;
|
|
69
|
+
return typeof lang.name === "string" && typeof lang.scopeName === "string";
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Used in hook to resolve loaded language for highlighting.
|
|
73
|
+
* Falls back to "plaintext" if not supported.
|
|
74
|
+
*/
|
|
75
|
+
const resolveLoadedLanguage = (languageId, loadedLanguages) => isSpecialLang(languageId) || loadedLanguages.includes(languageId) ? languageId : FALLBACK_LANGUAGE;
|
|
76
|
+
/**
|
|
77
|
+
* Resolves the language input to standardized IDs and objects for Shiki
|
|
78
|
+
* @param lang The language input from props
|
|
79
|
+
* @param customLanguages An array of custom textmate grammar objects or a single grammar object
|
|
80
|
+
* @returns A LanguageResult object containing:
|
|
81
|
+
* - languageId: The resolved language ID
|
|
82
|
+
* - langsToLoad: The language objects/string ids to load
|
|
83
|
+
*/
|
|
84
|
+
const resolveLanguage = (lang, customLanguages, langAliases, preloadLanguages) => {
|
|
85
|
+
const customLangs = toArray(customLanguages);
|
|
86
|
+
const preloadLangs = toArray(preloadLanguages);
|
|
87
|
+
const customMatchPool = [...customLangs, ...preloadLangs];
|
|
88
|
+
let languageId = FALLBACK_LANGUAGE;
|
|
89
|
+
let primaryLang;
|
|
90
|
+
if (lang == null || typeof lang === "string" && !lang.trim()) return {
|
|
91
|
+
languageId,
|
|
92
|
+
langsToLoad: dedupeLanguages([...preloadLangs, ...customLangs])
|
|
93
|
+
};
|
|
94
|
+
if (typeof lang === "object") {
|
|
95
|
+
languageId = lang.name;
|
|
96
|
+
primaryLang = lang;
|
|
97
|
+
} else {
|
|
98
|
+
const lowerLang = lang.toLowerCase();
|
|
99
|
+
const matches = (str) => str?.toLowerCase() === lowerLang;
|
|
100
|
+
const customMatch = customMatchPool.find((candidate) => typeof candidate === "object" && candidate != null && !!(matches(candidate.name) || matches(candidate.scopeName) || matches(candidate.scopeName?.split(".").pop()) || candidate.aliases?.some(matches) || candidate.fileTypes?.some(matches)));
|
|
101
|
+
if (customMatch) {
|
|
102
|
+
languageId = customMatch.name || lang;
|
|
103
|
+
primaryLang = customMatch;
|
|
104
|
+
} else if (langAliases?.[lang]) {
|
|
105
|
+
languageId = langAliases[lang];
|
|
106
|
+
primaryLang = langAliases[lang];
|
|
107
|
+
} else {
|
|
108
|
+
languageId = lang;
|
|
109
|
+
primaryLang = lang;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
languageId,
|
|
114
|
+
langsToLoad: dedupeLanguages([
|
|
115
|
+
primaryLang,
|
|
116
|
+
...preloadLangs,
|
|
117
|
+
...customLangs
|
|
118
|
+
])
|
|
119
|
+
};
|
|
120
|
+
};
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/lib/theme.ts
|
|
123
|
+
const DEFAULT_THEMES = {
|
|
124
|
+
light: "github-light",
|
|
125
|
+
dark: "github-dark"
|
|
126
|
+
};
|
|
127
|
+
const isTextmateTheme = (value) => {
|
|
128
|
+
if (typeof value !== "object" || value === null) return false;
|
|
129
|
+
const v = value;
|
|
130
|
+
const hasTokens = Array.isArray(v.tokenColors) || Array.isArray(v.settings);
|
|
131
|
+
const hasIdentity = typeof v.name === "string" || typeof v.type === "string";
|
|
132
|
+
return hasTokens && hasIdentity;
|
|
133
|
+
};
|
|
134
|
+
function resolveTheme(themeInput) {
|
|
135
|
+
if (typeof themeInput !== "object" || themeInput === null || isTextmateTheme(themeInput)) return {
|
|
136
|
+
isMulti: false,
|
|
137
|
+
theme: themeInput,
|
|
138
|
+
themesToLoad: [themeInput]
|
|
139
|
+
};
|
|
140
|
+
const validEntries = Object.entries(themeInput).filter(([key, value]) => key.trim() !== "" && (typeof value === "string" && value.trim() !== "" || isTextmateTheme(value)));
|
|
141
|
+
if (validEntries.length === 0) {
|
|
142
|
+
console.warn("[react-shiki] invalid multi-theme config, falling back to defaults");
|
|
143
|
+
return {
|
|
144
|
+
isMulti: true,
|
|
145
|
+
themes: DEFAULT_THEMES,
|
|
146
|
+
themesToLoad: Object.values(DEFAULT_THEMES)
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (validEntries.length !== Object.keys(themeInput).length) console.warn("[react-shiki] multi-theme config contained invalid entries; they were dropped");
|
|
150
|
+
return {
|
|
151
|
+
isMulti: true,
|
|
152
|
+
themes: Object.fromEntries(validEntries),
|
|
153
|
+
themesToLoad: validEntries.map(([, value]) => value)
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
//#endregion
|
|
157
|
+
//#region src/lib/transformers.ts
|
|
158
|
+
/**
|
|
159
|
+
* Creates a transformer that enables line numbers display
|
|
160
|
+
* @param startLine - The starting line number (defaults to 1)
|
|
161
|
+
*/
|
|
162
|
+
function lineNumbersTransformer(startLine = 1) {
|
|
163
|
+
return {
|
|
164
|
+
name: "react-shiki:line-numbers",
|
|
165
|
+
code(node) {
|
|
166
|
+
this.addClassToHast(node, "has-line-numbers");
|
|
167
|
+
this.addClassToHast(node, "rs-has-line-numbers");
|
|
168
|
+
if (startLine !== 1) {
|
|
169
|
+
const existingStyle = node.properties?.style || "";
|
|
170
|
+
const newStyle = existingStyle ? `${existingStyle}; --line-start: ${startLine}` : `--line-start: ${startLine}`;
|
|
171
|
+
node.properties = {
|
|
172
|
+
...node.properties,
|
|
173
|
+
style: newStyle
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
line(node) {
|
|
178
|
+
this.addClassToHast(node, "line-numbers");
|
|
179
|
+
this.addClassToHast(node, "rs-line-number");
|
|
180
|
+
return node;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
185
|
+
//#region src/lib/options.ts
|
|
186
|
+
const buildThemeOptions = (resolvedTheme, defaultColor, cssVariablePrefix) => {
|
|
187
|
+
if (resolvedTheme.isMulti) return {
|
|
188
|
+
themes: resolvedTheme.themes,
|
|
189
|
+
defaultColor,
|
|
190
|
+
cssVariablePrefix
|
|
191
|
+
};
|
|
192
|
+
return { theme: resolvedTheme.theme };
|
|
193
|
+
};
|
|
194
|
+
const buildShikiOptions = (languageId, resolvedTheme, options) => {
|
|
195
|
+
const { delay, customLanguages, preloadLanguages, outputFormat, highlighter, langAlias, engine, defaultColor, cssVariablePrefix, showLineNumbers, startingLineNumber, transformers: userTransformers, ...shikiPassthrough } = options;
|
|
196
|
+
const transformers = [...userTransformers || []];
|
|
197
|
+
if (showLineNumbers) transformers.push(lineNumbersTransformer(startingLineNumber));
|
|
198
|
+
return {
|
|
199
|
+
lang: languageId,
|
|
200
|
+
...buildThemeOptions(resolvedTheme, defaultColor, cssVariablePrefix),
|
|
201
|
+
...shikiPassthrough,
|
|
202
|
+
transformers
|
|
203
|
+
};
|
|
204
|
+
};
|
|
205
|
+
//#endregion
|
|
206
|
+
//#region src/lib/hook.ts
|
|
207
|
+
async function highlight(code, resolved, opts, factory) {
|
|
208
|
+
const { languageId, langsToLoad, themesToLoad, shikiOptions } = resolved;
|
|
209
|
+
const highlighter = opts.highlighter ?? await (async () => {
|
|
210
|
+
const hl = await factory(langsToLoad, themesToLoad, opts.engine);
|
|
211
|
+
await hl.loadLanguage(...getEmbeddedLanguages(code, languageId, hl));
|
|
212
|
+
return hl;
|
|
213
|
+
})();
|
|
214
|
+
const language = resolveLoadedLanguage(languageId, highlighter.getLoadedLanguages());
|
|
215
|
+
const options = {
|
|
216
|
+
...shikiOptions,
|
|
217
|
+
lang: language
|
|
218
|
+
};
|
|
219
|
+
return opts.outputFormat === "html" ? highlighter.codeToHtml(code, options) : toJsxRuntime(highlighter.codeToHast(code, options), {
|
|
220
|
+
jsx,
|
|
221
|
+
jsxs,
|
|
222
|
+
Fragment
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
const useHighlight = (code, lang, themeInput, options = {}, highlighterFactory) => {
|
|
226
|
+
const [highlightedCode, setHighlightedCode] = useState(null);
|
|
227
|
+
const stableLang = useStableValue(lang);
|
|
228
|
+
const stableTheme = useStableValue(themeInput);
|
|
229
|
+
const stableOpts = useStableValue(options);
|
|
230
|
+
const resolved = useMemo(() => {
|
|
231
|
+
const { languageId, langsToLoad } = resolveLanguage(stableLang, stableOpts.customLanguages, stableOpts.langAlias, stableOpts.preloadLanguages);
|
|
232
|
+
const theme = resolveTheme(stableTheme);
|
|
233
|
+
const shikiOptions = buildShikiOptions(languageId, theme, stableOpts);
|
|
234
|
+
return {
|
|
235
|
+
languageId,
|
|
236
|
+
langsToLoad,
|
|
237
|
+
themesToLoad: theme.themesToLoad,
|
|
238
|
+
shikiOptions
|
|
239
|
+
};
|
|
240
|
+
}, [
|
|
241
|
+
stableLang,
|
|
242
|
+
stableTheme,
|
|
243
|
+
stableOpts
|
|
244
|
+
]);
|
|
245
|
+
const requestIdRef = useRef(0);
|
|
246
|
+
const timeoutControl = useRef({
|
|
247
|
+
nextAllowedTime: 0,
|
|
248
|
+
timeoutId: void 0
|
|
249
|
+
});
|
|
250
|
+
useEffect(() => {
|
|
251
|
+
const requestId = ++requestIdRef.current;
|
|
252
|
+
if (!resolved.languageId) return;
|
|
253
|
+
const run = async () => {
|
|
254
|
+
try {
|
|
255
|
+
const result = await highlight(code, resolved, stableOpts, highlighterFactory);
|
|
256
|
+
if (requestId === requestIdRef.current) setHighlightedCode(result);
|
|
257
|
+
} catch (error) {
|
|
258
|
+
console.error("[react-shiki] highlight failed", error);
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
if (stableOpts.delay) throttleHighlighting(run, timeoutControl, stableOpts.delay);
|
|
262
|
+
else run();
|
|
263
|
+
return () => {
|
|
264
|
+
clearTimeout(timeoutControl.current.timeoutId);
|
|
265
|
+
};
|
|
266
|
+
}, [
|
|
267
|
+
code,
|
|
268
|
+
resolved,
|
|
269
|
+
stableOpts,
|
|
270
|
+
highlighterFactory
|
|
271
|
+
]);
|
|
272
|
+
return highlightedCode;
|
|
273
|
+
};
|
|
274
|
+
//#endregion
|
|
275
|
+
//#region src/lib/plugins.ts
|
|
276
|
+
/**
|
|
277
|
+
* Rehype plugin to add an 'inline' property to <code> elements
|
|
278
|
+
* Sets 'inline' property to true if the <code> is not within a <pre> tag
|
|
279
|
+
*
|
|
280
|
+
* Pass this plugin to the `rehypePlugins` prop of react-markdown
|
|
281
|
+
* You can then access `inline` as a prop in components passed to react-markdown
|
|
282
|
+
*
|
|
283
|
+
* @example
|
|
284
|
+
* <ReactMarkdown rehypePlugins={[rehypeInlineCodeProperty]} />
|
|
285
|
+
*/
|
|
286
|
+
function rehypeInlineCodeProperty() {
|
|
287
|
+
return (tree) => {
|
|
288
|
+
visit(tree, "element", (node, _index, parent) => {
|
|
289
|
+
if (node.tagName === "code" && parent?.type === "element" && parent.tagName !== "pre") node.properties.inline = true;
|
|
290
|
+
});
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Function to determine if code is inline based on the presence of line breaks
|
|
295
|
+
*
|
|
296
|
+
* @example
|
|
297
|
+
* const isInline = node && isInlineCode(node: Element)
|
|
298
|
+
*/
|
|
299
|
+
const isInlineCode = (node) => {
|
|
300
|
+
return !(node.children || []).filter((child) => child.type === "text").map((child) => child.value).join("").includes("\n");
|
|
301
|
+
};
|
|
302
|
+
//#endregion
|
|
303
|
+
//#region src/lib/component.tsx
|
|
304
|
+
/**
|
|
305
|
+
* Base ShikiHighlighter component factory.
|
|
306
|
+
* This creates a component that uses the provided hook implementation.
|
|
307
|
+
*/
|
|
308
|
+
const createShikiHighlighterComponent = (useShikiHighlighterImpl) => {
|
|
309
|
+
return forwardRef(({ language, theme, delay, transformers, defaultColor, cssVariablePrefix, addDefaultStyles = true, style, langStyle, className, langClassName, showLanguage = true, showLineNumbers = false, startingLineNumber = 1, children: code, as: Element = "div", customLanguages, preloadLanguages, ...shikiOptions }, ref) => {
|
|
310
|
+
const options = {
|
|
311
|
+
delay,
|
|
312
|
+
transformers,
|
|
313
|
+
customLanguages,
|
|
314
|
+
preloadLanguages,
|
|
315
|
+
showLineNumbers,
|
|
316
|
+
defaultColor,
|
|
317
|
+
cssVariablePrefix,
|
|
318
|
+
startingLineNumber,
|
|
319
|
+
...shikiOptions
|
|
320
|
+
};
|
|
321
|
+
const displayLanguageId = typeof language === "object" ? language.name || null : language?.trim() || null;
|
|
322
|
+
const highlightedCode = useShikiHighlighterImpl(code, language, theme, options);
|
|
323
|
+
return /* @__PURE__ */ jsxs(Element, {
|
|
324
|
+
ref,
|
|
325
|
+
"data-testid": "shiki-container",
|
|
326
|
+
"data-slot": "container",
|
|
327
|
+
className: clsx("rs-root", "not-prose", addDefaultStyles && "rs-default-styles", className),
|
|
328
|
+
style,
|
|
329
|
+
children: [showLanguage && displayLanguageId ? /* @__PURE__ */ jsx("span", {
|
|
330
|
+
id: "language-label",
|
|
331
|
+
"data-slot": "language-label",
|
|
332
|
+
className: clsx("rs-language-label", langClassName),
|
|
333
|
+
style: langStyle,
|
|
334
|
+
children: displayLanguageId
|
|
335
|
+
}) : null, typeof highlightedCode === "string" ? /* @__PURE__ */ jsx("div", {
|
|
336
|
+
"data-slot": "content",
|
|
337
|
+
dangerouslySetInnerHTML: { __html: highlightedCode }
|
|
338
|
+
}) : highlightedCode]
|
|
339
|
+
});
|
|
340
|
+
});
|
|
341
|
+
};
|
|
342
|
+
//#endregion
|
|
343
|
+
export { isLoadableLanguage as a, useHighlight as i, isInlineCode as n, rehypeInlineCodeProperty as r, createShikiHighlighterComponent as t };
|
|
344
|
+
|
|
345
|
+
//# sourceMappingURL=component-C5lsWZSq.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"component-C5lsWZSq.mjs","names":[],"sources":["../src/lib/utils.ts","../src/lib/language.ts","../src/lib/theme.ts","../src/lib/transformers.ts","../src/lib/options.ts","../src/lib/hook.ts","../src/lib/plugins.ts","../src/lib/component.tsx"],"sourcesContent":["import { useRef } from 'react';\nimport { dequal } from 'dequal';\n\nimport type { TimeoutState } from './types';\n\n/**\n * Returns a referentially stable version of `value` that only updates when content changes.\n * Uses reference equality as a fast path and deep comparison to prevent unnecessary updates.\n */\nexport const useStableValue = <T>(value: T): T => {\n const ref = useRef(value);\n\n if (value !== ref.current && !dequal(value, ref.current)) {\n ref.current = value;\n }\n\n return ref.current;\n};\n\n/**\n * Optionally throttles rapid sequential highlighting operations\n *\n * @example\n * const timeoutControl = useRef<TimeoutState>({\n * nextAllowedTime: 0,\n * timeoutId: undefined\n * });\n *\n * throttleHighlighting(highlightCode, timeoutControl, 1000);\n */\nexport const throttleHighlighting = (\n performHighlight: () => Promise<void>,\n timeoutControl: React.RefObject<TimeoutState>,\n throttleMs: number\n) => {\n clearTimeout(timeoutControl.current.timeoutId);\n\n const delay = Math.max(\n 0,\n timeoutControl.current.nextAllowedTime - Date.now()\n );\n timeoutControl.current.timeoutId = setTimeout(() => {\n performHighlight();\n timeoutControl.current.nextAllowedTime = Date.now() + throttleMs;\n }, delay);\n};\n","import type { Language } from './types';\nimport { guessEmbeddedLanguages, isSpecialLang } from 'shiki/core';\nimport type {\n DynamicImportLanguageRegistration,\n Highlighter,\n HighlighterCore,\n LanguageInput,\n LanguageRegistration,\n} from 'shiki';\n\nexport const FALLBACK_LANGUAGE = 'plaintext';\n\nexport const getEmbeddedLanguages = (\n code: string,\n languageId: string,\n highlighter: Highlighter | HighlighterCore\n): LanguageInput[] => {\n const bundled: Record<string, LanguageInput> =\n highlighter.getBundledLanguages();\n return guessEmbeddedLanguages(code, languageId).flatMap(\n (language) => bundled[language] ?? []\n );\n};\n\n/**\n * Resolved languages and metadata\n */\ntype LanguageResult = {\n languageId: string;\n langsToLoad: Language[];\n};\n\nconst toArray = <T>(value?: T | T[]): T[] =>\n value == null ? [] : Array.isArray(value) ? value : [value];\n\nconst languageKey = (lang: Language): string | null => {\n if (lang == null) return null;\n if (typeof lang === 'string') return `s:${lang}`;\n return `o:${lang.name}::${lang.scopeName}`;\n};\n\nconst dedupeLanguages = (langs: Language[]): Language[] => {\n const seen = new Set<string>();\n const deduped: Language[] = [];\n\n for (const lang of langs) {\n const key = languageKey(lang);\n if (key == null || seen.has(key)) continue;\n seen.add(key);\n deduped.push(lang);\n }\n\n return deduped;\n};\n\n/**\n * Used in factories to check if language is supported.\n * Objects are validated as grammar registrations (name + scopeName).\n */\nexport const isLoadableLanguage = <T extends string>(\n lang: Language,\n bundledLanguages: Record<T, DynamicImportLanguageRegistration>\n): lang is NonNullable<Language> => {\n if (lang == null) return false;\n if (typeof lang === 'string') return lang in bundledLanguages;\n return (\n typeof lang.name === 'string' && typeof lang.scopeName === 'string'\n );\n};\n\n/**\n * Used in hook to resolve loaded language for highlighting.\n * Falls back to \"plaintext\" if not supported.\n */\nexport const resolveLoadedLanguage = (\n languageId: string,\n loadedLanguages: string[]\n): string =>\n isSpecialLang(languageId) || loadedLanguages.includes(languageId)\n ? languageId\n : FALLBACK_LANGUAGE;\n\n/**\n * Resolves the language input to standardized IDs and objects for Shiki\n * @param lang The language input from props\n * @param customLanguages An array of custom textmate grammar objects or a single grammar object\n * @returns A LanguageResult object containing:\n * - languageId: The resolved language ID\n * - langsToLoad: The language objects/string ids to load\n */\nexport const resolveLanguage = (\n lang: Language,\n customLanguages?: LanguageRegistration | LanguageRegistration[],\n langAliases?: Record<string, string>,\n preloadLanguages?: Language | Language[]\n): LanguageResult => {\n const customLangs = toArray(customLanguages);\n const preloadLangs = toArray(preloadLanguages);\n const customMatchPool = [...customLangs, ...preloadLangs];\n let languageId = FALLBACK_LANGUAGE;\n let primaryLang: Language;\n\n // Language is null or empty string\n if (lang == null || (typeof lang === 'string' && !lang.trim())) {\n return {\n languageId,\n langsToLoad: dedupeLanguages([...preloadLangs, ...customLangs]),\n };\n }\n\n // Language is custom object\n if (typeof lang === 'object') {\n languageId = lang.name;\n primaryLang = lang;\n } else {\n // Language is string\n const lowerLang = lang.toLowerCase();\n const matches = (str: string | undefined): boolean =>\n str?.toLowerCase() === lowerLang;\n\n // Check custom registrations (from both customLanguages and preloadLanguages)\n const customMatch = customMatchPool.find(\n (candidate): candidate is LanguageRegistration =>\n typeof candidate === 'object' &&\n candidate != null &&\n !!(\n matches(candidate.name) ||\n matches(candidate.scopeName) ||\n matches(candidate.scopeName?.split('.').pop()) ||\n candidate.aliases?.some(matches) ||\n candidate.fileTypes?.some(matches)\n )\n );\n\n if (customMatch) {\n languageId = customMatch.name || lang;\n primaryLang = customMatch;\n } else if (langAliases?.[lang]) {\n // Language is aliased\n languageId = langAliases[lang];\n primaryLang = langAliases[lang];\n } else {\n // For any other string, pass it through to the factory\n languageId = lang;\n primaryLang = lang;\n }\n }\n\n return {\n languageId,\n langsToLoad: dedupeLanguages([\n primaryLang,\n ...preloadLangs,\n ...customLangs,\n ]),\n };\n};\n","import type { Theme, Themes } from './types';\nimport type { ThemeRegistrationAny } from 'shiki/core';\n\nexport const DEFAULT_THEMES: Themes = {\n light: 'github-light',\n dark: 'github-dark',\n};\n\nexport type ResolvedTheme =\n | { isMulti: true; themes: Themes; themesToLoad: Theme[] }\n | { isMulti: false; theme: Theme; themesToLoad: Theme[] };\n\nconst isTextmateTheme = (\n value: unknown\n): value is ThemeRegistrationAny => {\n if (typeof value !== 'object' || value === null) return false;\n const v = value as Partial<ThemeRegistrationAny> & {\n settings?: unknown;\n };\n const hasTokens =\n Array.isArray(v.tokenColors) || Array.isArray(v.settings);\n const hasIdentity =\n typeof v.name === 'string' || typeof v.type === 'string';\n return hasTokens && hasIdentity;\n};\n\nexport function resolveTheme(themeInput: Theme | Themes): ResolvedTheme {\n if (\n typeof themeInput !== 'object' ||\n themeInput === null ||\n isTextmateTheme(themeInput)\n ) {\n return {\n isMulti: false,\n theme: themeInput,\n themesToLoad: [themeInput],\n };\n }\n\n const validEntries = Object.entries(themeInput).filter(\n ([key, value]) =>\n key.trim() !== '' &&\n ((typeof value === 'string' && value.trim() !== '') ||\n isTextmateTheme(value))\n );\n\n if (validEntries.length === 0) {\n console.warn(\n '[react-shiki] invalid multi-theme config, falling back to defaults'\n );\n return {\n isMulti: true,\n themes: DEFAULT_THEMES,\n themesToLoad: Object.values(DEFAULT_THEMES),\n };\n }\n\n if (validEntries.length !== Object.keys(themeInput).length) {\n console.warn(\n '[react-shiki] multi-theme config contained invalid entries; they were dropped'\n );\n }\n\n const themes = Object.fromEntries(validEntries) as Themes;\n return {\n isMulti: true,\n themes,\n themesToLoad: validEntries.map(([, value]) => value as Theme),\n };\n}\n","import type { ShikiTransformer } from 'shiki/core';\n\n/**\n * Creates a transformer that enables line numbers display\n * @param startLine - The starting line number (defaults to 1)\n */\nexport function lineNumbersTransformer(startLine = 1): ShikiTransformer {\n return {\n name: 'react-shiki:line-numbers',\n code(node) {\n this.addClassToHast(node, 'has-line-numbers');\n this.addClassToHast(node, 'rs-has-line-numbers');\n if (startLine !== 1) {\n const existingStyle = (node.properties?.style as string) || '';\n const newStyle = existingStyle\n ? `${existingStyle}; --line-start: ${startLine}`\n : `--line-start: ${startLine}`;\n node.properties = {\n ...node.properties,\n style: newStyle,\n };\n }\n },\n line(node) {\n this.addClassToHast(node, 'line-numbers');\n this.addClassToHast(node, 'rs-line-number');\n return node;\n },\n };\n}\n","import type {\n BundledTheme,\n CodeOptionsMultipleThemes,\n CodeOptionsSingleTheme,\n CodeToHastOptions,\n} from 'shiki';\n\nimport type { HighlighterOptions } from './types';\nimport type { ResolvedTheme } from './theme';\nimport { lineNumbersTransformer } from './transformers';\n\nconst buildThemeOptions = (\n resolvedTheme: ResolvedTheme,\n defaultColor: HighlighterOptions['defaultColor'],\n cssVariablePrefix: HighlighterOptions['cssVariablePrefix']\n):\n | CodeOptionsMultipleThemes<BundledTheme>\n | CodeOptionsSingleTheme<BundledTheme> => {\n if (resolvedTheme.isMulti) {\n return {\n themes: resolvedTheme.themes,\n defaultColor,\n cssVariablePrefix,\n };\n }\n\n return {\n theme: resolvedTheme.theme,\n };\n};\n\nexport const buildShikiOptions = (\n languageId: string,\n resolvedTheme: ResolvedTheme,\n options: HighlighterOptions\n): CodeToHastOptions => {\n const {\n delay,\n customLanguages,\n preloadLanguages,\n outputFormat,\n highlighter,\n langAlias,\n engine,\n defaultColor,\n cssVariablePrefix,\n showLineNumbers,\n startingLineNumber,\n transformers: userTransformers,\n ...shikiPassthrough\n } = options;\n\n const transformers = [...(userTransformers || [])];\n if (showLineNumbers) {\n transformers.push(lineNumbersTransformer(startingLineNumber));\n }\n\n return {\n lang: languageId,\n ...buildThemeOptions(resolvedTheme, defaultColor, cssVariablePrefix),\n ...shikiPassthrough,\n transformers,\n };\n};\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport { toJsxRuntime } from 'hast-util-to-jsx-runtime';\nimport type { CodeToHastOptions } from 'shiki';\n\nimport type {\n HighlightedCode,\n HighlighterFactory,\n HighlighterOptions,\n Language,\n Theme,\n Themes,\n TimeoutState,\n} from './types';\n\nimport { throttleHighlighting, useStableValue } from './utils';\nimport {\n getEmbeddedLanguages,\n resolveLanguage,\n resolveLoadedLanguage,\n} from './language';\nimport { resolveTheme } from './theme';\nimport { buildShikiOptions } from './options';\n\nexport async function highlight(\n code: string,\n resolved: {\n languageId: string;\n langsToLoad: Language[];\n themesToLoad: Theme[];\n shikiOptions: CodeToHastOptions;\n },\n opts: Pick<\n HighlighterOptions,\n 'highlighter' | 'outputFormat' | 'engine'\n >,\n factory: HighlighterFactory\n) {\n const { languageId, langsToLoad, themesToLoad, shikiOptions } =\n resolved;\n\n const highlighter =\n opts.highlighter ??\n (await (async () => {\n const hl = await factory(langsToLoad, themesToLoad, opts.engine);\n await hl.loadLanguage(\n ...getEmbeddedLanguages(code, languageId, hl)\n );\n return hl;\n })());\n\n const language = resolveLoadedLanguage(\n languageId,\n highlighter.getLoadedLanguages()\n );\n const options = { ...shikiOptions, lang: language };\n\n return opts.outputFormat === 'html'\n ? highlighter.codeToHtml(code, options)\n : toJsxRuntime(highlighter.codeToHast(code, options), {\n jsx,\n jsxs,\n Fragment,\n });\n}\n\nexport const useHighlight = (\n code: string,\n lang: Language,\n themeInput: Theme | Themes,\n options: HighlighterOptions = {},\n highlighterFactory: HighlighterFactory\n) => {\n const [highlightedCode, setHighlightedCode] =\n useState<HighlightedCode>(null);\n\n const stableLang = useStableValue(lang);\n const stableTheme = useStableValue(themeInput);\n const stableOpts = useStableValue(options);\n\n const resolved = useMemo(() => {\n const { languageId, langsToLoad } = resolveLanguage(\n stableLang,\n stableOpts.customLanguages,\n stableOpts.langAlias,\n stableOpts.preloadLanguages\n );\n\n const theme = resolveTheme(stableTheme);\n\n const shikiOptions = buildShikiOptions(languageId, theme, stableOpts);\n return {\n languageId,\n langsToLoad,\n themesToLoad: theme.themesToLoad,\n shikiOptions,\n };\n }, [stableLang, stableTheme, stableOpts]);\n\n const requestIdRef = useRef(0);\n\n const timeoutControl = useRef<TimeoutState>({\n nextAllowedTime: 0,\n timeoutId: undefined,\n });\n\n useEffect(() => {\n const requestId = ++requestIdRef.current;\n\n if (!resolved.languageId) return;\n\n const run = async () => {\n try {\n const result = await highlight(\n code,\n resolved,\n stableOpts,\n highlighterFactory\n );\n if (requestId === requestIdRef.current) {\n setHighlightedCode(result);\n }\n } catch (error) {\n console.error('[react-shiki] highlight failed', error);\n }\n };\n\n if (stableOpts.delay) {\n throttleHighlighting(run, timeoutControl, stableOpts.delay);\n } else {\n run();\n }\n\n return () => {\n clearTimeout(timeoutControl.current.timeoutId);\n };\n }, [code, resolved, stableOpts, highlighterFactory]);\n\n return highlightedCode;\n};\n","import { visit } from 'unist-util-visit';\nimport type { Root } from 'hast';\nimport type { Element } from './types';\n\n/**\n * Rehype plugin to add an 'inline' property to <code> elements\n * Sets 'inline' property to true if the <code> is not within a <pre> tag\n *\n * Pass this plugin to the `rehypePlugins` prop of react-markdown\n * You can then access `inline` as a prop in components passed to react-markdown\n *\n * @example\n * <ReactMarkdown rehypePlugins={[rehypeInlineCodeProperty]} />\n */\nexport function rehypeInlineCodeProperty() {\n return (tree: Root): undefined => {\n visit(tree, 'element', (node: Element, _index, parent) => {\n if (\n node.tagName === 'code' &&\n parent?.type === 'element' &&\n parent.tagName !== 'pre'\n ) {\n node.properties.inline = true;\n }\n });\n };\n}\n\n/**\n * Function to determine if code is inline based on the presence of line breaks\n *\n * @example\n * const isInline = node && isInlineCode(node: Element)\n */\nexport const isInlineCode = (node: Element): boolean => {\n const textContent = (node.children || [])\n .filter((child) => child.type === 'text')\n .map((child) => child.value)\n .join('');\n\n return !textContent.includes('\\n');\n};\n","import '../styles/component.css';\nimport '../styles/features.css';\nimport { clsx } from 'clsx';\n\nimport type {\n HighlighterOptions,\n Language,\n Theme,\n Themes,\n UseShikiHighlighter,\n} from './types';\nimport { forwardRef } from 'react';\n\n/**\n * Props for the ShikiHighlighter component\n */\nexport interface ShikiHighlighterProps extends HighlighterOptions {\n /**\n * The programming language for syntax highlighting\n * Supports custom textmate grammar objects in addition to Shiki's bundled languages\n * @see https://shiki.style/languages\n */\n language: Language;\n\n /**\n * The code to be highlighted\n */\n children: string;\n\n /**\n * The color theme or themes for syntax highlighting\n * Supports single, dual, or multiple themes\n * Supports custom textmate theme objects in addition to Shiki's bundled themes\n *\n * @example\n * theme='github-dark' // single theme\n * theme={{ light: 'github-light', dark: 'github-dark' }} // multi-theme\n *\n * @see https://shiki.style/themes\n */\n theme: Theme | Themes;\n\n /**\n * Controls the application of default styles to the generated code blocks\n *\n * Default styles include padding, overflow handling, border radius, language label styling, and font settings\n * @default true\n */\n addDefaultStyles?: boolean;\n\n /**\n * Add custom inline styles to the generated code block\n */\n style?: React.CSSProperties;\n\n /**\n * Add custom inline styles to the language label\n */\n langStyle?: React.CSSProperties;\n\n /**\n * Add custom CSS class names to the generated code block\n */\n className?: string;\n\n /**\n * Add custom CSS class names to the language label\n */\n langClassName?: string;\n\n /**\n * Whether to show the language label\n * @default true\n */\n showLanguage?: boolean;\n\n /**\n * Whether to show line numbers\n * @default false\n */\n showLineNumbers?: boolean;\n\n /**\n * Starting line number (when showLineNumbers is true)\n * @default 1\n */\n startingLineNumber?: number;\n\n /**\n * The HTML element that wraps the generated code block.\n * @default 'div'\n */\n as?: React.ElementType;\n}\n\n/**\n * Base ShikiHighlighter component factory.\n * This creates a component that uses the provided hook implementation.\n */\nexport const createShikiHighlighterComponent = (\n useShikiHighlighterImpl: UseShikiHighlighter\n) => {\n return forwardRef<HTMLElement, ShikiHighlighterProps>(\n (\n {\n language,\n theme,\n delay,\n transformers,\n defaultColor,\n cssVariablePrefix,\n addDefaultStyles = true,\n style,\n langStyle,\n className,\n langClassName,\n showLanguage = true,\n showLineNumbers = false,\n startingLineNumber = 1,\n children: code,\n as: Element = 'div',\n customLanguages,\n preloadLanguages,\n ...shikiOptions\n },\n ref\n ) => {\n // Destructure some options for use in hook\n const options: HighlighterOptions = {\n delay,\n transformers,\n customLanguages,\n preloadLanguages,\n showLineNumbers,\n defaultColor,\n cssVariablePrefix,\n startingLineNumber,\n ...shikiOptions,\n };\n\n const displayLanguageId =\n typeof language === 'object'\n ? language.name || null\n : language?.trim() || null;\n\n const highlightedCode = useShikiHighlighterImpl(\n code,\n language,\n theme,\n options\n );\n\n return (\n <Element\n ref={ref}\n data-testid=\"shiki-container\"\n data-slot=\"container\"\n className={clsx(\n 'rs-root',\n 'not-prose',\n addDefaultStyles && 'rs-default-styles',\n className\n )}\n style={style}\n >\n {showLanguage && displayLanguageId ? (\n <span\n id=\"language-label\"\n data-slot=\"language-label\"\n className={clsx('rs-language-label', langClassName)}\n style={langStyle}\n >\n {displayLanguageId}\n </span>\n ) : null}\n {typeof highlightedCode === 'string' ? (\n <div\n data-slot=\"content\"\n dangerouslySetInnerHTML={{ __html: highlightedCode }}\n />\n ) : (\n highlightedCode\n )}\n </Element>\n );\n }\n );\n};\n"],"mappings":";;;;;;;;;;;;AASA,MAAa,kBAAqB,UAAgB;CAChD,MAAM,MAAM,OAAO,MAAM;AAEzB,KAAI,UAAU,IAAI,WAAW,CAAC,OAAO,OAAO,IAAI,QAAQ,CACtD,KAAI,UAAU;AAGhB,QAAO,IAAI;;;;;;;;;;;;;AAcb,MAAa,wBACX,kBACA,gBACA,eACG;AACH,cAAa,eAAe,QAAQ,UAAU;CAE9C,MAAM,QAAQ,KAAK,IACjB,GACA,eAAe,QAAQ,kBAAkB,KAAK,KAAK,CACpD;AACD,gBAAe,QAAQ,YAAY,iBAAiB;AAClD,oBAAkB;AAClB,iBAAe,QAAQ,kBAAkB,KAAK,KAAK,GAAG;IACrD,MAAM;;;;AClCX,MAAa,oBAAoB;AAEjC,MAAa,wBACX,MACA,YACA,gBACoB;CACpB,MAAM,UACJ,YAAY,qBAAqB;AACnC,QAAO,uBAAuB,MAAM,WAAW,CAAC,SAC7C,aAAa,QAAQ,aAAa,EAAE,CACtC;;AAWH,MAAM,WAAc,UAClB,SAAS,OAAO,EAAE,GAAG,MAAM,QAAQ,MAAM,GAAG,QAAQ,CAAC,MAAM;AAE7D,MAAM,eAAe,SAAkC;AACrD,KAAI,QAAQ,KAAM,QAAO;AACzB,KAAI,OAAO,SAAS,SAAU,QAAO,KAAK;AAC1C,QAAO,KAAK,KAAK,KAAK,IAAI,KAAK;;AAGjC,MAAM,mBAAmB,UAAkC;CACzD,MAAM,uBAAO,IAAI,KAAa;C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