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

20.83% Statements 5/24
25% Branches 4/16
28.57% Functions 2/7
20.83% Lines 5/24

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 67                                            4x 4x                                                             5x 2x   3x                  
import { isAbortError } from '@be-music/shared-utils/core';
import readline from 'node:readline';
import { beginSharedRawInputCapture } from '../raw-input-capture.ts';
 
export interface RawInputCapture {
  stdin: NodeJS.ReadStream & { isRaw?: boolean };
  restore: () => void;
}
 
type LoadingCancelReason = 'escape' | 'ctrl-c';
 
interface LoadingAbortCapture {
  signal: AbortSignal;
  getReason: () => LoadingCancelReason | undefined;
  dispose: () => void;
}
 
export function beginRawInputCapture(): RawInputCapture {
  return beginSharedRawInputCapture();
}
 
export function beginLoadingAbortCapture(): LoadingAbortCapture | undefined {
  Eif (!process.stdin.isTTY || !process.stdout.isTTY) {
    return undefined;
  }
  const inputCapture = beginRawInputCapture();
  const controller = new AbortController();
  let reason: LoadingCancelReason | undefined;
  const onKeyPress = (_chunk: string | undefined, key: readline.Key): void => {
    if (key.sequence === '\u0003') {
      reason = 'ctrl-c';
      controller.abort();
      return;
    }
    if (key.name?.toLowerCase() === 'escape' || key.sequence === '\u001b') {
      reason = 'escape';
      controller.abort();
    }
  };
  inputCapture.stdin.on('keypress', onKeyPress);
  return {
    signal: controller.signal,
    getReason: () => reason,
    dispose: () => {
      inputCapture.stdin.removeListener('keypress', onKeyPress);
      inputCapture.restore();
    },
  };
}
 
export function resolveLoadingCancelReason(
  error: unknown,
  capture: LoadingAbortCapture | undefined,
): LoadingCancelReason | undefined {
  if (!isAbortError(error)) {
    return undefined;
  }
  return capture?.getReason();
}
 
export function applyLoadingCancel(reason: LoadingCancelReason): void {
  process.exitCode = reason === 'ctrl-c' ? 130 : 0;
  if (process.stdout.isTTY) {
    process.stdout.write('\u001b[2J\u001b[H');
  }
}