Skip to content

Commit badce18

Browse files
committed
Add autoFocus prop to compass-editor
1 parent 2109acd commit badce18

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

packages/compass-editor/src/editor.spec.tsx

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React from 'react';
22
import { render, userEvent } from '@mongodb-js/testing-library-compass';
3-
import { CodemirrorInlineEditor } from './editor';
3+
import { CodemirrorInlineEditor, CodemirrorMultilineEditor } from './editor';
44
import type { EditorRef } from './types';
55
import { expect } from 'chai';
66

@@ -55,4 +55,13 @@ describe('Editor', function () {
5555
expect(editorRef.current?.editorContents).to.equal('{\n \n}');
5656
});
5757
});
58+
59+
context('CodemirrorMultilineEditor', function () {
60+
it('focuses the editor when autoFocus is true', function () {
61+
const editorRef = React.createRef<EditorRef>();
62+
render(
63+
<CodemirrorMultilineEditor text={'{}'} autoFocus ref={editorRef} />
64+
);
65+
});
66+
});
5867
});

packages/compass-editor/src/editor.tsx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,7 @@ type EditorProps = {
573573
placeholder?: Parameters<typeof codemirrorPlaceholder>[0];
574574
commands?: readonly KeyBinding[];
575575
initialJSONFoldAll?: boolean;
576+
autoFocus?: boolean;
576577
} & (
577578
| { text: string; initialText?: never }
578579
| { text?: never; initialText: string }
@@ -735,6 +736,7 @@ const BaseEditor = React.forwardRef<EditorRef, EditorProps>(function BaseEditor(
735736
placeholder,
736737
commands,
737738
initialJSONFoldAll: _initialJSONFoldAll = true,
739+
autoFocus = true,
738740
...props
739741
},
740742
ref
@@ -1201,6 +1203,14 @@ const BaseEditor = React.forwardRef<EditorRef, EditorProps>(function BaseEditor(
12011203
}
12021204
}, [maxLines, contentHeight, hasScroll, lineHeight, showScroll]);
12031205

1206+
const autoFocusRef = useRef(autoFocus);
1207+
1208+
useLayoutEffect(() => {
1209+
if (autoFocusRef.current) {
1210+
editorViewRef.current?.focus();
1211+
}
1212+
}, [autoFocusRef]);
1213+
12041214
return (
12051215
<div
12061216
ref={containerRef}

0 commit comments

Comments
 (0)