mirror of
https://github.com/google-gemini/gemini-cli.git
synced 2026-05-13 05:12:55 -07:00
Refactor KeypressContext (#11677)
This commit is contained in:
committed by
GitHub
parent
047bc44032
commit
1202dced73
@@ -76,101 +76,10 @@ const ALT_KEY_CHARACTER_MAP: Record<string, string> = {
|
||||
'\u03A9': 'z',
|
||||
};
|
||||
|
||||
export interface Key {
|
||||
name: string;
|
||||
ctrl: boolean;
|
||||
meta: boolean;
|
||||
shift: boolean;
|
||||
paste: boolean;
|
||||
sequence: string;
|
||||
kittyProtocol?: boolean;
|
||||
}
|
||||
|
||||
export type KeypressHandler = (key: Key) => void;
|
||||
|
||||
interface KeypressContextValue {
|
||||
subscribe: (handler: KeypressHandler) => void;
|
||||
unsubscribe: (handler: KeypressHandler) => void;
|
||||
}
|
||||
|
||||
const KeypressContext = createContext<KeypressContextValue | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
export function useKeypressContext() {
|
||||
const context = useContext(KeypressContext);
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
'useKeypressContext must be used within a KeypressProvider',
|
||||
);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
export function KeypressProvider({
|
||||
children,
|
||||
kittyProtocolEnabled,
|
||||
config,
|
||||
debugKeystrokeLogging,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
kittyProtocolEnabled: boolean;
|
||||
config?: Config;
|
||||
debugKeystrokeLogging?: boolean;
|
||||
}) {
|
||||
const { stdin, setRawMode } = useStdin();
|
||||
const subscribers = useRef<Set<KeypressHandler>>(new Set()).current;
|
||||
const isDraggingRef = useRef(false);
|
||||
const dragBufferRef = useRef('');
|
||||
const draggingTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
const subscribe = useCallback(
|
||||
(handler: KeypressHandler) => {
|
||||
subscribers.add(handler);
|
||||
},
|
||||
[subscribers],
|
||||
);
|
||||
|
||||
const unsubscribe = useCallback(
|
||||
(handler: KeypressHandler) => {
|
||||
subscribers.delete(handler);
|
||||
},
|
||||
[subscribers],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const clearDraggingTimer = () => {
|
||||
if (draggingTimerRef.current) {
|
||||
clearTimeout(draggingTimerRef.current);
|
||||
draggingTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const wasRaw = stdin.isRaw;
|
||||
if (wasRaw === false) {
|
||||
setRawMode(true);
|
||||
}
|
||||
|
||||
const keypressStream = new PassThrough();
|
||||
let usePassthrough = false;
|
||||
const nodeMajorVersion = parseInt(process.versions.node.split('.')[0], 10);
|
||||
if (
|
||||
nodeMajorVersion < 20 ||
|
||||
process.env['PASTE_WORKAROUND'] === '1' ||
|
||||
process.env['PASTE_WORKAROUND'] === 'true'
|
||||
) {
|
||||
usePassthrough = true;
|
||||
}
|
||||
|
||||
let isPaste = false;
|
||||
let pasteBuffer = Buffer.alloc(0);
|
||||
let kittySequenceBuffer = '';
|
||||
let kittySequenceTimeout: NodeJS.Timeout | null = null;
|
||||
let backslashTimeout: NodeJS.Timeout | null = null;
|
||||
let waitingForEnterAfterBackslash = false;
|
||||
|
||||
// Check if a buffer could potentially be a valid kitty sequence or its prefix
|
||||
const couldBeKittySequence = (buffer: string): boolean => {
|
||||
/**
|
||||
* Check if a buffer could potentially be a valid kitty sequence or its prefix.
|
||||
*/
|
||||
function couldBeKittySequence(buffer: string): boolean {
|
||||
// Kitty sequences always start with ESC[.
|
||||
if (buffer.length === 0) return true;
|
||||
if (buffer === ESC || buffer === `${ESC}[`) return true;
|
||||
@@ -196,18 +105,21 @@ export function KeypressProvider({
|
||||
// Anything else starting with ESC[ that doesn't match our patterns
|
||||
// is likely not a kitty sequence we handle
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
// Parse a single complete kitty sequence from the start (prefix) of the
|
||||
// buffer and return both the Key and the number of characters consumed.
|
||||
// This lets us "peel off" one complete event when multiple sequences arrive
|
||||
// in a single chunk, preventing buffer overflow and fragmentation.
|
||||
// Parse a single complete kitty/parameterized/legacy sequence from the start
|
||||
// of the buffer and return both the parsed Key and the number of characters
|
||||
// consumed. This enables peel-and-continue parsing for batched input.
|
||||
const parseKittyPrefix = (
|
||||
buffer: string,
|
||||
): { key: Key; length: number } | null => {
|
||||
/**
|
||||
* Parses a single complete kitty/parameterized/legacy sequence from the start
|
||||
* of the buffer.
|
||||
*
|
||||
* This enables peel-and-continue parsing for batched input, allowing us to
|
||||
* "peel off" one complete event when multiple sequences arrive in a single
|
||||
* chunk, preventing buffer overflow and fragmentation.
|
||||
*
|
||||
* @param buffer - The input buffer string to parse.
|
||||
* @returns The parsed Key and the number of characters consumed, or null if
|
||||
* no complete sequence is found at the start of the buffer.
|
||||
*/
|
||||
function parseKittyPrefix(buffer: string): { key: Key; length: number } | null {
|
||||
// In older terminals ESC [ Z was used as Cursor Backward Tabulation (CBT)
|
||||
// In newer terminals the same functionality of key combination for moving
|
||||
// backward through focusable elements is Shift+Tab, hence we will
|
||||
@@ -317,8 +229,7 @@ export function KeypressProvider({
|
||||
modifiers -= KITTY_MODIFIER_EVENT_TYPES_OFFSET;
|
||||
}
|
||||
const modifierBits = modifiers - KITTY_MODIFIER_BASE;
|
||||
const shift =
|
||||
(modifierBits & MODIFIER_SHIFT_BIT) === MODIFIER_SHIFT_BIT;
|
||||
const shift = (modifierBits & MODIFIER_SHIFT_BIT) === MODIFIER_SHIFT_BIT;
|
||||
const alt = (modifierBits & MODIFIER_ALT_BIT) === MODIFIER_ALT_BIT;
|
||||
const ctrl = (modifierBits & MODIFIER_CTRL_BIT) === MODIFIER_CTRL_BIT;
|
||||
const terminator = m[4];
|
||||
@@ -440,11 +351,107 @@ export function KeypressProvider({
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
const broadcast = (key: Key) => {
|
||||
for (const handler of subscribers) {
|
||||
handler(key);
|
||||
export interface Key {
|
||||
name: string;
|
||||
ctrl: boolean;
|
||||
meta: boolean;
|
||||
shift: boolean;
|
||||
paste: boolean;
|
||||
sequence: string;
|
||||
kittyProtocol?: boolean;
|
||||
}
|
||||
|
||||
export type KeypressHandler = (key: Key) => void;
|
||||
|
||||
interface KeypressContextValue {
|
||||
subscribe: (handler: KeypressHandler) => void;
|
||||
unsubscribe: (handler: KeypressHandler) => void;
|
||||
}
|
||||
|
||||
const KeypressContext = createContext<KeypressContextValue | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
export function useKeypressContext() {
|
||||
const context = useContext(KeypressContext);
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
'useKeypressContext must be used within a KeypressProvider',
|
||||
);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the passthrough stream workaround should be used.
|
||||
* This is necessary for Node.js versions older than 20 or when the
|
||||
* PASTE_WORKAROUND environment variable is set, to correctly handle
|
||||
* paste events.
|
||||
*/
|
||||
function shouldUsePassthrough(): boolean {
|
||||
const nodeMajorVersion = parseInt(process.versions.node.split('.')[0], 10);
|
||||
return (
|
||||
nodeMajorVersion < 20 ||
|
||||
process.env['PASTE_WORKAROUND'] === '1' ||
|
||||
process.env['PASTE_WORKAROUND'] === 'true'
|
||||
);
|
||||
}
|
||||
|
||||
export function KeypressProvider({
|
||||
children,
|
||||
kittyProtocolEnabled,
|
||||
config,
|
||||
debugKeystrokeLogging,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
kittyProtocolEnabled: boolean;
|
||||
config?: Config;
|
||||
debugKeystrokeLogging?: boolean;
|
||||
}) {
|
||||
const { stdin, setRawMode } = useStdin();
|
||||
|
||||
const subscribers = useRef<Set<KeypressHandler>>(new Set()).current;
|
||||
const subscribe = useCallback(
|
||||
(handler: KeypressHandler) => subscribers.add(handler),
|
||||
[subscribers],
|
||||
);
|
||||
const unsubscribe = useCallback(
|
||||
(handler: KeypressHandler) => subscribers.delete(handler),
|
||||
[subscribers],
|
||||
);
|
||||
const broadcast = useCallback(
|
||||
(key: Key) => subscribers.forEach((handler) => handler(key)),
|
||||
[subscribers],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const wasRaw = stdin.isRaw;
|
||||
if (wasRaw === false) {
|
||||
setRawMode(true);
|
||||
}
|
||||
|
||||
const keypressStream = shouldUsePassthrough() ? new PassThrough() : null;
|
||||
|
||||
// If non-null that means we are in paste mode
|
||||
let pasteBuffer: Buffer | null = null;
|
||||
|
||||
// Used to turn "\" quickly followed by a "enter" into a shift enter
|
||||
let backslashTimeout: NodeJS.Timeout | null = null;
|
||||
|
||||
// Buffers incomplete Kitty sequences and timer to flush it
|
||||
let kittySequenceBuffer = '';
|
||||
let kittySequenceTimeout: NodeJS.Timeout | null = null;
|
||||
|
||||
// Used to detect filename drag-and-drops.
|
||||
let dragBuffer = '';
|
||||
let draggingTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
const clearDraggingTimer = () => {
|
||||
if (draggingTimer) {
|
||||
clearTimeout(draggingTimer);
|
||||
draggingTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -479,11 +486,11 @@ export function KeypressProvider({
|
||||
}
|
||||
if (key.name === 'paste-start') {
|
||||
flushKittyBufferOnInterrupt('paste start');
|
||||
isPaste = true;
|
||||
pasteBuffer = Buffer.alloc(0);
|
||||
return;
|
||||
}
|
||||
if (key.name === 'paste-end') {
|
||||
isPaste = false;
|
||||
if (pasteBuffer !== null) {
|
||||
broadcast({
|
||||
name: '',
|
||||
ctrl: false,
|
||||
@@ -492,11 +499,12 @@ export function KeypressProvider({
|
||||
paste: true,
|
||||
sequence: pasteBuffer.toString(),
|
||||
});
|
||||
pasteBuffer = Buffer.alloc(0);
|
||||
}
|
||||
pasteBuffer = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isPaste) {
|
||||
if (pasteBuffer !== null) {
|
||||
pasteBuffer = Buffer.concat([pasteBuffer, Buffer.from(key.sequence)]);
|
||||
return;
|
||||
}
|
||||
@@ -504,16 +512,15 @@ export function KeypressProvider({
|
||||
if (
|
||||
key.sequence === SINGLE_QUOTE ||
|
||||
key.sequence === DOUBLE_QUOTE ||
|
||||
isDraggingRef.current
|
||||
draggingTimer !== null
|
||||
) {
|
||||
isDraggingRef.current = true;
|
||||
dragBufferRef.current += key.sequence;
|
||||
dragBuffer += key.sequence;
|
||||
|
||||
clearDraggingTimer();
|
||||
draggingTimerRef.current = setTimeout(() => {
|
||||
isDraggingRef.current = false;
|
||||
const seq = dragBufferRef.current;
|
||||
dragBufferRef.current = '';
|
||||
draggingTimer = setTimeout(() => {
|
||||
draggingTimer = null;
|
||||
const seq = dragBuffer;
|
||||
dragBuffer = '';
|
||||
if (seq) {
|
||||
broadcast({ ...key, name: '', paste: true, sequence: seq });
|
||||
}
|
||||
@@ -529,18 +536,15 @@ export function KeypressProvider({
|
||||
ctrl: false,
|
||||
meta: true,
|
||||
shift: false,
|
||||
paste: isPaste,
|
||||
paste: pasteBuffer !== null,
|
||||
sequence: key.sequence,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.name === 'return' && waitingForEnterAfterBackslash) {
|
||||
if (backslashTimeout) {
|
||||
if (key.name === 'return' && backslashTimeout !== null) {
|
||||
clearTimeout(backslashTimeout);
|
||||
backslashTimeout = null;
|
||||
}
|
||||
waitingForEnterAfterBackslash = false;
|
||||
broadcast({
|
||||
...key,
|
||||
shift: true,
|
||||
@@ -551,21 +555,16 @@ export function KeypressProvider({
|
||||
|
||||
if (key.sequence === '\\' && !key.name) {
|
||||
// Corrected escaping for backslash
|
||||
waitingForEnterAfterBackslash = true;
|
||||
backslashTimeout = setTimeout(() => {
|
||||
waitingForEnterAfterBackslash = false;
|
||||
backslashTimeout = null;
|
||||
broadcast(key);
|
||||
}, BACKSLASH_ENTER_DETECTION_WINDOW_MS);
|
||||
return;
|
||||
}
|
||||
|
||||
if (waitingForEnterAfterBackslash && key.name !== 'return') {
|
||||
if (backslashTimeout) {
|
||||
if (backslashTimeout !== null && key.name !== 'return') {
|
||||
clearTimeout(backslashTimeout);
|
||||
backslashTimeout = null;
|
||||
}
|
||||
waitingForEnterAfterBackslash = false;
|
||||
broadcast({
|
||||
name: '',
|
||||
sequence: '\\',
|
||||
@@ -764,7 +763,7 @@ export function KeypressProvider({
|
||||
if (key.name === 'return' && key.sequence === `${ESC}\r`) {
|
||||
key.meta = true;
|
||||
}
|
||||
broadcast({ ...key, paste: isPaste });
|
||||
broadcast({ ...key, paste: pasteBuffer !== null });
|
||||
};
|
||||
|
||||
const handleRawKeypress = (data: Buffer) => {
|
||||
@@ -791,13 +790,13 @@ export function KeypressProvider({
|
||||
markerLength = pasteModeSuffixBuffer.length;
|
||||
|
||||
if (nextMarkerPos === -1) {
|
||||
keypressStream.write(data.slice(pos));
|
||||
keypressStream!.write(data.slice(pos));
|
||||
return;
|
||||
}
|
||||
|
||||
const nextData = data.slice(pos, nextMarkerPos);
|
||||
if (nextData.length > 0) {
|
||||
keypressStream.write(nextData);
|
||||
keypressStream!.write(nextData);
|
||||
}
|
||||
const createPasteKeyEvent = (
|
||||
name: 'paste-start' | 'paste-end',
|
||||
@@ -819,7 +818,7 @@ export function KeypressProvider({
|
||||
};
|
||||
|
||||
let rl: readline.Interface;
|
||||
if (usePassthrough) {
|
||||
if (keypressStream !== null) {
|
||||
rl = readline.createInterface({
|
||||
input: keypressStream,
|
||||
escapeCodeTimeout: 0,
|
||||
@@ -834,7 +833,7 @@ export function KeypressProvider({
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (usePassthrough) {
|
||||
if (keypressStream !== null) {
|
||||
keypressStream.removeListener('keypress', handleKeypress);
|
||||
stdin.removeListener('data', handleRawKeypress);
|
||||
} else {
|
||||
@@ -872,7 +871,7 @@ export function KeypressProvider({
|
||||
}
|
||||
|
||||
// Flush any pending paste data to avoid data loss on exit.
|
||||
if (isPaste) {
|
||||
if (pasteBuffer !== null) {
|
||||
broadcast({
|
||||
name: '',
|
||||
ctrl: false,
|
||||
@@ -881,24 +880,20 @@ export function KeypressProvider({
|
||||
paste: true,
|
||||
sequence: pasteBuffer.toString(),
|
||||
});
|
||||
pasteBuffer = Buffer.alloc(0);
|
||||
pasteBuffer = null;
|
||||
}
|
||||
|
||||
if (draggingTimerRef.current) {
|
||||
clearTimeout(draggingTimerRef.current);
|
||||
draggingTimerRef.current = null;
|
||||
}
|
||||
if (isDraggingRef.current && dragBufferRef.current) {
|
||||
clearDraggingTimer();
|
||||
if (dragBuffer) {
|
||||
broadcast({
|
||||
name: '',
|
||||
ctrl: false,
|
||||
meta: false,
|
||||
shift: false,
|
||||
paste: true,
|
||||
sequence: dragBufferRef.current,
|
||||
sequence: dragBuffer,
|
||||
});
|
||||
isDraggingRef.current = false;
|
||||
dragBufferRef.current = '';
|
||||
dragBuffer = '';
|
||||
}
|
||||
};
|
||||
}, [
|
||||
@@ -906,8 +901,8 @@ export function KeypressProvider({
|
||||
setRawMode,
|
||||
kittyProtocolEnabled,
|
||||
config,
|
||||
subscribers,
|
||||
debugKeystrokeLogging,
|
||||
broadcast,
|
||||
]);
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user