I’m trying to set up a basic JSON code editor that can be readOnly.
This tells me that it can be done as an extension and I also found the readOnly prop
But I just can’t figure out how to glue things together
I’m trying to set up a basic JSON code editor that can be readOnly.
This tells me that it can be done as an extension and I also found the readOnly prop
But I just can’t figure out how to glue things together
You need to use the readOnly
facet as an extension in your view. For example, to set the editor as readOnly, you need to add this to your extensions:
EditorState.readOnly.of(true)
EditorState.readOnly.of(true)
hello, can i add it to EditorState after running extensions, as trigger - select readOnly / deselect readOnly
and how ? if you have some code example - please let me understand how it works )
See the configuration example.
You can do that with extension
import { EditorView } from "@codemirror/view"
import { EditorState } from "@codemirror/state"
let editable = false
new EditorView ({
extensions: [ EditorState.readOnly.of(editable), ...]
...
})
I have also struggled to find a “setReadOnly” method/property to make an editor read-only. It should be like an on/off switch available after the editor has been created or loaded.
What I finally did was to set the “contenteditable” property of the “cm-content” element to “false” or to “true” as needed.
document.querySelector("#editor .cm-content").setAttribute("contenteditable","false");
A CSS class can also be added to show a visual effect defining the read-only status to the user.
document.querySelector("#editor .cm-content").classList.add("cm-editor-readonly");
The function in traditional JS:
function setReadOnly(readOnly){
if( readOnly ){
document.querySelector("#editor .cm-content").classList.add("cm-editor-readonly");
document.querySelector("#editor .cm-content").setAttribute("contenteditable","false");
}else{
document.querySelector("#editor .cm-content").classList.remove("cm-editor-readonly");
document.querySelector("#editor .cm-content").setAttribute("contenteditable","true");
}
}
The user can still scroll and copy code, which I wanted. But now I can switch to read-only on demand.
In the end, CodeMirror operates the DOM too. I consider this a “hack” until I found the easy way to just do EditorView.setReadOnly(true)
.
I hope this helps someone.
That’s very much not how you do this. This example covers dynamic configuration.