import { terminal as term } from 'terminal-kit' ; import { Messenger , MessageEvent , Verification } from '../Messenger' ; import { stationToCallsignSSID , isCallsign , isCallsignSSID } from '../utils' ; term . on ( 'key' , ( name , matches , data ) : void => { if ( matches . includes ( 'CTRL_C' ) || matches . includes ( 'CTRL_D' ) ) { exit ( 0 ) ; } } ) ; type TerminalFunction = ( buffer : string ) => TerminalFunction ; const colorMap = { } ; const myColorFunction = term . cyan ; function getColorFunction ( callsign ) { const choices = [ term . red , term . green , term . yellow , term . blue , term . magenta , term . brightRed , term . brightGreen , term . brightYellow , term . brightBlue , term . brightMagenta ] ; if ( ! colorMap . hasOwnProperty ( callsign ) ) { colorMap [ callsign ] = choices [ Math . floor ( Math . random ( ) * choices . length ) ] ; } return colorMap [ callsign ] ; } export function enter ( ) { term . fullscreen ( ) ; } export function exit ( code ) { term . processExit ( code ) ; } export async function printReceivedMessage ( message , callsign ) { const pos = await term . getCursorLocation ( ) ; if ( pos ) { term . moveTo ( 0 , pos . y ) ; term . insertLine ( 1 ) ; printStyledText ( message ) ; term . move ( pos . x - 1 , 0 ) ; if ( term . height === pos . y ) { if ( input ) { term . moveTo ( 0 , term . height ) ; myColorFunction ( `${ callsign }` ) ( ': ' ) ; input . redraw ( ) ; } } } } export async function inputLoop ( callsign , messenger , sign ) { while ( true ) { const text = ( await prompt ( callsign ) ) . trim ( ) ; if ( text !== '' ) { let to = 'CQ' ; if ( text . startsWith ( '@' ) ) { const space = text . indexOf ( ' ' ) ; const callsign = space === - 1 ? text . slice ( 1 ) : text . slice ( 1 , space ) ; if ( isCallsign ( callsign ) || isCallsignSSID ( callsign ) ) to = callsign . toUpperCase ( ) ; } await messenger . send ( to , text , sign ) ; } term . eraseLine ( ) ; const pos = await term . getCursorLocation ( ) ; term . moveTo ( 0 , pos . y ) ; myColorFunction ( `${ callsign }` ) ( `: ${ text }` ) ; } } let input ; async function prompt ( callsign ) { myColorFunction ( `\n${ callsign }` ) ( ': ' ) ; input = term . inputField ( { cancelable : true } ) ; const message = await input . promise ; return message ; } function printStyledText ( message ) { const from = stationToCallsignSSID ( message . from ) ; getColorFunction ( from ) ( `${ from }` ) ; switch ( message . verification ) { case Verification . NotSigned : term ( ' (UNSIGNED): ' ) . dim ( `${ message . message }` ) ; break ; case Verification . Valid : term ( `: ${ message . message }` ) ; break ; case Verification . Invalid : term ( ' (INVALID SIGNATURE): ' ) . strike ( `${ message . message }` ) ; break ; case Verification . KeyNotFound : term ( ' (KEY NOT FOUND): ' ) . underline ( `${ message . message }` ) ; break ; } term ( '\n' ) ; }