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
| const EventEmitter=require('events') const readline=require('readline') const MuteStream=require('mute-stream') const {fromEvent}=require('rxjs') const ansiEscapes=require('ansi-escapes');
const option={ type:'list', name:'name', message:'select your name', choices:[{ name:'Baran', value:'isMe' },{ name:'张三', value:'他塔' },{ name:'李四', value:'他他' }] }
function Prompt(option){ return new Promise((resolve, reject)=>{ try { const list=new List(option) list.render() list.on('exit',function (answers){ resolve(answers) }) }catch (e){ reject(e) } }) }
class List extends EventEmitter{ constructor(option) { super(); this.message=option.message this.choices=option.choices this.input=process.stdin const ms=new MuteStream(); ms.pipe(process.stdout) this.output=ms this.rl=readline.createInterface({ input:this.input, output:this.output }) this.selected=0; this.height=-10; this.keypress=fromEvent(this.rl.input,'keypress') .forEach(this.onkeypress) this.haveSelected=false; } onkeypress=(keymap)=>{ const key=keymap[1]; switch (key.name){ case 'down': this.selected++; if(this.selected>this.choices.length-1){ this.selected=0 } this.render() break; case 'up': this.selected--; if(this.selected<0){ this.selected=this.choices.length-1 } this.render() break; default: this.haveSelected=true; this.render() this.close() this.emit('exit',this.choices[this.selected]) } } render(){ this.output.unmute(); this.clean() this.output.write(this.getContent()) this.output.mute(); } getContent=()=>{ if(!this.haveSelected){ let title = '\x1B[32m?\x1B[39m \x1B[1m' + this.message + '\x1B[22m\x1B[0m \x1B[0m\x1B[2m(Use arrow keys)\x1B[22m\n'; this.choices.forEach((choice,index)=>{ if(index===this.selected){ if(index===this.choices.length-1){ title+='\x1B[36m> '+choice.name+'\x1B[39m ' }else{ title+='\x1B[36m> '+choice.name+'\x1B[39m \n' } }else{ if(index===this.choices.length-1){ title+=' '+choice.name }else{ title+=' '+choice.name+'\n' } } }) this.height=this.choices.length+1; return title; }else{ const name = this.choices[this.selected].name; let title = '\x1B[32m?\x1B[39m \x1B[1m' + this.message + '\x1B[22m\x1B[0m \x1B[36m' + name + '\x1B[39m\x1B[0m \n'; return title; } } clean(){ const emptyLines=ansiEscapes.eraseLines(this.height) this.output.write(emptyLines) } close(){ this.output.unmute() this.rl.output.end() this.rl.pause() this.rl.close() }
}
Prompt(option) .then(answers=>{ console.log(answers) }) .catch(error=>console.log({error}))
|