react-shiki 0.5.3 → 0.7.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/utils.ts","../src/lib/hook.ts","../src/lib/resolvers.ts","#style-inject:#style-inject","../src/lib/styles.css","../src/lib/component.tsx"],"sourcesContent":["import { visit } from 'unist-util-visit';\n\nimport type { TimeoutState, 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: any): undefined => {\n visit(tree, 'element', (node: Element, _index, parent: Element) => {\n if (node.tagName === 'code' && parent.tagName !== 'pre') {\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\n/**\n * Optionally throttles rapid sequential highlighting operations\n * Exported for testing in __tests__/throttleHighlighting.test.ts\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 const now = Date.now();\n clearTimeout(timeoutControl.current.timeoutId);\n\n const delay = Math.max(0, timeoutControl.current.nextAllowedTime - now);\n timeoutControl.current.timeoutId = setTimeout(() => {\n performHighlight().catch(console.error);\n timeoutControl.current.nextAllowedTime = now + throttleMs;\n }, delay);\n};\n","import {\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\n\nimport { dequal } from 'dequal/lite';\n\nimport { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport { toJsxRuntime } from 'hast-util-to-jsx-runtime';\n\nimport type {\n CodeToHastOptions,\n CodeOptionsSingleTheme,\n CodeOptionsMultipleThemes,\n Highlighter,\n HighlighterCore,\n} from 'shiki';\n\nimport type { ShikiLanguageRegistration } from './extended-types';\n\nimport type {\n Language,\n Theme,\n HighlighterOptions,\n TimeoutState,\n Themes,\n} from './types';\n\nimport { throttleHighlighting } from './utils';\nimport { resolveLanguage, resolveTheme } from './resolvers';\n\nconst DEFAULT_THEMES: Themes = {\n light: 'github-light',\n dark: 'github-dark',\n};\n\n/**\n * Returns a deep-stable reference and a version counter that only changes when content changes.\n * Includes optimizations for primitive values and reference equality.\n */\nconst useStableOptions = <T>(value: T) => {\n const ref = useRef(value);\n const revision = useRef(0);\n\n // Fast-path for primitive values\n if (typeof value !== 'object' || value === null) {\n if (value !== ref.current) {\n ref.current = value;\n revision.current += 1;\n }\n return [value, revision.current] as const;\n }\n\n // Reference equality check before expensive deep comparison\n if (value !== ref.current) {\n if (!dequal(value, ref.current)) {\n ref.current = value;\n revision.current += 1;\n }\n }\n\n return [ref.current, revision.current] as const;\n};\n\n/**\n * Base hook for syntax highlighting using Shiki.\n * This is the core implementation used by all entry points.\n *\n * @param code - The code to highlight\n * @param lang - Language for highlighting\n * @param themeInput - Theme or themes to use\n * @param options - Highlighting options\n * @param createHighlighter - Factory function to create highlighter (internal use)\n */\nexport const useShikiHighlighter = (\n code: string,\n lang: Language,\n themeInput: Theme | Themes,\n createHighlighter: (\n langsToLoad: ShikiLanguageRegistration,\n themesToLoad: Theme[]\n ) => Promise<Highlighter | HighlighterCore>,\n options: HighlighterOptions = {}\n) => {\n const [highlightedCode, setHighlightedCode] =\n useState<ReactNode | null>(null);\n\n // Stabilize options, language and theme inputs to prevent unnecessary\n // re-renders or recalculations when object references change\n const [stableLang, langRev] = useStableOptions(lang);\n const [stableTheme, themeRev] = useStableOptions(themeInput);\n const [stableOpts, optsRev] = useStableOptions(options);\n\n const { languageId, langsToLoad } = useMemo(\n () => resolveLanguage(stableLang, stableOpts.customLanguages),\n [stableLang, stableOpts.customLanguages]\n );\n\n const { isMultiTheme, themeId, multiTheme, singleTheme, themesToLoad } =\n useMemo(() => resolveTheme(stableTheme), [stableTheme]);\n\n const timeoutControl = useRef<TimeoutState>({\n nextAllowedTime: 0,\n timeoutId: undefined,\n });\n\n const shikiOptions = useMemo<CodeToHastOptions>(() => {\n const { defaultColor, cssVariablePrefix, ...restOptions } =\n stableOpts;\n const languageOption = { lang: languageId };\n\n const themeOptions = isMultiTheme\n ? ({\n themes: multiTheme || DEFAULT_THEMES,\n defaultColor,\n cssVariablePrefix,\n } as CodeOptionsMultipleThemes)\n : ({\n theme: singleTheme || DEFAULT_THEMES.dark,\n } as CodeOptionsSingleTheme);\n\n return { ...languageOption, ...themeOptions, ...restOptions };\n }, [languageId, themeId, langRev, themeRev, optsRev]);\n\n useEffect(() => {\n let isMounted = true;\n\n const highlightCode = async () => {\n if (!languageId) return;\n\n // Use provided custom highlighter or create one using the factory\n const highlighter = stableOpts.highlighter\n ? stableOpts.highlighter\n : await createHighlighter(\n langsToLoad as ShikiLanguageRegistration,\n themesToLoad\n );\n\n // Check if language is loaded, fallback to plaintext if not\n const loadedLanguages = highlighter.getLoadedLanguages();\n const langToUse = loadedLanguages.includes(languageId) ? languageId : 'plaintext';\n const finalOptions = { ...shikiOptions, lang: langToUse };\n \n const hast = highlighter.codeToHast(code, finalOptions);\n\n if (isMounted) {\n setHighlightedCode(toJsxRuntime(hast, { jsx, jsxs, Fragment }));\n }\n };\n\n const { delay } = stableOpts;\n\n if (delay) {\n throttleHighlighting(highlightCode, timeoutControl, delay);\n } else {\n highlightCode().catch(console.error);\n }\n\n return () => {\n isMounted = false;\n clearTimeout(timeoutControl.current.timeoutId);\n };\n }, [\n code,\n shikiOptions,\n stableOpts.delay,\n stableOpts.highlighter,\n langsToLoad,\n themesToLoad,\n ]);\n\n return highlightedCode;\n};\n","import type { Language, Theme, Themes } from './types';\nimport type { ThemeRegistrationAny } from 'shiki/core';\nimport type { LanguageRegistration } from './extended-types';\n\n/**\n * Resolved languages and metadata\n */\ntype LanguageResult = {\n languageId: string;\n displayLanguageId: string | null;\n langsToLoad: Language;\n};\n\n/**\n * Resolves the language input to standardized IDs and objects for Shiki and UI display\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 * - displayLanguageId: The display language ID\n * - langToLoad: The language object or string id to load\n */\nexport const resolveLanguage = (\n lang: Language,\n customLanguages?: LanguageRegistration | LanguageRegistration[]\n): LanguageResult => {\n const normalizedCustomLangs = customLanguages\n ? Array.isArray(customLanguages)\n ? customLanguages\n : [customLanguages]\n : [];\n\n // Language is null or empty string\n if (lang == null || (typeof lang === 'string' && !lang.trim())) {\n return {\n languageId: 'plaintext',\n displayLanguageId: 'plaintext',\n langsToLoad: undefined,\n };\n }\n\n // Language is custom\n if (typeof lang === 'object') {\n return {\n languageId: lang.name,\n displayLanguageId: lang.name || null,\n langsToLoad: lang,\n };\n }\n\n // Language is string\n const lowerLang = lang.toLowerCase();\n const matches = (str: string | undefined): boolean =>\n str?.toLowerCase() === lowerLang;\n\n // Check if the string identifies a provided custom language\n const customMatch = normalizedCustomLangs.find(\n (cl) =>\n matches(cl.name) ||\n matches(cl.scopeName) ||\n matches(cl.scopeName?.split('.').pop()) ||\n cl.aliases?.some(matches) ||\n cl.fileTypes?.some(matches)\n );\n\n if (customMatch) {\n return {\n languageId: customMatch.name || lang,\n displayLanguageId: lang,\n langsToLoad: customMatch,\n };\n }\n\n // For any other string, pass it through, \n // fallback is handled in highlighter factories\n return {\n languageId: lang,\n displayLanguageId: lang,\n langsToLoad: lang,\n };\n};\n\n/**\n * Resolved themes and metadata\n */\ninterface ThemeResult {\n isMultiTheme: boolean;\n themeId: Theme;\n multiTheme?: Themes | ThemeRegistrationAny | null;\n singleTheme?: Theme | undefined;\n themesToLoad: Theme[];\n}\n\n/**\n * Determines theme configuration and returns the resolved theme with metadata\n * @param themeInput - The theme input, either as a string name or theme object\n * @returns Object containing:\n * - isMultiTheme: If theme input is a multi-theme configuration\n * - themeId: Theme reference identifier\n * - multiTheme: The multi-theme config if it exists\n * - singleTheme: The single theme if it exists\n * - themesToLoad: The themes to load when creating the highlighter\n */\nexport function resolveTheme(themeInput: Theme | Themes): ThemeResult {\n const isTextmateTheme =\n typeof themeInput === 'object' &&\n 'tokenColors' in themeInput &&\n Array.isArray(themeInput.tokenColors);\n\n // Assume non textmate objects are multi theme configs\n const isMultiThemeConfig =\n typeof themeInput === 'object' &&\n themeInput !== null &&\n !isTextmateTheme;\n\n const validMultiThemeObj =\n typeof themeInput === 'object' &&\n themeInput !== null &&\n !isTextmateTheme &&\n Object.entries(themeInput).some(\n ([key, value]) =>\n key &&\n value &&\n key.trim() !== '' &&\n value !== '' &&\n (typeof value === 'string' || isTextmateTheme)\n );\n\n if (isMultiThemeConfig) {\n const themeId = validMultiThemeObj\n ? `multi-${Object.values(themeInput)\n .map(\n (theme) =>\n (typeof theme === 'string' ? theme : theme?.name) ||\n 'custom'\n )\n .sort()\n .join('-')}`\n : 'multi-default';\n\n // If config is invalid, return null to handle fallback in `buildShikiOptions()`\n return {\n isMultiTheme: true,\n themeId,\n multiTheme: validMultiThemeObj ? themeInput : null,\n themesToLoad: validMultiThemeObj ? Object.values(themeInput) : [],\n };\n }\n\n return {\n isMultiTheme: false,\n themeId:\n typeof themeInput === 'string'\n ? themeInput\n : themeInput?.name || 'custom',\n singleTheme: themeInput,\n themesToLoad: [themeInput],\n };\n}\n","\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\".relative {\\n position: relative;\\n}\\n.defaultStyles pre {\\n overflow: auto;\\n border-radius: 0.5rem;\\n padding-left: 1.5rem;\\n padding-right: 1.5rem;\\n padding-top: 1.25rem;\\n padding-bottom: 1.25rem;\\n}\\n.languageLabel {\\n position: absolute;\\n right: 0.75rem;\\n top: 0.5rem;\\n font-family: monospace;\\n font-size: 0.75rem;\\n letter-spacing: -0.05em;\\n color: rgba(107, 114, 128, 0.85);\\n}\\n\")","import './styles.css';\nimport { clsx } from 'clsx';\nimport { resolveLanguage } from './resolvers';\n\nimport type {\n HighlighterOptions,\n Language,\n Theme,\n Themes,\n} from './types';\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 * The HTML element that wraps the generated code block.\n * @default 'pre'\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: (\n code: string,\n lang: Language,\n themeInput: Theme | Themes,\n options?: HighlighterOptions\n ) => React.ReactNode\n) => {\n return ({\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 children: code,\n as: Element = 'pre',\n customLanguages,\n ...shikiOptions\n }: ShikiHighlighterProps): React.ReactElement => {\n const options: HighlighterOptions = {\n delay,\n transformers,\n customLanguages,\n defaultColor,\n cssVariablePrefix,\n ...shikiOptions,\n };\n\n // Use resolveLanguage to get displayLanguageId directly\n const { displayLanguageId } = resolveLanguage(\n language,\n customLanguages\n );\n\n const highlightedCode = useShikiHighlighterImpl(\n code,\n language,\n theme,\n options\n );\n\n return (\n <Element\n data-testid=\"shiki-container\"\n className={clsx(\n 'relative',\n 'not-prose',\n addDefaultStyles && 'defaultStyles',\n className\n )}\n style={style}\n id=\"shiki-container\"\n >\n {showLanguage && displayLanguageId ? (\n <span\n className={clsx('languageLabel', langClassName)}\n style={langStyle}\n id=\"language-label\"\n >\n {displayLanguageId}\n </span>\n ) : null}\n {highlightedCode}\n </Element>\n );\n };\n};\n"],"mappings":";AAAA,SAAS,aAAa;AAcf,SAAS,2BAA2B;AACzC,SAAO,CAAC,SAAyB;AAC/B,UAAM,MAAM,WAAW,CAAC,MAAe,QAAQ,WAAoB;AACjE,UAAI,KAAK,YAAY,UAAU,OAAO,YAAY,OAAO;AACvD,aAAK,WAAW,SAAS;AAAA,MAC3B;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAQO,IAAM,eAAe,CAAC,SAA2B;A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E;AAAA,UACH;AAAA;AAAA;AAAA,IACH;AAAA,EAEJ;AACF;","names":["jsx","jsxs"]}
@@ -0,0 +1,209 @@
1
+ import { Highlighter, HighlighterCore, CodeOptionsMultipleThemes, BundledTheme, CodeToHastOptions, StringLiteralUnion, BundledLanguage, SpecialLanguage, ThemeRegistrationAny } from 'shiki';
2
+ import { ReactNode } from 'react';
3
+ import { LanguageRegistration as LanguageRegistration$1 } from 'shiki/core';
4
+ import { Element as Element$1 } from 'hast';
5
+
6
+ /**
7
+ * Attribution:
8
+ * This code was written by github:hippotastic in expressive-code/expressive-code
9
+ * https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-shiki/src/languages.ts
10
+ */
11
+
12
+ type IShikiRawRepository = LanguageRegistration$1['repository'];
13
+ type IShikiRawRule = IShikiRawRepository[keyof IShikiRawRepository];
14
+ type ILocation = IShikiRawRepository['$vscodeTextmateLocation'];
15
+ interface ILocatable {
16
+ readonly $vscodeTextmateLocation?: ILocation;
17
+ }
18
+ interface IRawRepositoryMap {
19
+ [name: string]: IRawRule;
20
+ }
21
+ type IRawRepository = IRawRepositoryMap & ILocatable;
22
+ interface IRawCapturesMap {
23
+ [captureId: string]: IRawRule;
24
+ }
25
+ type IRawCaptures = IRawCapturesMap & ILocatable;
26
+ interface IRawRule extends Omit<IShikiRawRule, 'applyEndPatternLast' | 'captures' | 'patterns'> {
27
+ readonly applyEndPatternLast?: boolean | number;
28
+ readonly captures?: IRawCaptures;
29
+ readonly comment?: string;
30
+ readonly patterns?: IRawRule[];
31
+ }
32
+ /**
33
+ * A less strict version of Shiki's `LanguageRegistration` interface that aligns better with
34
+ * actual grammars found in the wild. This version attempts to reduce the amount
35
+ * of type errors that would occur when importing and adding external grammars,
36
+ * while still being supported by the language processing code.
37
+ */
38
+ interface LanguageRegistration extends Omit<LanguageRegistration$1, 'repository'> {
39
+ repository?: IRawRepository;
40
+ }
41
+
42
+ /**
43
+ * HTML Element, use to type `node` from react-markdown
44
+ */
45
+ type Element = Element$1;
46
+ /**
47
+ * A Shiki BundledLanguage or a custom textmate grammar object
48
+ * @see https://shiki.style/languages
49
+ */
50
+ type Language = LanguageRegistration | StringLiteralUnion<BundledLanguage | SpecialLanguage> | undefined;
51
+ /**
52
+ * A Shiki BundledTheme or a custom textmate theme object
53
+ * @see https://shiki.style/themes
54
+ */
55
+ type Theme = ThemeRegistrationAny | StringLiteralUnion<BundledTheme>;
56
+ /**
57
+ * A map of color names to themes.
58
+ * This allows you to specify multiple themes for the generated code.
59
+ * Supports custom textmate theme objects in addition to Shiki's bundled themes
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * useShikiHighlighter(code, language, {
64
+ * light: 'github-light',
65
+ * dark: 'github-dark',
66
+ * dim: 'github-dark-dimmed'
67
+ * })
68
+ * ```
69
+ *
70
+ * @see https://shiki.style/guide/dual-themes
71
+ */
72
+ type Themes = {
73
+ [key: string]: ThemeRegistrationAny | StringLiteralUnion<BundledTheme>;
74
+ };
75
+ /**
76
+ * Configuration options specific to react-shiki
77
+ */
78
+ interface ReactShikiOptions {
79
+ /**
80
+ * Minimum time (in milliseconds) between highlight operations.
81
+ * @default undefined (no throttling)
82
+ */
83
+ delay?: number;
84
+ /**
85
+ * Custom textmate grammars to be preloaded for highlighting.
86
+ */
87
+ customLanguages?: LanguageRegistration | LanguageRegistration[];
88
+ /**
89
+ * Custom Shiki highlighter instance to use instead of the default one.
90
+ * Keeps bundle small by only importing specified languages/themes.
91
+ * Can be either a Highlighter or HighlighterCore instance.
92
+ *
93
+ * @example
94
+ * import {
95
+ * createHighlighterCore,
96
+ * createOnigurumaEngine,
97
+ * useShikiHighlighter
98
+ * } from "react-shiki";
99
+ *
100
+ * const customHighlighter = await createHighlighterCore({
101
+ * themes: [
102
+ * import('@shikijs/themes/nord')
103
+ * ],
104
+ * langs: [
105
+ * import('@shikijs/langs/javascript'),
106
+ * import('@shikijs/langs/typescript')
107
+ * ],
108
+ * engine: createOnigurumaEngine(import('shiki/wasm'))
109
+ * });
110
+ *
111
+ * const highlightedCode = useShikiHighlighter(code, language, theme, {
112
+ * highlighter: customHighlighter,
113
+ * });
114
+ */
115
+ highlighter?: Highlighter | HighlighterCore;
116
+ }
117
+ /**
118
+ * Configuration options for the syntax highlighter
119
+ * Extends CodeToHastOptions to allow passing any Shiki options directly
120
+ */
121
+ interface HighlighterOptions extends ReactShikiOptions, Pick<CodeOptionsMultipleThemes<BundledTheme>, 'defaultColor' | 'cssVariablePrefix'>, Omit<CodeToHastOptions, 'lang' | 'theme' | 'themes'> {
122
+ }
123
+ /**
124
+ * Public API signature for the useShikiHighlighter hook.
125
+ * This ensures all entry points have consistent signatures.
126
+ */
127
+ type UseShikiHighlighter = (code: string, lang: Language, themeInput: Theme | Themes, options?: HighlighterOptions) => ReactNode;
128
+
129
+ /**
130
+ * Rehype plugin to add an 'inline' property to <code> elements
131
+ * Sets 'inline' property to true if the <code> is not within a <pre> tag
132
+ *
133
+ * Pass this plugin to the `rehypePlugins` prop of react-markdown
134
+ * You can then access `inline` as a prop in components passed to react-markdown
135
+ *
136
+ * @example
137
+ * <ReactMarkdown rehypePlugins={[rehypeInlineCodeProperty]} />
138
+ */
139
+ declare function rehypeInlineCodeProperty(): (tree: any) => undefined;
140
+ /**
141
+ * Function to determine if code is inline based on the presence of line breaks
142
+ *
143
+ * @example
144
+ * const isInline = node && isInlineCode(node: Element)
145
+ */
146
+ declare const isInlineCode: (node: Element) => boolean;
147
+
148
+ /**
149
+ * Props for the ShikiHighlighter component
150
+ */
151
+ interface ShikiHighlighterProps extends HighlighterOptions {
152
+ /**
153
+ * The programming language for syntax highlighting
154
+ * Supports custom textmate grammar objects in addition to Shiki's bundled languages
155
+ * @see https://shiki.style/languages
156
+ */
157
+ language: Language;
158
+ /**
159
+ * The code to be highlighted
160
+ */
161
+ children: string;
162
+ /**
163
+ * The color theme or themes for syntax highlighting
164
+ * Supports single, dual, or multiple themes
165
+ * Supports custom textmate theme objects in addition to Shiki's bundled themes
166
+ *
167
+ * @example
168
+ * theme='github-dark' // single theme
169
+ * theme={{ light: 'github-light', dark: 'github-dark' }} // multi-theme
170
+ *
171
+ * @see https://shiki.style/themes
172
+ */
173
+ theme: Theme | Themes;
174
+ /**
175
+ * Controls the application of default styles to the generated code blocks
176
+ *
177
+ * Default styles include padding, overflow handling, border radius, language label styling, and font settings
178
+ * @default true
179
+ */
180
+ addDefaultStyles?: boolean;
181
+ /**
182
+ * Add custom inline styles to the generated code block
183
+ */
184
+ style?: React.CSSProperties;
185
+ /**
186
+ * Add custom inline styles to the language label
187
+ */
188
+ langStyle?: React.CSSProperties;
189
+ /**
190
+ * Add custom CSS class names to the generated code block
191
+ */
192
+ className?: string;
193
+ /**
194
+ * Add custom CSS class names to the language label
195
+ */
196
+ langClassName?: string;
197
+ /**
198
+ * Whether to show the language label
199
+ * @default true
200
+ */
201
+ showLanguage?: boolean;
202
+ /**
203
+ * The HTML element that wraps the generated code block.
204
+ * @default 'pre'
205
+ */
206
+ as?: React.ElementType;
207
+ }
208
+
209
+ export { type Element as E, type HighlighterOptions as H, type Language as L, type ShikiHighlighterProps as S, type Theme as T, type UseShikiHighlighter as U, type Themes as a, isInlineCode as i, rehypeInlineCodeProperty as r };
package/dist/core.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { S as ShikiHighlighterProps, U as UseShikiHighlighter } from './component-D73l5tW-.js';
2
+ export { E as Element, H as HighlighterOptions, L as Language, T as Theme, a as Themes, i as isInlineCode, r as rehypeInlineCodeProperty } from './component-D73l5tW-.js';
3
+ export { createHighlighterCore } from 'shiki/core';
4
+ export { createOnigurumaEngine } from 'shiki/engine/oniguruma';
5
+ export { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
6
+ import 'shiki';
7
+ import 'react';
8
+ import 'hast';
9
+
10
+ /**
11
+ * A React hook that provides syntax highlighting using Shiki with a custom highlighter.
12
+ * Requires a highlighter to be provided in options for minimal bundle size.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { createHighlighterCore, createOnigurumaEngine } from 'react-shiki/core';
17
+ *
18
+ * const highlighter = await createHighlighterCore({
19
+ * themes: [import('@shikijs/themes/nord')],
20
+ * langs: [import('@shikijs/langs/typescript')],
21
+ * engine: createOnigurumaEngine(import('shiki/wasm'))
22
+ * });
23
+ *
24
+ * const code = useShikiHighlighter(code, 'typescript', 'nord', { highlighter });
25
+ * ```
26
+ *
27
+ * For plug-and-play usage, consider:
28
+ * - `react-shiki` for full shiki bundle (~6.4MB minified, 1.2MB gzipped)
29
+ * - `react-shiki/web` for smaller shiki web bundle (~3.8MB minified, 695KB gzipped)
30
+ */
31
+ declare const useShikiHighlighter: UseShikiHighlighter;
32
+ /**
33
+ * ShikiHighlighter component using a custom highlighter.
34
+ * Requires a highlighter to be provided.
35
+ */
36
+ declare const ShikiHighlighter: ({ language, theme, delay, transformers, defaultColor, cssVariablePrefix, addDefaultStyles, style, langStyle, className, langClassName, showLanguage, children: code, as: Element, customLanguages, ...shikiOptions }: ShikiHighlighterProps) => React.ReactElement;
37
+
38
+ export { ShikiHighlighter, ShikiHighlighterProps, UseShikiHighlighter, ShikiHighlighter as default, useShikiHighlighter };
package/dist/core.js ADDED
@@ -0,0 +1,43 @@
1
+ import {
2
+ createShikiHighlighterComponent,
3
+ isInlineCode,
4
+ rehypeInlineCodeProperty,
5
+ useShikiHighlighter
6
+ } from "./chunk-XAMWR6XF.js";
7
+
8
+ // src/bundles/core.ts
9
+ function validateCoreHighlighter(highlighter) {
10
+ if (!highlighter) {
11
+ throw new Error(
12
+ "react-shiki/core requires a custom highlighter. Use createHighlighterCore() from react-shiki or switch to react-shiki for plug-and-play usage."
13
+ );
14
+ }
15
+ return highlighter;
16
+ }
17
+
18
+ // src/core.ts
19
+ import { createHighlighterCore } from "shiki/core";
20
+ import { createOnigurumaEngine } from "shiki/engine/oniguruma";
21
+ import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
22
+ var useShikiHighlighter2 = (code, lang, themeInput, options = {}) => {
23
+ const highlighter = validateCoreHighlighter(options.highlighter);
24
+ return useShikiHighlighter(code, lang, themeInput, async () => highlighter, {
25
+ ...options,
26
+ highlighter
27
+ });
28
+ };
29
+ var ShikiHighlighter = createShikiHighlighterComponent(
30
+ useShikiHighlighter2
31
+ );
32
+ var core_default = ShikiHighlighter;
33
+ export {
34
+ ShikiHighlighter,
35
+ createHighlighterCore,
36
+ createJavaScriptRegexEngine,
37
+ createOnigurumaEngine,
38
+ core_default as default,
39
+ isInlineCode,
40
+ rehypeInlineCodeProperty,
41
+ useShikiHighlighter2 as useShikiHighlighter
42
+ };
43
+ //# sourceMappingURL=core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/bundles/core.ts","../src/core.ts"],"sourcesContent":["import type { HighlighterCore } from 'shiki';\n\n/**\n * Validates that a highlighter is provided for the core bundle.\n * The core bundle requires users to provide their own highlighter instance.\n */\nexport function validateCoreHighlighter(\n highlighter: HighlighterCore | undefined\n): HighlighterCore {\n if (!highlighter) {\n throw new Error(\n 'react-shiki/core requires a custom highlighter. ' +\n 'Use createHighlighterCore() from react-shiki or switch to react-shiki for plug-and-play usage.'\n );\n }\n return highlighter;\n}\n","import { useShikiHighlighter as useBaseHook } from './lib/hook';\nimport { validateCoreHighlighter } from './bundles/core';\nimport type { UseShikiHighlighter } from './lib/types';\n\nexport { isInlineCode, rehypeInlineCodeProperty } from './lib/utils';\n\nimport {\n createShikiHighlighterComponent,\n type ShikiHighlighterProps,\n} from './lib/component';\n\nexport type { ShikiHighlighterProps };\n\nexport type {\n UseShikiHighlighter,\n Language,\n Theme,\n Themes,\n Element,\n HighlighterOptions,\n} from './lib/types';\n\nexport { createHighlighterCore } from 'shiki/core';\nexport { createOnigurumaEngine } from 'shiki/engine/oniguruma';\nexport { createJavaScriptRegexEngine } from 'shiki/engine/javascript';\n\n/**\n * A React hook that provides syntax highlighting using Shiki with a custom highlighter.\n * Requires a highlighter to be provided in options for minimal bundle size.\n *\n * @example\n * ```ts\n * import { createHighlighterCore, createOnigurumaEngine } from 'react-shiki/core';\n *\n * const highlighter = await createHighlighterCore({\n * themes: [import('@shikijs/themes/nord')],\n * langs: [import('@shikijs/langs/typescript')],\n * engine: createOnigurumaEngine(import('shiki/wasm'))\n * });\n *\n * const code = useShikiHighlighter(code, 'typescript', 'nord', { highlighter });\n * ```\n *\n * For plug-and-play usage, consider:\n * - `react-shiki` for full shiki bundle (~6.4MB minified, 1.2MB gzipped)\n * - `react-shiki/web` for smaller shiki web bundle (~3.8MB minified, 695KB gzipped)\n */\nexport const useShikiHighlighter: UseShikiHighlighter = (\n code,\n lang,\n themeInput,\n options = {}\n) => {\n // Validate that highlighter is provided\n const highlighter = validateCoreHighlighter(options.highlighter);\n\n return useBaseHook(code, lang, themeInput, async () => highlighter, {\n ...options,\n highlighter,\n });\n};\n\n/**\n * ShikiHighlighter component using a custom highlighter.\n * Requires a highlighter to be provided.\n */\nexport const ShikiHighlighter = createShikiHighlighterComponent(\n useShikiHighlighter\n);\nexport default ShikiHighlighter;\n"],"mappings":";;;;;;;;AAMO,SAAS,wBACd,aACiB;AACjB,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;;;ACMA,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,mCAAmC;AAuBrC,IAAMA,uBAA2C,CACtD,MACA,MACA,YACA,UAAU,CAAC,MACR;AAEH,QAAM,cAAc,wBAAwB,QAAQ,WAAW;AAE/D,SAAO,oBAAY,MAAM,MAAM,YAAY,YAAY,aAAa;AAAA,IAClE,GAAG;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAMO,IAAM,mBAAmB;AAAA,EAC9BA;AACF;AACA,IAAO,eAAQ;","names":["useShikiHighlighter"]}
package/dist/index.d.ts CHANGED
@@ -1,236 +1,25 @@
1
- import { ReactNode } from 'react';
2
- import { LanguageRegistration as LanguageRegistration$1, StringLiteralUnion, BundledLanguage, SpecialLanguage, ThemeRegistrationAny, BundledTheme, CodeOptionsMultipleThemes, CodeToHastOptionsCommon } from 'shiki';
3
- import { Element as Element$1 } from 'hast';
1
+ import { S as ShikiHighlighterProps, U as UseShikiHighlighter } from './component-D73l5tW-.js';
2
+ export { E as Element, H as HighlighterOptions, L as Language, T as Theme, a as Themes, i as isInlineCode, r as rehypeInlineCodeProperty } from './component-D73l5tW-.js';
3
+ import 'shiki';
4
+ import 'react';
5
+ import 'shiki/core';
6
+ import 'hast';
4
7
 
5
8
  /**
6
- * Attribution:
7
- * This code was written by github:hippotastic in expressive-code/expressive-code
8
- * https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-shiki/src/languages.ts
9
- */
10
-
11
- type IShikiRawRepository = LanguageRegistration$1['repository'];
12
- type IShikiRawRule = IShikiRawRepository[keyof IShikiRawRepository];
13
- type ILocation = IShikiRawRepository['$vscodeTextmateLocation'];
14
- interface ILocatable {
15
- readonly $vscodeTextmateLocation?: ILocation;
16
- }
17
- interface IRawRepositoryMap {
18
- [name: string]: IRawRule;
19
- }
20
- type IRawRepository = IRawRepositoryMap & ILocatable;
21
- interface IRawCapturesMap {
22
- [captureId: string]: IRawRule;
23
- }
24
- type IRawCaptures = IRawCapturesMap & ILocatable;
25
- interface IRawRule extends Omit<IShikiRawRule, 'applyEndPatternLast' | 'captures' | 'patterns'> {
26
- readonly applyEndPatternLast?: boolean | number;
27
- readonly captures?: IRawCaptures;
28
- readonly comment?: string;
29
- readonly patterns?: IRawRule[];
30
- }
31
- /**
32
- * A less strict version of Shiki's `LanguageRegistration` interface that aligns better with
33
- * actual grammars found in the wild. This version attempts to reduce the amount
34
- * of type errors that would occur when importing and adding external grammars,
35
- * while still being supported by the language processing code.
36
- */
37
- interface LanguageRegistration extends Omit<LanguageRegistration$1, 'repository'> {
38
- repository?: IRawRepository;
39
- }
40
-
41
- /**
42
- * HTML Element, use to type `node` from react-markdown
43
- */
44
- type Element = Element$1;
45
- /**
46
- * A Shiki BundledLanguage or a custom textmate grammar object
47
- * @see https://shiki.style/languages
48
- */
49
- type Language = LanguageRegistration | StringLiteralUnion<BundledLanguage | SpecialLanguage> | undefined;
50
- /**
51
- * A Shiki BundledTheme or a custom textmate theme object
52
- * @see https://shiki.style/themes
53
- */
54
- type Theme = ThemeRegistrationAny | StringLiteralUnion<BundledTheme>;
55
- /**
56
- * A map of color names to themes.
57
- * This allows you to specify multiple themes for the generated code.
58
- * Supports custom textmate theme objects in addition to Shiki's bundled themes
59
- *
60
- * @example
61
- * ```ts
62
- * useShikiHighlighter(code, language, {
63
- * light: 'github-light',
64
- * dark: 'github-dark',
65
- * dim: 'github-dark-dimmed'
66
- * })
67
- * ```
68
- *
69
- * @see https://shiki.style/guide/dual-themes
70
- */
71
- type Themes = {
72
- [key: string]: ThemeRegistrationAny | StringLiteralUnion<BundledTheme>;
73
- };
74
- /**
75
- * Configuration options specific to react-shiki
76
- */
77
- interface ReactShikiOptions {
78
- /**
79
- * Minimum time (in milliseconds) between highlight operations.
80
- * @default undefined (no throttling)
81
- */
82
- delay?: number;
83
- /**
84
- * Custom textmate grammars to be preloaded for highlighting.
85
- */
86
- customLanguages?: LanguageRegistration | LanguageRegistration[];
87
- }
88
- /**
89
- * Configuration options for the syntax highlighter
90
- */
91
- interface HighlighterOptions extends ReactShikiOptions, Pick<CodeOptionsMultipleThemes<BundledTheme>, 'defaultColor' | 'cssVariablePrefix'>, Pick<CodeToHastOptionsCommon, 'transformers'> {
92
- }
93
-
94
- /**
95
- * A React hook that provides syntax highlighting using Shiki.
96
- * Supports single theme and multi-theme highlighting, custom themes
97
- * and languages, custom transformers, and optional throttling.
98
- *
99
- * ```ts
100
- * // Basic Usage
101
- * const highlightedCode = useShikiHighlighter( code, 'typescript', 'github-dark');
102
- * ```
9
+ * A React hook that provides syntax highlighting using Shiki with the full bundle.
10
+ * Includes all languages and themes for maximum compatibility.
103
11
  *
104
- * ```ts
105
- * // Custom Languages, Transformers, and Delay
106
- * const highlightedCode = useShikiHighlighter(code, language, theme, {
107
- * transformers: [customTransformer],
108
- * delay: 150
109
- * customLanguages: ['bosque', 'mcfunction']
110
- * });
111
- * ```
12
+ * Bundle size: ~6.4MB minified (1.2MB gzipped)
112
13
  *
113
- * ```ts
114
- * // Multiple Themes, Custom Languages, Delay, and Custom Transformers
115
- * const highlightedCode = useShikiHighlighter(
116
- * code,
117
- * language,
118
- * {
119
- * light: 'github-light',
120
- * dark: 'github-dark',
121
- * dim: 'github-dark-dimmed'
122
- * },
123
- * {
124
- * delay: 150,
125
- * defaultColor: 'dim',
126
- * transformers: [customTransformer],
127
- * customLanguages: ['bosque', 'mcfunction']
128
- * }
129
- * );
130
- * ```
14
+ * For smaller bundles, consider:
15
+ * - `react-shiki/web` for smaller shiki web bundle (~3.8MB minified, 695KB gzipped)
16
+ * - `react-shiki/core` for custom fine-grained bundle
131
17
  */
132
- declare const useShikiHighlighter: (code: string, lang: Language, themeInput: Theme | Themes, options?: HighlighterOptions) => ReactNode;
133
-
18
+ declare const useShikiHighlighter: UseShikiHighlighter;
134
19
  /**
135
- * Rehype plugin to add an 'inline' property to <code> elements
136
- * Sets 'inline' property to true if the <code> is not within a <pre> tag
137
- *
138
- * Pass this plugin to the `rehypePlugins` prop of react-markdown
139
- * You can then access `inline` as a prop in components passed to react-markdown
140
- *
141
- * @example
142
- * <ReactMarkdown rehypePlugins={[rehypeInlineCodeProperty]} />
143
- */
144
- declare function rehypeInlineCodeProperty(): (tree: any) => undefined;
145
- /**
146
- * Function to determine if code is inline based on the presence of line breaks
147
- *
148
- * @example
149
- * const isInline = node && isInlineCode(node: Element)
150
- */
151
- declare const isInlineCode: (node: Element) => boolean;
152
-
153
- /**
154
- * Props for the ShikiHighlighter component
155
- */
156
- interface ShikiHighlighterProps extends HighlighterOptions {
157
- /**
158
- * The programming language for syntax highlighting
159
- * Supports custom textmate grammar objects in addition to Shiki's bundled languages
160
- * @see https://shiki.style/languages
161
- */
162
- language: Language;
163
- /**
164
- * The code to be highlighted
165
- */
166
- children: string;
167
- /**
168
- * The color theme or themes for syntax highlighting
169
- * Supports single, dual, or multiple themes
170
- * Supports custom textmate theme objects in addition to Shiki's bundled themes
171
- *
172
- * @example
173
- * theme='github-dark' // single theme
174
- * theme={{ light: 'github-light', dark: 'github-dark' }} // multi-theme
175
- *
176
- * @see https://shiki.style/themes
177
- */
178
- theme: Theme | Themes;
179
- /**
180
- * Controls the application of default styles to the generated code blocks
181
- *
182
- * Default styles include padding, overflow handling, border radius, language label styling, and font settings
183
- * @default true
184
- */
185
- addDefaultStyles?: boolean;
186
- /**
187
- * Add custom inline styles to the generated code block
188
- */
189
- style?: React.CSSProperties;
190
- /**
191
- * Add custom inline styles to the language label
192
- */
193
- langStyle?: React.CSSProperties;
194
- /**
195
- * Add custom CSS class names to the generated code block
196
- */
197
- className?: string;
198
- /**
199
- * Add custom CSS class names to the language label
200
- */
201
- langClassName?: string;
202
- /**
203
- * Whether to show the language label
204
- * @default true
205
- */
206
- showLanguage?: boolean;
207
- /**
208
- * The HTML element that wraps the generated code block.
209
- * @default 'pre'
210
- */
211
- as?: React.ElementType;
212
- }
213
- /**
214
- * ShikiHighlighter is a React component that provides syntax highlighting for code snippets.
215
- * It uses Shiki to render beautiful, theme-based syntax highlighting with optimized performance.
216
- *
217
- * @example
218
- * ```tsx
219
- * <ShikiHighlighter
220
- * language="typescript"
221
- * theme="github-dark"
222
- * delay={100}
223
- * transformers={[customTransformer]}
224
- * addDefaultStyles={false}
225
- * className="code-block"
226
- * langClassName="lang-label"
227
- * langStyle={{ color: 'blue' }},
228
- * style={{ fontSize: '1.2rem' }}
229
- * >
230
- * {code}
231
- * </ShikiHighlighter>
232
- * ```
20
+ * ShikiHighlighter component using the full bundle.
21
+ * Includes all languages and themes for maximum compatibility.
233
22
  */
234
- declare const ShikiHighlighter: ({ language, theme, delay, transformers, defaultColor, cssVariablePrefix, addDefaultStyles, style, langStyle, className, langClassName, showLanguage, children: code, as: Element, customLanguages, }: ShikiHighlighterProps) => React.ReactElement;
23
+ declare const ShikiHighlighter: ({ language, theme, delay, transformers, defaultColor, cssVariablePrefix, addDefaultStyles, style, langStyle, className, langClassName, showLanguage, children: code, as: Element, customLanguages, ...shikiOptions }: ShikiHighlighterProps) => React.ReactElement;
235
24
 
236
- export { type Element, type HighlighterOptions, type Language, type ShikiHighlighterProps, type Theme, type Themes, ShikiHighlighter as default, isInlineCode, rehypeInlineCodeProperty, useShikiHighlighter };
25
+ export { ShikiHighlighter, ShikiHighlighterProps, UseShikiHighlighter, ShikiHighlighter as default, useShikiHighlighter };
package/dist/index.js CHANGED
@@ -1,4 +1,48 @@
1
- import{useEffect as z,useMemo as b,useRef as D,useState as F}from"react";import B from"html-react-parser";import{getSingletonHighlighter as V}from"shiki";import{visit as w}from"unist-util-visit";import{bundledLanguages as M,isSpecialLang as A}from"shiki";function N(){return e=>{w(e,"element",(i,o,t)=>{i.tagName==="code"&&t.tagName!=="pre"&&(i.properties.inline=!0)})}}var P=e=>!(e.children||[]).filter(o=>o.type==="text").map(o=>o.value).join("").includes(`
2
- `),k={pre(e){return"properties"in e&&(e.properties.tabindex="-1"),e}},R=(e,i,o)=>{let t=Date.now();clearTimeout(i.current.timeoutId);let r=Math.max(0,i.current.nextAllowedTime-t);i.current.timeoutId=setTimeout(()=>{e().catch(console.error),i.current.nextAllowedTime=t+o},r)},p=(e,i=[])=>{let o=new Set(Object.keys(M).map(a=>a.toLowerCase()));if(e==null||typeof e=="string"&&!e.trim())return{languageId:"plaintext",displayLanguageId:"plaintext",langsToLoad:void 0};if(typeof e=="object")return{languageId:e.name,displayLanguageId:e.name||null,langsToLoad:e};let t=e.toLowerCase(),r=a=>a?.toLowerCase()===t,n=i.find(a=>r(a.name)||r(a.scopeName)||r(a.scopeName?.split(".").pop())||a.aliases?.some(r)||a.fileTypes?.some(r));return n?{languageId:n.name||e,displayLanguageId:e,langsToLoad:n}:(o.has(t)||A(t))&&!n?{languageId:e,displayLanguageId:e,langsToLoad:e}:{languageId:"plaintext",displayLanguageId:e,langsToLoad:void 0}};function v(e){let i=typeof e=="object"&&"tokenColors"in e&&Array.isArray(e.tokenColors),o=typeof e=="object"&&e!==null&&!i,t=typeof e=="object"&&e!==null&&!i&&Object.entries(e).some(([r,n])=>r&&n&&r.trim()!==""&&n!==""&&(typeof n=="string"||i));return o?{isMultiTheme:!0,themeId:t?`multi-${Object.values(e).map(n=>(typeof n=="string"?n:n?.name)||"custom").sort().join("-")}`:"multi-default",multiTheme:t?e:null,themesToLoad:t?Object.values(e):[]}:{isMultiTheme:!1,themeId:typeof e=="string"?e:e?.name||"custom",singleTheme:e,themesToLoad:[e]}}var I={light:"github-light",dark:"github-dark"},H=(e,i,o,t={})=>{let[r,n]=F(null),a=t.customLanguages?Array.isArray(t.customLanguages)?t.customLanguages:[t.customLanguages]:[],g=a.map(l=>l.name||"").sort().join("-"),m=b(()=>[k,...t.transformers||[]],[t.transformers]),{isMultiTheme:c,themeId:f,multiTheme:T,singleTheme:y,themesToLoad:L}=b(()=>v(o),[o]),{languageId:s,langsToLoad:x}=b(()=>p(i,a),[i,g]),d=D({nextAllowedTime:0,timeoutId:void 0}),u=()=>{let{defaultColor:l,cssVariablePrefix:h}=t,S={lang:s,transformers:m},C=c?{themes:T||I,defaultColor:l,cssVariablePrefix:h}:{theme:y||I.dark};return{...S,...C}};return z(()=>{let l=!0,h=async()=>{if(!s)return;let S=await V({langs:[x],themes:L}),C=u(),E=S.codeToHtml(e,C);l&&n(B(E))};return t.delay?R(h,d,t.delay):h().catch(console.error),()=>{l=!1,clearTimeout(d.current.timeoutId)}},[e,s,f,g,m,t.delay,t.defaultColor,t.cssVariablePrefix]),r};function O(e,{insertAt:i}={}){if(!e||typeof document>"u")return;let o=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",i==="top"&&o.firstChild?o.insertBefore(t,o.firstChild):o.appendChild(t),t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}O(`.relative{position:relative}.defaultStyles pre{overflow:auto;border-radius:.5rem;padding:1.25rem 1.5rem}.languageLabel{position:absolute;right:.75rem;top:.5rem;font-family:monospace;font-size:.75rem;letter-spacing:-.05em;color:#6b7280d9}
3
- `);import{clsx as j}from"clsx";import{jsx as U,jsxs as $}from"react/jsx-runtime";var _=({language:e,theme:i,delay:o,transformers:t,defaultColor:r,cssVariablePrefix:n,addDefaultStyles:a=!0,style:g,langStyle:m,className:c,langClassName:f,showLanguage:T=!0,children:y,as:L="pre",customLanguages:s})=>{let x={delay:o,transformers:t,customLanguages:s,defaultColor:r,cssVariablePrefix:n},d=s?Array.isArray(s)?s:[s]:[],{displayLanguageId:u}=p(e,d),l=H(y,e,i,x);return $(L,{"data-testid":"shiki-container",className:j("relative","not-prose",a&&"defaultStyles",c),style:g,id:"shiki-container",children:[T&&u?U("span",{className:j("languageLabel",f),style:m,id:"language-label",children:u}):null,l]})};export{_ as default,P as isInlineCode,N as rehypeInlineCodeProperty,H as useShikiHighlighter};
1
+ import {
2
+ createShikiHighlighterComponent,
3
+ isInlineCode,
4
+ rehypeInlineCodeProperty,
5
+ useShikiHighlighter
6
+ } from "./chunk-XAMWR6XF.js";
7
+
8
+ // src/bundles/full.ts
9
+ import { getSingletonHighlighter } from "shiki";
10
+ async function createFullHighlighter(langsToLoad, themesToLoad) {
11
+ try {
12
+ return await getSingletonHighlighter({
13
+ langs: [langsToLoad],
14
+ themes: themesToLoad
15
+ });
16
+ } catch (error) {
17
+ if (error instanceof Error && error.message.includes("Language")) {
18
+ return await getSingletonHighlighter({
19
+ langs: ["plaintext"],
20
+ themes: themesToLoad
21
+ });
22
+ }
23
+ throw error;
24
+ }
25
+ }
26
+
27
+ // src/index.ts
28
+ var useShikiHighlighter2 = (code, lang, themeInput, options = {}) => {
29
+ return useShikiHighlighter(
30
+ code,
31
+ lang,
32
+ themeInput,
33
+ createFullHighlighter,
34
+ options
35
+ );
36
+ };
37
+ var ShikiHighlighter = createShikiHighlighterComponent(
38
+ useShikiHighlighter2
39
+ );
40
+ var src_default = ShikiHighlighter;
41
+ export {
42
+ ShikiHighlighter,
43
+ src_default as default,
44
+ isInlineCode,
45
+ rehypeInlineCodeProperty,
46
+ useShikiHighlighter2 as useShikiHighlighter
47
+ };
4
48
  //# sourceMappingURL=index.js.map