StackUnderFlow
StackUnderFlow

Reputation: 367

Using Hot Keys with Monaco Editor?

I'm trying to use hot keys in a monaco editor to run a function when cmd + enter is pressed using the 'react-hotkeys-hook' npm package.

I have it working when I click off from the monaco editor. It seems when the cursor is focused in the editor, the hot keys don't work.

Is there a way to make the hot keys work while also typing in the monaco editor instead of manually clicking off to anther div?

Here is some of the code I'm working on:

import React from "react";
import Editor from "@monaco-editor/react";
import { useHotkeys } from "react-hotkeys-hook";

export default function codeEditor(props) {
useHotkeys("cmd+enter", () => runCode());

function runCode() {
  alert('Running code...')
}

return (
    <div className="editor-container">
      <Editor
        defaultValue={`Hello World`}
        onMount={handleEditorDidMount}
        width="100%"
        height="80vh"
        theme="vs-dark"
        fontSize='20px'
        defaultLanguage="javascript"
        options={{
          fontSize: '18px'
        }}  
      />
    </div>
  )
}

Upvotes: 5

Views: 3246

Answers (2)

Mike Lischke
Mike Lischke

Reputation: 53437

I have never used react-hotkeys-hook, but I registered multiple shortcuts in the editor, including cmd / ctrl + enter:

            editor.addAction({
                id: "executeCurrentAndAdvance",
                label: "Execute Block and Advance",
                keybindings: [KeyMod.CtrlCmd | KeyCode.Enter],
                contextMenuGroupId: "2_execution",
                precondition: blockContext,
                run: () => {
                    // run your code for the action here
                },
            });

with the precondition:

        const blockContext = "editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode " +
            "&& !quickFixWidgetVisible";

Upvotes: 2

MaxAlex
MaxAlex

Reputation: 3319

Try using the following call form:

useHotkeys("cmd+enter", () => runCode(), {enableOnTags: ['INPUT','TEXTAREA','SELECT']});

"enableOnTags: string[] is used to enable listening to hotkeys in form fields".

Upvotes: -1

Related Questions