lowcode-engine/packages/engine-core/src/keybinding/keybindingParser.ts

91 lines
2.2 KiB
TypeScript

import { KeyCodeUtils } from '../common';
import { KeyCodeChord, Keybinding } from './keybindings';
export class KeybindingParser {
private static _readModifiers(input: string) {
input = input.toLowerCase().trim();
let ctrl = false;
let shift = false;
let alt = false;
let meta = false;
let matchedModifier: boolean;
do {
matchedModifier = false;
if (/^ctrl(\+|-)/.test(input)) {
ctrl = true;
input = input.slice('ctrl-'.length);
matchedModifier = true;
}
if (/^shift(\+|-)/.test(input)) {
shift = true;
input = input.slice('shift-'.length);
matchedModifier = true;
}
if (/^alt(\+|-)/.test(input)) {
alt = true;
input = input.slice('alt-'.length);
matchedModifier = true;
}
if (/^meta(\+|-)/.test(input)) {
meta = true;
input = input.slice('meta-'.length);
matchedModifier = true;
}
if (/^win(\+|-)/.test(input)) {
meta = true;
input = input.slice('win-'.length);
matchedModifier = true;
}
if (/^cmd(\+|-)/.test(input)) {
meta = true;
input = input.slice('cmd-'.length);
matchedModifier = true;
}
} while (matchedModifier);
let key: string;
const firstSpaceIdx = input.indexOf(' ');
if (firstSpaceIdx > 0) {
key = input.substring(0, firstSpaceIdx);
input = input.substring(firstSpaceIdx);
} else {
key = input;
input = '';
}
return {
remains: input,
ctrl,
shift,
alt,
meta,
key,
};
}
private static parseChord(input: string): [KeyCodeChord, string] {
const mods = this._readModifiers(input);
const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
return [new KeyCodeChord(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
static parseKeybinding(input: string): Keybinding | null {
if (!input) {
return null;
}
const chords: KeyCodeChord[] = [];
let chord: KeyCodeChord;
while (input.length > 0) {
[chord, input] = this.parseChord(input);
chords.push(chord);
}
return chords.length > 0 ? new Keybinding(chords) : null;
}
}