Monaco Editor 中的 Keybinding 機制
一、前言
前段時間碰到了一個 Keybinding 相關的問題,於是探究了一番,首先大家可能會有兩個問題:Monaco Editor 是啥?Keybinding 又是啥?
- Monaco Editor:
微軟開源的一個代碼編輯器,為 VS Code 的編輯器提供支持,Monaco Editor 核心代碼與 VS Code 是共用的(都在 VS Code github 倉庫中)。 - Keybinding:
Monaco Editor 中實現快捷鍵功能的機制(其實準確來說,應該是部分機制),可以使得通過快捷鍵來執行操作,例如打開命令面板、切換主題以及編輯器中的一些快捷操作等。
本文主要是針對 Monaco Editor 的 Keybinding 機制進行介紹,由於源碼完整的邏輯比較龐雜,所以本文中的展示的源碼以及流程會有一定的簡化。
文中使用的代碼版本:
Monaco Editor:0.30.1
VS Code:1.62.1
二、舉個🌰
這裡使用 monaco-editor 創建了一個簡單的例子,後文會基於這個例子來進行介紹。
import React, { useRef, useEffect, useState } from "react";
import * as monaco from "monaco-editor";
import { codeText } from "./help";
const Editor = () => {
const domRef = useRef<HTMLDivElement>(null);
const [actionDispose, setActionDispose] = useState<monaco.IDisposable>();
useEffect(() => {
const editorIns = monaco.editor.create(domRef.current!, {
value: codeText,
language: "typescript",
theme: "vs-dark",
});
const action = {
id: 'test',
label: 'test',
precondition: 'isChrome == true',
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyL],
run: () => {
window.alert('chrome: cmd + k');
},
};
setActionDispose(editorIns.addAction(action));
editorIns.focus();
return () => {
editorIns.dispose();
};
}, []);
const onClick = () => {
actionDispose?.dispose();
window.alert('已卸載');
};
return (
<div>
<div ref={domRef} className='editor-container' />
<button className='cancel-button' onClick={onClick}>卸載keybinding</button>
</div>
);
};
export default Editor;
三、原理機制
1. 概覽
根據上面的例子,Keybinding 機制的總體流程可以簡單的分為以下幾步:
- 初始化:主要是初始化服務以及給 dom 添加監聽事件
- 註冊:註冊 keybinding 和 command
- 執行:通過按快捷鍵觸發執行對應的 keybinding 和 command
- 卸載:清除註冊的 keybinding 和 command
2. 初始化
回到上面例子中創建 editor 的代碼:
const editorIns = monaco.editor.create(domRef.current!, {
value: codeText,
language: "typescript",
theme: "vs-dark",
});
初始化過程如下:
創建 editor 之前會先初始化 services,通過實例化 DynamicStandaloneServices 類創建服務:
let services = new DynamicStandaloneServices(domElement, override);
在 constructor 函數中會執行以下代碼註冊 keybindingService:
let keybindingService = ensure(IKeybindingService, () =>
this._register(
new StandaloneKeybindingService(
contextKeyService,
commandService,
telemetryService,
notificationService,
logService,
domElement
)
)
);
其中 this._register 方法和 ensure 方法會分別將 StandaloneKeybindingServices 實例保存到 disposable 對象(用於卸載)和 this._serviceCollection 中(用於執行過程查找keybinding)。
實例化 StandaloneKeybindingService,在 constructor 函數中添加 DOM 監聽事件:
this._register(
dom.addDisposableListener(
domNode,
dom.EventType.KEY_DOWN,
(e: KeyboardEvent) => {
const keyEvent = new StandardKeyboardEvent(e);
const shouldPreventDefault = this._dispatch(
keyEvent,
keyEvent.target
);
if (shouldPreventDefault) {
keyEvent.preventDefault();
keyEvent.stopPropagation();
}
}
)
);
以上代碼中的 dom.addDisposableListener 方法,會通過 addEventListener 的方式,在 domNode 上添加一個 keydown 事件的監聽函數,並且返回一個 DomListener 的實例,該實例包含一個用於移除事件監聽的 dispose 方法。然後通過 this._register 方法將 DomListener 的實例保存起來。
3. 註冊 keybindings
回到例子中的代碼:
const action = {
id: 'test',
label: 'test',
precondition: 'isChrome == true',
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyL],
run: () => {
window.alert('chrome: cmd + k');
},
};
setActionDispose(editorIns.addAction(action));
註冊過程如下:
當通過 editorIns.addAction 來註冊 keybinding 時,會調用 StandaloneKeybindingServices 實例的 addDynamicKeybinding 方法來註冊 keybinding。
public addDynamicKeybinding(
commandId: string,
_keybinding: number,
handler: ICommandHandler,
when: ContextKeyExpression | undefined
): IDisposable {
const keybinding = createKeybinding(_keybinding, OS);
const toDispose = new DisposableStore();
if (keybinding) {
this._dynamicKeybindings.push({
keybinding: keybinding.parts,
command: commandId,
when: when,
weight1: 1000,
weight2: 0,
extensionId: null,
isBuiltinExtension: false,
});
toDispose.add(
toDisposable(() => {
for (let i = 0; i < this._dynamicKeybindings.length; i++) {
let kb = this._dynamicKeybindings[i];
if (kb.command === commandId) {
this._dynamicKeybindings.splice(i, 1);
this.updateResolver({
source: KeybindingSource.Default,
});
return;
}
}
})
);
}
toDispose.add(CommandsRegistry.registerCommand(commandId, handler));
this.updateResolver({ source: KeybindingSource.Default });
return toDispose;
}
會先根據傳入的 _keybinding 創建 keybinding 實例,然後連同 command、when 等其他信息存入_dynamicKeybindings 數組中,同時會註冊對應的 command,當後面觸發 keybinding 時便執行對應的 command。返回的 toDispose 實例則用於取消對應的 keybinding 和 command。
回到上面代碼中創建 keybinding 實例的地方,createKeybinding 方法會根據傳入的 _keybinding 數字和 OS 類型得到實例,大致結構如下(已省略部分屬性):
{
parts: [
{
ctrlKey: boolean,
shiftKey: boolean,
altKey: boolean,
metaKey: boolean,
keyCode: KeyCode,
}
],
}
那麼,是怎麼通過一個 number 得到所有按鍵信息的呢?往下看↓↓↓
4. key的轉換
先看看一開始傳入的 keybinding 是什麼:
const action = {
id: 'test',
label: 'test',
precondition: 'isChrome == true',
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyL],
run: () => {
window.alert('chrome: cmd + k');
},
};
傳入的 keybinding 就是上面代碼中的 keybindings 數組中的元素,monaco.KeyMod.CtrlCmd = 2048,monaco.KeyCode.KeyL = 42,對應的數字是 monaco-editor 中定義的枚舉值,與真實的 keyCode 存在對應關係。所以註冊時傳入的 keybinding 參數為: 2048 | 42 = 2090
先簡單了解下 JS 中的位運算(操作的是32位帶符號的二進制整數,下面例子中只用8位簡單表示):
按位與(AND)&
對應的位都為1則返回1,否則返回0
例如:
00001010 // 10
00000110 // 6
——
00000010 // 2
按位或(OR)|
對應的位,只要有一個為1則返回1,否則返回0
00001010 // 10
00000110 // 6
——-
00001110 // 14
左移(Left shift)<<
將二進制數每一位向左移動指定位數,左側移出的位捨棄,右側補0
00001010 // 10
——- // 10 << 2
00101000 // 40
右移 >>
將二進制數每位向右移動指定位數,右側移出的位捨棄,左側用原來最左邊的數補齊
00001010 // 10
——- // 10 >> 2
00000010 // 2
無符號右移 >>>
將二進制數每位向右移動指定位數,右側移出的位捨棄,左側補0
00001010 // 10
——- // 10 >> 2
00000010 // 2
接下來看下是怎麼根據一個數字,創建出對應的 keybinding 實例:
export function createKeybinding(keybinding: number, OS: OperatingSystem): Keybinding | null {
if (keybinding === 0) {
return null;
}
const firstPart = (keybinding & 0x0000FFFF) >>> 0;
// 處理分兩步的keybinding,例如:shift shift,若無第二部分,則chordPart = 0
const chordPart = (keybinding & 0xFFFF0000) >>> 16;
if (chordPart !== 0) {
return new ChordKeybinding([
createSimpleKeybinding(firstPart, OS),
createSimpleKeybinding(chordPart, OS)
]);
}
return new ChordKeybinding([createSimpleKeybinding(firstPart, OS)]);
}
看下 createSimpleKeybinding 方法做了什麼
const enum BinaryKeybindingsMask {
CtrlCmd = (1 << 11) >>> 0, // 2048
Shift = (1 << 10) >>> 0, // 1024
Alt = (1 << 9) >>> 0, // 512
WinCtrl = (1 << 8) >>> 0, // 256
KeyCode = 0x000000FF // 255
}
export function createSimpleKeybinding(keybinding: number, OS: OperatingSystem): SimpleKeybinding {
const ctrlCmd = (keybinding & BinaryKeybindingsMask.CtrlCmd ? true : false);
const winCtrl = (keybinding & BinaryKeybindingsMask.WinCtrl ? true : false);
const ctrlKey = (OS === OperatingSystem.Macintosh ? winCtrl : ctrlCmd);
const shiftKey = (keybinding & BinaryKeybindingsMask.Shift ? true : false);
const altKey = (keybinding & BinaryKeybindingsMask.Alt ? true : false);
const metaKey = (OS === OperatingSystem.Macintosh ? ctrlCmd : winCtrl);
const keyCode = (keybinding & BinaryKeybindingsMask.KeyCode);
return new SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode);
}
拿上面的例子:keybinding = monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyL,即 keybinding = 2048 | 42 = 2090,然後看上面代碼中的:
const ctrlCmd = (keybinding & BinaryKeybindingsMask.CtrlCmd ? true : false);
運算如下:
100000101010 // 2090 -> keybinding
100000000000 // 2048 -> CtrlCmd
———– // &
100000000000 // 2048 -> CtrlCmd
再看keyCode的運算:
const keyCode = (keybinding & BinaryKeybindingsMask.KeyCode)
100000101010 // 2090 -> keybinding
000011111111 // 255 -> KeyCode
———– // &
000000101010 // 42 -> KeyL
於是便得到了 ctrlKey,shiftKey,altKey,metaKey,keyCode 這些值,接下來便由這些值生成SimpleKeybinding實例,該實例包含了上面的這些按鍵信息以及一些操作方法。
至此,已經完成了 keybinding 的註冊,將 keybinding 實例及相關信息存入了 StandaloneKeybindingService 實例的 _dynamicKeybindings 數組中,對應的 command 也註冊到了 CommandsRegistry 中。
5.執行
當用戶在鍵盤上按下快捷鍵時,便會觸發 keybinding 對應 command 的執行,執行過程如下:
回到 StandaloneKeybindingServices 初始化的時候,在 domNode 上綁定了 keydown 事件監聽函數:
(e: KeyboardEvent) => {
const keyEvent = new StandardKeyboardEvent(e);
const shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
if (shouldPreventDefault) {
keyEvent.preventDefault();
keyEvent.stopPropagation();
}
};
當 keydown 事件觸發後,便會執行這個監聽函數,首先會實例化一個 StandardKeyboardEvent 實例,該實例包含了一些按鍵信息和方法,大致結構如下(已省略部分屬性):
{
target: HTMLElement,
ctrlKey: boolean,
shiftKey: boolean,
altKey: boolean,
metaKey: boolean,
keyCode: KeyCode,
}
其中 keyCode 是經過處理後得到的,由原始鍵盤事件的 keyCode 轉換為 monoco-editor 中的 keyCode,轉換過程主要就是兼容一些不同的瀏覽器,並根據映射關係得到最終的 keyCode。准換方法如下:
function extractKeyCode(e: KeyboardEvent): KeyCode {
if (e.charCode) {
// "keypress" events mostly
let char = String.fromCharCode(e.charCode).toUpperCase();
return KeyCodeUtils.fromString(char);
}
const keyCode = e.keyCode;
// browser quirks
if (keyCode === 3) {
return KeyCode.PauseBreak;
} else if (browser.isFirefox) {
if (keyCode === 59) {
return KeyCode.Semicolon;
} else if (keyCode === 107) {
return KeyCode.Equal;
} else if (keyCode === 109) {
return KeyCode.Minus;
} else if (platform.isMacintosh && keyCode === 224) {
return KeyCode.Meta;
}
} else if (browser.isWebKit) {
if (keyCode === 91) {
return KeyCode.Meta;
} else if (platform.isMacintosh && keyCode === 93) {
// the two meta keys in the Mac have different key codes (91 and 93)
return KeyCode.Meta;
} else if (!platform.isMacintosh && keyCode === 92) {
return KeyCode.Meta;
}
}
// cross browser keycodes:
return EVENT_KEY_CODE_MAP[keyCode] || KeyCode.Unknown;
}
得到了 keyEvent 實例對象後,便通過 this._dispatch(keyEvent, keyEvent.target) 執行。
protected _dispatch(
e: IKeyboardEvent,
target: IContextKeyServiceTarget
): boolean {
return this._doDispatch(
this.resolveKeyboardEvent(e),
target,
/*isSingleModiferChord*/ false
);
}
直接調用了 this._doDispatch 方法,通過 this.resolveKeyboardEvent(e) 方法處理傳入的 keyEvent,得到一個包含了許多 keybinding 操作方法的實例。
接下來主要看下 _doDispatch 方法主要幹了啥(以下僅展示了部分代碼):
private _doDispatch(
keybinding: ResolvedKeybinding,
target: IContextKeyServiceTarget,
isSingleModiferChord = false
): boolean {
const resolveResult = this._getResolver().resolve(
contextValue,
currentChord,
firstPart
);
if (resolveResult && resolveResult.commandId) {
if (typeof resolveResult.commandArgs === 'undefined') {
this._commandService
.executeCommand(resolveResult.commandId)
.then(undefined, (err) =>
this._notificationService.warn(err)
);
} else {
this._commandService
.executeCommand(
resolveResult.commandId,
resolveResult.commandArgs
)
.then(undefined, (err) =>
this._notificationService.warn(err)
);
}
}
}
主要是找到 keybinding 對應的 command 並執行,_getResolver 方法會拿到已註冊的 keybinding,然後通過 resolve 方法找到對應的 keybinding 及 command 信息。而執行 command 則會從 CommandsRegistry 中找到對應已註冊的 command,然後執行 command 的 handler 函數(即keybinding 的回調函數)。
6.卸載
先看看一開始的例子中的代碼:
const onClick = () => {
actionDispose?.dispose();
window.alert('已卸載');
};
卸載過程如下:
回到剛開始註冊時:setActionDispose(editorIns.addAction(action)),addAction 方法會返回一個 disposable 對象,setActionDispose 將該對象保存了起來。通過調用該對象的 dispose 方法:actionDispose.dispose(),便可卸載該 action,對應的 command 和 keybinding 便都會被卸載。
四、結語
對 Monaco Editor 的 Keybinding 機制進行簡單描述,就是通過監聽用戶的鍵盤輸入,找到對應註冊的 keybinding 和 command,然後執行對應的回調函數。但仔細探究的話,每個過程都有很多處理邏輯,本文也只是對其做了一個大體的介紹,實際上還有許多相關的細節沒有講到,感興趣的同學可以探索探索。