Reputation: 38641
I want to switch the codemirror6 theme, now I do it like this:
if (projConf.confYype == ProjConfType.Theme) {
const currentTheme = themeMap.get(projConf.confValue);
if (currentTheme) {
if (!activeEditorView) return;
var theme = new Compartment;
activeEditorView.dispatch({
effects: theme.reconfigure(currentTheme)
});
}
}
first I stored the theme in a map<string,theme>, and get the theme by name, set the theme into the editorView. But the codemirror6 theme did not changed, am I missing something? I am inspired from this question https://discuss.codemirror.net/t/how-to-change-editor-theme-dinamically/4173/5 from codemirror6 community.
Upvotes: 0
Views: 182
Reputation: 13529
Here's what I have as a solution:
import { EditorState, Compartment } from '@codemirror/state';
import { javascript } from '@codemirror/lang-javascript';
import { EditorView, basicSetup } from 'codemirror';
import { cobalt as darkTheme, clouds as lightTheme } from 'thememirror';
let theme = 'light';
const themeCompartment = new Compartment;
const extensions = [
basicSetup,
javascript(),
themeCompartment.of(theme === 'light' ? lightTheme : darkTheme)
];
let startState = EditorState.create({ doc: '...', extensions });
let editor = new EditorView({
state: startState,
parent: document.querySelector('#editor'),
});
// and then later at some point in your app
editor.dispatch({
effects: themeCompartment.reconfigure(theme === 'light' ? lightTheme : darkTheme)
})
Notice how we use the compartment on the first place when we initialize the editor's state. Then we use create the effect using that same compartment.
Upvotes: 2