xterm中的attachCustomKeyEventHandler

· 2 min read

xterm.js中监听按键执行特殊处理需要用到attachCustomKeyEventHandler,这里说明下。

源码解读

/**
     * 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;

源码位置

 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;
    }
   ... 
  }
   

源码位置

由上可以看出

attachCustomKeyEventHandler中回调函数是在xterm.js中优先处理,之后才是xterm.js控制。回调函数在keydown/keyup/keypress阶段均会被触发。而回调函数返回值为void还是true效果一致,只有false才会阻止xterm.js进一步处理该按键输入,

举例

比如我希望xterm.js下按`ctrl ``时执行某个特殊动作,比如唤起AI,因此如下操作即可。

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

假如执行处理后还需要xterm.js继续处理,则return void或者true即可。

done。