All files / src index.tsx

67.34% Statements 66/98
46% Branches 23/50
75% Functions 9/12
60% Lines 42/70

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 1391x                 1x 1x 1x 1x   1x 1x 1x                                 16x 16x 16x   16x   16x 1x         16x                           16x           16x 1x     1x 1x 1x 1x 1x                                             16x 11x       16x 11x 4x     7x 7x 7x 7x 7x   7x 7x 7x         16x 16x 1x   16x                         1x 1x  
import React, {
  useState,
  useEffect,
  useRef,
  KeyboardEvent,
  ChangeEvent,
  ReactNode,
  ReactElement
} from 'react';
import TerminalInput from './linetypes/TerminalInput';
import TerminalOutput from './linetypes/TerminalOutput';
import './style.css';
import {IWindowButtonsProps, WindowButtons} from "./ui-elements/WindowButtons";
 
export enum ColorMode {
  Light,
  Dark
}
 
export interface Props {
  name?: string;
  prompt?: string;
  height?: string;
  colorMode?: ColorMode;
  children?: ReactNode;
  onInput?: ((input: string) => void) | null | undefined;
  startingInputValue?: string;
  redBtnCallback?: () => void;
  yellowBtnCallback?: () => void;
  greenBtnCallback?: () => void;
  TopButtonsPanel?: (props: IWindowButtonsProps) => ReactElement | null;
}
 
const Terminal = ({name, prompt, height = "600px", colorMode, onInput, children, startingInputValue = "", redBtnCallback, yellowBtnCallback, greenBtnCallback, TopButtonsPanel = WindowButtons}: Props) => {
  const [currentLineInput, setCurrentLineInput] = useState('');
  const [cursorPos, setCursorPos] = useState(0);
 
  const scrollIntoViewRef = useRef<HTMLDivElement>(null)
 
  const updateCurrentLineInput = (event: ChangeEvent<HTMLInputElement>) => {
    setCurrentLineInput(event.target.value);
  }
 
  // Calculates the total width in pixels of the characters to the right of the cursor.
  // Create a temporary span element to measure the width of the characters.
  const calculateInputWidth = (inputElement: HTMLInputElement, chars: string) => {
    const span = document.createElement('span');
    span.style.visibility = 'hidden';
    span.style.position = 'absolute';
    span.style.fontSize = window.getComputedStyle(inputElement).fontSize;
    span.style.fontFamily = window.getComputedStyle(inputElement).fontFamily;
    span.innerText = chars;
    document.body.appendChild(span);
    const width = span.getBoundingClientRect().width;
    document.body.removeChild(span);
    // Return the negative width, since the cursor position is to the left of the input suffix
    return -width;
  };
 
  const clamp = (value: number, min: number, max: number) => {
    Iif(value > max) return max;
    Iif(value < min) return min;
    return value;
  }
 
  const handleInputKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    Iif(!onInput) {
      return;
    };
    if (event.key === 'Enter') {
      onInput(currentLineInput);
      setCursorPos(0);
      setCurrentLineInput('');
      setTimeout(() => scrollIntoViewRef?.current?.scrollIntoView({ behavior: "auto", block: "nearest" }), 500);
    } else IEif (["ArrowLeft", "ArrowRight", "ArrowDown", "ArrowUp", "Delete"].includes(event.key)) { 
      const inputElement = event.currentTarget;
      let charsToRightOfCursor = "";
      let cursorIndex = currentLineInput.length - (inputElement.selectionStart || 0);
      cursorIndex = clamp(cursorIndex, 0, currentLineInput.length);
 
      if(event.key === 'ArrowLeft') {
        Iif(cursorIndex > currentLineInput.length - 1) cursorIndex --;
        charsToRightOfCursor = currentLineInput.slice(currentLineInput.length -1 - cursorIndex);
      }
      else if (event.key === 'ArrowRight' || event.key === 'Delete') {
        charsToRightOfCursor = currentLineInput.slice(currentLineInput.length - cursorIndex + 1);
      }
      else Iif (event.key === 'ArrowUp') {
        charsToRightOfCursor = currentLineInput.slice(0)
      }
 
      const inputWidth = calculateInputWidth(inputElement, charsToRightOfCursor);
      setCursorPos(inputWidth);
    }
  }
 
  useEffect(() => {
    setCurrentLineInput(startingInputValue.trim());
  }, [startingInputValue]);
 
  // We use a hidden input to capture terminal input; make sure the hidden input is focused when clicking anywhere on the terminal
  useEffect(() => {
    if (onInput == null) {
      return;
    }
    // keep reference to listeners so we can perform cleanup
    const elListeners: { terminalEl: Element; listener: EventListenerOrEventListenerObject }[] = [];
    for (const terminalEl of document.getElementsByClassName('react-terminal-wrapper')) {
      const listener = () => (terminalEl?.querySelector('.terminal-hidden-input') as HTMLElement)?.focus();
      terminalEl?.addEventListener('click', listener);
      elListeners.push({ terminalEl, listener });
    }
    return function cleanup () {
      elListeners.forEach(elListener => {
        elListener.terminalEl.removeEventListener('click', elListener.listener);
      });
    }
  }, [onInput]);
 
  const classes = ['react-terminal-wrapper'];
  if (colorMode === ColorMode.Light) {
    classes.push('react-terminal-light');
  }
  return (
    <div className={ classes.join(' ') } data-terminal-name={ name }>
      <TopButtonsPanel {...{redBtnCallback, yellowBtnCallback, greenBtnCallback}}/>
      <div className="react-terminal" style={ { height } }>
        { children }
        { typeof onInput === 'function' && <div className="react-terminal-line react-terminal-input react-terminal-active-input" data-terminal-prompt={ prompt || '$' } key="terminal-line-prompt" >{ currentLineInput }<span className="cursor" style={{ left: `${cursorPos+1}px` }}></span></div> }
        <div ref={ scrollIntoViewRef }></div>
      </div>
      <input className="terminal-hidden-input" placeholder="Terminal Hidden Input" value={ currentLineInput } autoFocus={ onInput != null } onChange={ updateCurrentLineInput } onKeyDown={ handleInputKeyDown }/>
    </div>
  );
}
 
export { TerminalInput, TerminalOutput };
export default Terminal;