36 lines
764 B
TypeScript
36 lines
764 B
TypeScript
|
|
import * as readline from 'node:readline'
|
||
|
|
import {BehaviorSubject} from "../util/subject.js";
|
||
|
|
import {Lifecycle, LifecycleAware} from "../util/lifecycle.js";
|
||
|
|
|
||
|
|
export class Input extends BehaviorSubject<string> implements LifecycleAware {
|
||
|
|
private rl?: readline.Interface
|
||
|
|
|
||
|
|
public setupPrompt(): void {
|
||
|
|
if ( this.rl ) {
|
||
|
|
this.closePrompt()
|
||
|
|
}
|
||
|
|
|
||
|
|
this.rl = readline.createInterface({
|
||
|
|
input: process.stdin,
|
||
|
|
output: process.stdout,
|
||
|
|
prompt: 'str %> ',
|
||
|
|
})
|
||
|
|
|
||
|
|
this.rl.prompt()
|
||
|
|
|
||
|
|
this.rl.on('line', async (line) => {
|
||
|
|
await this.next(line + '\n')
|
||
|
|
this.rl?.prompt(true)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
public closePrompt(): void {
|
||
|
|
this.rl?.close()
|
||
|
|
this.rl = undefined
|
||
|
|
}
|
||
|
|
|
||
|
|
adoptLifecycle(lifecycle: Lifecycle): void {
|
||
|
|
lifecycle.onClose(() => this.closePrompt())
|
||
|
|
}
|
||
|
|
}
|