Hello,
I’m using the CodeMirror package to write a coding tutor, but I’m struggling to add and remove decorations. I want to highlight the text in specific places via a function, and if the code is updated (which means it was edited) the highlighting should disappear.
It worked as long as I only added a highlight, but after adding a StateEffect to remove the highlighting I added the condition to check for effect.is(), which will always return false for me.
I based this off of the example: CodeMirror Decoration Example
and this question: How to remove a decoration mark from state
My code looks like this:
const highlightExtension = StateField.define({
create() {
return Decoration.none
},
update(decorations, transaction) {
decorations = decorations.map(transaction.changes)
for (let effect of transaction.effects) {
if (effect.is(addHightlight)) {
decorations = decorations.update({ add: effect.value, sort: true })
} else if (effect.is(addHightlight)) {
decorations = decorations.update({
filter: (f, t, value) => value.range !== undefined,
})
} else {
// will always land here. -> Console Error: effect.is is not a function
}
}
return decorations
},
provide: (f) => EditorView.decorations.from(f),
})
const addHightlight = StateEffect.define()
const removeHighlight = StateEffect.define()
const highlightDecoration = Decoration.mark({
attributes: { style: "background-color: red" },
})
let state = EditorState.create({
doc: initialcode,
extensions: [basicSetup, javascript(), highlightExtension],
})
function addDecorationHighlight(start, end) {
view.dispatch({
effects: StateEffect.define({
map: ({ from, to }) => addHighlight.of({ from, to }),
}).of([highlightDecoration.range(start, end)]),
})
}
function removeDecorationHighlight(start, end) {
view.dispatch({
effects: StateEffect.define({
map: ({ from, to }) => removeHighlight.of({ from, to }),
}).of([highlightDecoration.range(start, end)]),
})
}
let view = new EditorView({
state,
parent: document.getElementById("codeeditor"),
})
I`m not sure what exactly is different in my code and why it doesn’t work. Appreciate any help and tips (or code snippets). Thank you very much!