All files / player-terminal/src raw-input-capture.ts

84% Statements 21/25
80% Branches 12/15
66.66% Functions 2/3
84% Lines 21/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 57 58 59 60 61 62 63 64 65 66                                        16x 16x             16x 15x         15x 15x 2x   15x 15x     16x 16x   16x     16x     16x 16x 16x     16x 16x 1x   15x 15x        
import readline from 'node:readline';
 
export interface RawInputCapture {
  stdin: NodeJS.ReadStream & { isRaw?: boolean };
  restore: () => void;
}
 
interface SharedRawInputCaptureState {
  stdin: NodeJS.ReadStream & { isRaw?: boolean };
  wasRawMode: boolean;
  refCount: number;
}
 
let sharedRawInputCaptureState: SharedRawInputCaptureState | undefined;
 
export function beginSharedRawInputCapture(
  options: {
    forceResetRawMode?: boolean;
  } = {},
): RawInputCapture {
  const stdin = process.stdin as NodeJS.ReadStream & { isRaw?: boolean };
  Iif (!stdin.isTTY) {
    return {
      stdin,
      restore: () => undefined,
    };
  }
 
  if (!sharedRawInputCaptureState) {
    sharedRawInputCaptureState = {
      stdin,
      wasRawMode: Boolean(stdin.isRaw),
      refCount: 0,
    };
    readline.emitKeypressEvents(process.stdin);
    if (options.forceResetRawMode && stdin.isRaw) {
      stdin.setRawMode(false);
    }
    stdin.setRawMode(true);
    stdin.resume();
  }
 
  sharedRawInputCaptureState.refCount += 1;
  let restored = false;
 
  return {
    stdin,
    restore: () => {
      Iif (restored) {
        return;
      }
      restored = true;
      const activeState = sharedRawInputCaptureState;
      Iif (!activeState) {
        return;
      }
      activeState.refCount -= 1;
      if (activeState.refCount > 0) {
        return;
      }
      activeState.stdin.setRawMode(activeState.wasRawMode);
      sharedRawInputCaptureState = undefined;
    },
  };
}