monaco do not apply keyboard hit on editor on certain case

Viewed 25

I am using monaco-editor, I would like to define that when user hits Enter key, it will apply only on certain condition.

Here is my code:

  renderEditor(el: HTMLElement) {
    this.editor = monaco.editor.create(el, {
       ...
       ...
    });
    this.editor.onKeyDown(this.keyDown);
  }

  keyDown(event: IKeyboardEvent): void {
    if (event.code == 'ArrowDown') {
      const shouldInsertNewLine = checkIfEnterShouldApplyOnEditorOrNot();
      if(! shouldInsertNewLine){
          // ?? code here to cancel the 'ArrowDown' hit ??
          // (other action happens instead)
      }
    }
  }

now if checkIfShouldMoveCursorOnEditorOrNot returns false, then arrowDown key should not apply on editor (cursor should not move to next line).

How can I achieve that?

I tried using event.preventDefault() but it doesn't work.

1 Answers

can use editor.addCommand
found an answer here https://github.com/Microsoft/monaco-editor/issues/940,
see example: https://microsoft.github.io/monaco-editor/playground.html#interacting-with-the-editor-adding-a-command-to-an-editor-instance

  renderEditor(el: HTMLElement) {
    this.editor = monaco.editor.create(el, {..});
    this.editor.onKeyDown(this.keyDown);

    this.shouldInsertNewLine = this.editor.createContextKey('shouldInsertNewLine', true);
    this.editor.addCommand(monaco.KeyCode.Enter, this.shouldInsertNewLine.reset, '!shouldInsertNewLine');
  }

  keyDown(event: IKeyboardEvent): void {
    if (event.code == 'ArrowDown') {
      const shouldInsertNewLine = checkIfEnterShouldApplyOnEditorOrNot();

      this.shouldInsertNewLine?.set(shouldInsertNewLine);

    }
  }
Related