github.com/hernad/nomad@v1.6.112/ui/app/utils/classes/exec-command-editor-xterm-adapter.js (about) 1 /** 2 * Copyright (c) HashiCorp, Inc. 3 * SPDX-License-Identifier: MPL-2.0 4 */ 5 6 import KEYS from 'nomad-ui/utils/keys'; 7 8 const REVERSE_WRAPAROUND_MODE = '\x1b[?45h'; 9 const BACKSPACE_ONE_CHARACTER = '\x08 \x08'; 10 11 // eslint-disable-next-line no-control-regex 12 const UNPRINTABLE_CHARACTERS_REGEX = /[\x00-\x1F]/g; 13 14 export default class ExecCommandEditorXtermAdapter { 15 constructor(terminal, setCommandCallback, command) { 16 this.terminal = terminal; 17 this.setCommandCallback = setCommandCallback; 18 19 this.command = command; 20 21 this.dataListener = terminal.onData((data) => { 22 this.handleDataEvent(data); 23 }); 24 25 // Allows tests to bypass synthetic keyboard event restrictions 26 terminal.simulateCommandDataEvent = this.handleDataEvent.bind(this); 27 28 terminal.write(REVERSE_WRAPAROUND_MODE); 29 } 30 31 handleDataEvent(data) { 32 if ( 33 data === KEYS.LEFT_ARROW || 34 data === KEYS.UP_ARROW || 35 data === KEYS.RIGHT_ARROW || 36 data === KEYS.DOWN_ARROW 37 ) { 38 // Ignore arrow keys 39 } else if (data === KEYS.CONTROL_U) { 40 this.terminal.write(BACKSPACE_ONE_CHARACTER.repeat(this.command.length)); 41 this.command = ''; 42 } else if (data === KEYS.ENTER) { 43 this.terminal.writeln(''); 44 this.setCommandCallback(this.command); 45 this.dataListener.dispose(); 46 } else if (data === KEYS.DELETE) { 47 if (this.command.length > 0) { 48 this.terminal.write(BACKSPACE_ONE_CHARACTER); 49 this.command = this.command.slice(0, -1); 50 } 51 } else if (data.length > 0) { 52 const strippedData = data.replace(UNPRINTABLE_CHARACTERS_REGEX, ''); 53 this.terminal.write(strippedData); 54 this.command = `${this.command}${strippedData}`; 55 } 56 } 57 58 destroy() { 59 this.dataListener.dispose(); 60 } 61 }