How to add Editor Action in monaco-editor?

I have learned a lot while working on my Tinkerwell alternative project. One of them was the Monaco Editor. This time, the problem I want to tackle is having custom commands for the Monaco Editor.

I want to be able to listen when the Cmd + Enter key is pressed. I also want to show the command when the user right-clicks on the editor. This is how it looks:

monaco-editor-action-command.png

Editor Action

After some research I found that we can add custom action to monaco editor. So here's my action I created to achieve that runner code.

const executeAction: monaco.editor.IActionDescriptor = {
    id: "run-code",
    label: "Run Code",
    contextMenuOrder: 2,
    contextMenuGroupId: "1_modification",
    keybindings: [
        KeyMod.CtrlCmd | KeyCode.Enter,
    ],
    run: runTinker,
}

Here is a brief description for this code.

  1. id: A unique identifier for the action.
  2. label: The label of the action, this will be displayed in the context menu.
  3. contextMenuOrder: The order in which the action should be displayed in the context menu, if you want to show this at the top set it to 0.
  4. contextMenuGroupId: The group id of the action, set to 1_modification there are three options for this group id.
    1. navigation - The navigation group comes first in all cases.
    2. 1_modification - This group comes next and contains commands that modify your code.
    3. 9_cutcopypaste - The last default group with the basic editing commands.
  5. keybindings: The keybindings to trigger the action, set to [CtrlCmd + Enter].
  6. run: A function to be called when the action is triggered.

Don't forget to register the command to the editor.

monaco.editor.addEditorAction(executeAction)

And I think that's all. I hope you find this useful. Let me know if you have any questions.