File size: 1,277 Bytes
9332ccf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { Key } from '../contexts/KeypressContext.js';
export type { Key };
const SPECIAL_KEYS: Record<string, string> = {
up: '\x1b[A',
down: '\x1b[B',
right: '\x1b[C',
left: '\x1b[D',
escape: '\x1b',
tab: '\t',
backspace: '\x7f',
delete: '\x1b[3~',
home: '\x1b[H',
end: '\x1b[F',
pageup: '\x1b[5~',
pagedown: '\x1b[6~',
enter: '\r',
};
/**
* Translates a Key object into its corresponding ANSI escape sequence.
* This is useful for sending control characters to a pseudo-terminal.
*
* @param key The Key object to translate.
* @returns The ANSI escape sequence as a string, or null if no mapping exists.
*/
export function keyToAnsi(key: Key): string | null {
if (key.ctrl) {
// Ctrl + letter (A-Z maps to 1-26, e.g., Ctrl+C is \x03)
if (key.name >= 'a' && key.name <= 'z') {
return String.fromCharCode(
key.name.charCodeAt(0) - 'a'.charCodeAt(0) + 1,
);
}
}
// Arrow keys and other special keys
if (key.name in SPECIAL_KEYS) {
return SPECIAL_KEYS[key.name];
}
// If it's a simple character, return it.
if (!key.ctrl && !key.cmd && key.sequence) {
return key.sequence;
}
return null;
}
|