11import React , { useMemo , useRef } from "react" ;
22import { defaultKeymap , indentWithTab } from "@codemirror/commands" ;
33import { foldKeymap } from "@codemirror/language" ;
4- import { EditorState , Extension } from "@codemirror/state" ;
4+ import { EditorState , Extension , Compartment } from "@codemirror/state" ;
55import { DOMEventHandlers , EditorView , KeyBinding , keymap , Rect , ViewUpdate } from "@codemirror/view" ;
66import { minimalSetup } from "codemirror" ;
77
@@ -221,7 +221,12 @@ export const CodeEditor = ({
221221} : CodeEditorProps ) => {
222222 const parent = useRef < any > ( undefined ) ;
223223 const [ view , setView ] = React . useState < EditorView | undefined > ( ) ;
224+ const currentView = React . useRef < EditorView > ( )
225+ currentView . current = view
226+ const currentReadOnly = React . useRef ( readOnly )
227+ currentReadOnly . current = readOnly
224228 const [ showPreview , setShowPreview ] = React . useState < boolean > ( false ) ;
229+ const readOnlyCompartment = React . useRef < Compartment > ( new Compartment ( ) )
225230
226231 const linters = useMemo ( ( ) => {
227232 if ( ! mode ) {
@@ -240,7 +245,7 @@ export const CodeEditor = ({
240245
241246 const onKeyDownHandler = ( event : KeyboardEvent , view : EditorView ) => {
242247 if ( onKeyDown && ! onKeyDown ( event ) ) {
243- if ( event . key === "Enter" ) {
248+ if ( event . key === "Enter" && ! currentReadOnly . current ) {
244249 const cursor = view . state . selection . main . head ;
245250 const cursorLine = view . state . doc . lineAt ( cursor ) . number ;
246251 const offsetFromFirstLine = view . state . doc . line ( cursorLine ) . to ;
@@ -291,7 +296,7 @@ export const CodeEditor = ({
291296 useCodeMirrorModeExtension ( mode ) ,
292297 keymap ?. of ( keyMapConfigs ) ,
293298 EditorState ?. tabSize . of ( tabIntentSize ) ,
294- EditorState ?. readOnly . of ( readOnly ) ,
299+ readOnlyCompartment . current . of ( EditorState ?. readOnly . of ( readOnly ) ) ,
295300 EditorView ?. editable . of ( ! disabled ) ,
296301 AdaptedEditorViewDomEventHandlers ( domEventHandlers ) as Extension ,
297302 EditorView ?. updateListener . of ( ( v : ViewUpdate ) => {
@@ -377,6 +382,14 @@ export const CodeEditor = ({
377382 } ;
378383 } , [ parent . current , mode , preventLineNumbers , wrapLines ] ) ;
379384
385+ React . useEffect ( ( ) => {
386+ const v = EditorState ?. readOnly . of ( readOnly ! )
387+
388+ currentView . current ?. dispatch ( {
389+ effects : readOnlyCompartment . current . reconfigure ( v )
390+ } )
391+ } , [ readOnly ] )
392+
380393 const hasToolbarSupport = mode && ModeToolbarSupport . indexOf ( mode ) > - 1 && useToolbar ;
381394
382395 const editorToolbar = ( mode ?: SupportedCodeEditorModes ) : JSX . Element => {
0 commit comments