Skip to content

Commit 1db298d

Browse files
mrzmyrRhysSullivan
andauthored
feat(react): high-contrast syntax highlighting with light/dark pair (#162)
* feat(react): high-contrast syntax highlighting with light/dark pair The previous single Vitesse Dark theme was the same in both modes and lacked contrast. Switch to GitHub Light/Dark as the default pair and make the theme selectable at the component level. - `lib/shiki.ts`: export `SupportedTheme`, `DEFAULT_LIGHT_THEME`, `DEFAULT_DARK_THEME`, and a `ShikiThemeProp` that accepts either a single theme or a `{ light, dark }` pair. Add `useIsDark` and `useResolvedShikiTheme` hooks so components can react to the system color-scheme. Load both GitHub themes up-front. - `CodeBlock` and `ExpandableCodeBlock`: accept an optional `theme` prop and pass it through the tokenization hooks. - Streamdown plugin: key its cache per active theme so switching color schemes doesn't serve stale tokens. * refactor(react): extract useIsDark hook from shiki module Move useIsDark into its own hook file so it can be reused outside of syntax highlighting. Also remove unused THEME export and vitesse-dark theme. --------- Co-authored-by: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com>
1 parent d8e589f commit 1db298d

4 files changed

Lines changed: 94 additions & 17 deletions

File tree

‎packages/react/src/components/code-block.tsx‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
22
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
33
import { toJsxRuntime } from "hast-util-to-jsx-runtime";
4-
import { getHighlighter, resolveLang, THEME } from "../lib/shiki";
4+
import {
5+
getHighlighter,
6+
resolveLang,
7+
useResolvedShikiTheme,
8+
type ShikiThemeProp,
9+
type SupportedTheme,
10+
} from "../lib/shiki";
511
import { cn } from "../lib/utils";
612
import { Button } from "./button";
713

@@ -55,7 +61,7 @@ const CheckIcon = () => (
5561
// Highlight hook
5662
// ---------------------------------------------------------------------------
5763

58-
function useHighlighted(code: string, lang: string): ReactNode | null {
64+
function useHighlighted(code: string, lang: string, theme: SupportedTheme): ReactNode | null {
5965
const [highlighted, setHighlighted] = useState<ReactNode | null>(null);
6066

6167
useEffect(() => {
@@ -64,7 +70,7 @@ function useHighlighted(code: string, lang: string): ReactNode | null {
6470
getHighlighter().then((highlighter) => {
6571
if (cancelled) return;
6672

67-
const hast = highlighter.codeToHast(code, { lang, theme: THEME });
73+
const hast = highlighter.codeToHast(code, { lang, theme });
6874
const nodes = toJsxRuntime(hast, { jsx, jsxs, Fragment });
6975

7076
if (!cancelled) setHighlighted(nodes);
@@ -73,7 +79,7 @@ function useHighlighted(code: string, lang: string): ReactNode | null {
7379
return () => {
7480
cancelled = true;
7581
};
76-
}, [code, lang]);
82+
}, [code, lang, theme]);
7783

7884
return highlighted;
7985
}
@@ -88,13 +94,15 @@ export function CodeBlock(props: {
8894
title?: string;
8995
maxHeight?: string;
9096
className?: string;
97+
theme?: ShikiThemeProp;
9198
}) {
92-
const { code, lang: langHint, title, className } = props;
99+
const { code, lang: langHint, title, className, theme } = props;
93100
const [expanded, setExpanded] = useState(false);
94101
const [copied, setCopied] = useState(false);
95102

96103
const language = useMemo(() => detectLanguage(code, langHint), [code, langHint]);
97-
const highlighted = useHighlighted(code, language);
104+
const resolvedTheme = useResolvedShikiTheme(theme);
105+
const highlighted = useHighlighted(code, language, resolvedTheme);
98106

99107
const lines = code.split("\n");
100108
const isLong = lines.length > 24;

‎packages/react/src/components/expandable-code-block.tsx‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { useCallback, useEffect, useMemo, useState, startTransition } from "react";
2-
import { getHighlighter, THEME } from "../lib/shiki";
2+
import {
3+
getHighlighter,
4+
useResolvedShikiTheme,
5+
type ShikiThemeProp,
6+
type SupportedTheme,
7+
} from "../lib/shiki";
38
import { cn } from "../lib/utils";
49
import { Button } from "./button";
510
import type { ThemedToken } from "shiki/core";
@@ -98,7 +103,7 @@ const CheckIcon = () => (
98103
// Shiki tokenization hook — non-blocking
99104
// ---------------------------------------------------------------------------
100105

101-
function useTokens(code: string): ThemedToken[][] | null {
106+
function useTokens(code: string, theme: SupportedTheme): ThemedToken[][] | null {
102107
const [tokens, setTokens] = useState<ThemedToken[][] | null>(null);
103108

104109
useEffect(() => {
@@ -107,7 +112,7 @@ function useTokens(code: string): ThemedToken[][] | null {
107112
if (cancelled) return;
108113
const result = highlighter.codeToTokens(code, {
109114
lang: "typescript",
110-
theme: THEME,
115+
theme,
111116
});
112117
if (!cancelled) {
113118
startTransition(() => setTokens(result.tokens));
@@ -116,7 +121,7 @@ function useTokens(code: string): ThemedToken[][] | null {
116121
return () => {
117122
cancelled = true;
118123
};
119-
}, [code]);
124+
}, [code, theme]);
120125

121126
return tokens;
122127
}
@@ -300,8 +305,10 @@ export function ExpandableCodeBlock(props: {
300305
code: string;
301306
definitions?: readonly Definition[];
302307
className?: string;
308+
theme?: ShikiThemeProp;
303309
}) {
304-
const { code, definitions = [], className } = props;
310+
const { code, definitions = [], className, theme } = props;
311+
const resolvedTheme = useResolvedShikiTheme(theme);
305312
// Auto-expand trivial aliases (primitives, simple unions, string literals)
306313
const trivialNames = useMemo(() => {
307314
const trivial = new Set<string>();
@@ -348,7 +355,7 @@ export function ExpandableCodeBlock(props: {
348355
return formatTypeScript(withExpansions);
349356
}, [code, allExpanded, definitionMap, emptyAncestors]);
350357

351-
const tokens = useTokens(displayCode);
358+
const tokens = useTokens(displayCode, resolvedTheme);
352359

353360
const handleToggle = useCallback((name: string) => {
354361
setExpanded((prev) => {
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { useEffect, useState } from "react";
2+
3+
/**
4+
* Returns `true` when the user's system prefers a dark color scheme.
5+
* Reactive: updates when the media query changes.
6+
*/
7+
export function useIsDark(): boolean {
8+
const [dark, setDark] = useState<boolean>(() => {
9+
if (typeof window === "undefined") return false;
10+
return window.matchMedia("(prefers-color-scheme: dark)").matches;
11+
});
12+
13+
useEffect(() => {
14+
if (typeof window === "undefined") return;
15+
const mql = window.matchMedia("(prefers-color-scheme: dark)");
16+
const handler = (event: MediaQueryListEvent) => setDark(event.matches);
17+
mql.addEventListener("change", handler);
18+
return () => mql.removeEventListener("change", handler);
19+
}, []);
20+
21+
return dark;
22+
}

‎packages/react/src/lib/shiki.ts‎

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createHighlighterCore, type HighlighterCore, type LanguageInput } from "shiki/core";
22
import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
3+
import { useIsDark } from "../hooks/use-is-dark";
34

45
// ---------------------------------------------------------------------------
56
// Supported languages — explicit imports to avoid bundling all grammars
@@ -96,7 +97,29 @@ const LANG_LOADERS: Record<SupportedLang, () => LanguageInput> = {
9697

9798
const supportedSet = new Set<string>([...SUPPORTED_LANGS, ...Object.keys(LANG_ALIASES)]);
9899

99-
export const THEME = "vitesse-dark";
100+
export const SUPPORTED_THEMES = ["github-dark", "github-light"] as const;
101+
export type SupportedTheme = (typeof SUPPORTED_THEMES)[number];
102+
103+
export const DEFAULT_LIGHT_THEME: SupportedTheme = "github-light";
104+
export const DEFAULT_DARK_THEME: SupportedTheme = "github-dark";
105+
106+
export type ShikiThemeProp =
107+
| SupportedTheme
108+
| { light: SupportedTheme; dark: SupportedTheme };
109+
110+
/**
111+
* Resolve a `ShikiThemeProp` (either a single theme or a `{ light, dark }`
112+
* pair) to the theme that should currently be used, reacting to system
113+
* dark-mode changes. When no theme is provided, the default github pair is
114+
* used.
115+
*/
116+
export function useResolvedShikiTheme(theme?: ShikiThemeProp): SupportedTheme {
117+
const isDark = useIsDark();
118+
if (typeof theme === "string") return theme;
119+
const light = theme?.light ?? DEFAULT_LIGHT_THEME;
120+
const dark = theme?.dark ?? DEFAULT_DARK_THEME;
121+
return isDark ? dark : light;
122+
}
100123

101124
export function resolveLang(lang: string): SupportedLang | null {
102125
const l = lang.trim().toLowerCase();
@@ -120,7 +143,10 @@ let _promise: Promise<HighlighterCore> | null = null;
120143
export function getHighlighter(): Promise<HighlighterCore> {
121144
if (!_promise) {
122145
_promise = createHighlighterCore({
123-
themes: [import("@shikijs/themes/vitesse-dark")],
146+
themes: [
147+
import("@shikijs/themes/github-dark"),
148+
import("@shikijs/themes/github-light"),
149+
],
124150
langs: Object.values(LANG_LOADERS).map((loader) => loader()),
125151
engine: jsEngine,
126152
});
@@ -137,17 +163,31 @@ import type { CodeHighlighterPlugin, ThemeInput } from "streamdown";
137163
const tokensCache = new Map<string, unknown>();
138164
const pendingCallbacks = new Map<string, Set<(result: unknown) => void>>();
139165

166+
/**
167+
* Read the current system color-scheme preference synchronously. Used in
168+
* non-React contexts (like the streamdown plugin) where hooks aren't
169+
* available.
170+
*/
171+
const prefersDarkNow = (): boolean => {
172+
if (typeof window === "undefined") return false;
173+
return window.matchMedia("(prefers-color-scheme: dark)").matches;
174+
};
175+
140176
export function createCodeHighlighterPlugin(): CodeHighlighterPlugin {
141177
return {
142178
name: "shiki" as const,
143179
type: "code-highlighter" as const,
144180
getSupportedLanguages: () => [...SUPPORTED_LANGS] as string[] as never,
145-
getThemes: () => [THEME as ThemeInput, THEME as ThemeInput],
181+
getThemes: () => [
182+
DEFAULT_LIGHT_THEME as ThemeInput,
183+
DEFAULT_DARK_THEME as ThemeInput,
184+
],
146185
supportsLanguage: (language: string) => isSupportedLang(language),
147186
highlight(options, callback) {
148187
const resolved = resolveLang(options.language);
149188
const lang = resolved ?? "json";
150-
const key = `${lang}:${options.code.length}:${options.code.slice(0, 128)}`;
189+
const activeTheme = prefersDarkNow() ? DEFAULT_DARK_THEME : DEFAULT_LIGHT_THEME;
190+
const key = `${activeTheme}:${lang}:${options.code.length}:${options.code.slice(0, 128)}`;
151191

152192
const cached = tokensCache.get(key);
153193
if (cached) return cached as never;
@@ -168,7 +208,7 @@ export function createCodeHighlighterPlugin(): CodeHighlighterPlugin {
168208
}
169209
const result = highlighter.codeToTokens(options.code, {
170210
lang,
171-
themes: { light: THEME, dark: THEME },
211+
themes: { light: activeTheme, dark: activeTheme },
172212
});
173213
tokensCache.set(key, result);
174214
pendingCallbacks.get(key)?.forEach((cb) => cb(result));

0 commit comments

Comments
 (0)