attachCustomKeyEventHandler in xterm.js

Apr 13, 2024 · 2 min read · 346 Words · -Views -Comments

To handle special key behavior in xterm.js, use attachCustomKeyEventHandler. Here’s how it works.

Source Walkthrough

/**
     * Attaches a custom key event handler which is run before keys are
     * processed, giving consumers of xterm.js ultimate control as to what keys
     * should be processed by the terminal and what keys should not.
     * @param customKeyEventHandler The custom KeyboardEvent handler to attach.
     * This is a function that takes a KeyboardEvent, allowing consumers to stop
     * propagation and/or prevent the default action. The function returns
     * whether the event should be processed by xterm.js.
     *
     * @example A custom keymap that overrides the backspace key
     * ```ts
     * const keymap = [
     *   { "key": "Backspace", "shiftKey": false, "mapCode": 8 },
     *   { "key": "Backspace", "shiftKey": true, "mapCode": 127 }
     * ];
     * term.attachCustomKeyEventHandler(ev => {
     *   if (ev.type === 'keydown') {
     *     for (let i in keymap) {
     *       if (keymap[i].key == ev.key && keymap[i].shiftKey == ev.shiftKey) {
     *         socket.send(String.fromCharCode(keymap[i].mapCode));
     *         return false;
     *       }
     *     }
     *   }
     * });
     * ```
     */
attachCustomKeyEventHandler(customKeyEventHandler: (event: KeyboardEvent) => boolean): void;

Source location

 protected _keyDown(event: KeyboardEvent): boolean | undefined {
    this._keyDownHandled = false;
    this._keyDownSeen = true;

    if (this._customKeyEventHandler && this._customKeyEventHandler(event) === false) {
      return false;
    }
    ...
 }
 protected _keyUp(ev: KeyboardEvent): void {
    this._keyDownSeen = false;

    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
      return;
    }
    ...
  }
   protected _keyPress(ev: KeyboardEvent): boolean {
    let key;

    this._keyPressHandled = false;

    if (this._keyDownHandled) {
      return false;
    }

    if (this._customKeyEventHandler && this._customKeyEventHandler(ev) === false) {
      return false;
    }
   ... 
  }
   

Source location

From the above we can see:

The callback provided to attachCustomKeyEventHandler runs before xterm.js processes keys. It fires on keydown/keyup/keypress. Returning void or true has the same effect; only returning false prevents xterm.js from further processing the key event.

Example

Suppose I want `Ctrl + `` in xterm.js to trigger a special action (e.g., invoke AI). Do this:

term.attachCustomKeyEventHandler((event)=>{
  if (event.type==='keydown'&&'`' === event.key && event.ctrlKey) {
    // dosomething
    return false;
  }
}); 

If you still want xterm.js to process the key after your handler, return void or true.

Done.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover