Skip to content

Commit

Permalink
Focus the code editor on load when the "autoFocus" prop is set
Browse files Browse the repository at this point in the history
  • Loading branch information
emir89 committed Nov 27, 2024
1 parent b417911 commit 47a6122
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/extensions/codemirror/CodeMirror.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ export const LinterExample = TemplateFull.bind({});
LinterExample.args = {
name: "codeinput",
defaultValue: "**test me**",
mode: "json",
mode: "javascript",
useLinting: true,
};
21 changes: 17 additions & 4 deletions src/extensions/codemirror/CodeMirror.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,17 @@ export interface CodeEditorProps {
*/
enableTab?: boolean;
/**
* If the editor should use a linting feature.
* Enables linting feature in the editor.
*/
useLinting?: boolean;
/**
* Id used for testing
*/
dataTestId?: string;
/**
* Autofocus the editor when it is rendered
*/
autoFocus?: boolean;
}

const addExtensionsFor = (flag: boolean, ...extensions: Extension[]) => (flag ? [...extensions] : []);
Expand Down Expand Up @@ -184,13 +192,13 @@ export const CodeEditor = ({
enableTab = false,
height,
useLinting = false,
dataTestId,
autoFocus = false,
}: CodeEditorProps) => {
const parent = useRef<any>(undefined);

// console.log("outerDivAttributes", outerDivAttributes);

const linters = useMemo(() => {
if (!useLinting || !mode) {
if (!mode) {
return [];
}

Expand Down Expand Up @@ -297,6 +305,10 @@ export const CodeEditor = ({
view.dom.style.height = typeof height === "string" ? height : `${height}px`;
}

if (autoFocus) {
view.focus();
}

setEditorView && setEditorView(view);

return () => {
Expand All @@ -312,6 +324,7 @@ export const CodeEditor = ({
id={id ? id : name ? `codemirror-${name}` : undefined}
ref={parent}
data-test-id="codemirror-wrapper"
data-testid={dataTestId ? `${dataTestId}_codemirror}` : undefined}
className={
`${eccgui}-codeeditor ${eccgui}-codeeditor--mode-${mode}` +
(outerDivAttributes?.className ? ` ${outerDivAttributes?.className}` : "")
Expand Down

0 comments on commit 47a6122

Please sign in to comment.