Skip to content

fix: resolve CodeMirror dark mode and theme switching issues #138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 8, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions components/ui/code-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(
) {
const containerRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
const { theme: systemTheme } = useTheme();
const { resolvedTheme } = useTheme();

// Store the onChange callback in a ref to avoid stale closures
const onChangeRef = useRef(onChange);
Expand All @@ -139,8 +139,8 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(
[]
);

// Determine the active theme
const activeTheme = themeOverride || systemTheme || "light";
// Determine the active theme - use resolvedTheme which handles system theme properly
const activeTheme = themeOverride || resolvedTheme || "light";

// Get language extension
const getLanguageExtension = useCallback((lang: string) => {
Expand Down Expand Up @@ -215,11 +215,19 @@ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(
// Debounced onChange for performance
let changeTimeout: ReturnType<typeof setTimeout>;

// Determine theme for initialization - prefer resolved theme but fallback to system preference
const initTheme =
resolvedTheme ||
(typeof window !== "undefined" &&
window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light");

// Create extensions with compartments
const extensions = [
...baseExtensions,
languageCompartment.of(getLanguageExtension(language)),
themeCompartment.of(getThemeExtension(activeTheme)),
themeCompartment.of(getThemeExtension(initTheme)),
readOnlyCompartment.of(EditorState.readOnly.of(readOnly)),
lineNumbersCompartment.of(
showLineNumbers ? [lineNumbers(), foldGutter()] : []
Expand Down