Skip to content

Instantly share code, notes, and snippets.

@cjfff
Created October 8, 2021 06:48
Show Gist options
  • Save cjfff/60c2d2c4111f5866277001dda24b6fde to your computer and use it in GitHub Desktop.
Save cjfff/60c2d2c4111f5866277001dda24b6fde to your computer and use it in GitHub Desktop.
a extention of the inquirer
// eslint-disable-next-line @typescript-eslint/no-var-requires
const chalk = require('chalk')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const ConfirmPrompt = require('inquirer/lib/prompts/confirm')
class TimeoutConfirmPrompt extends ConfirmPrompt {
constructor(...args) {
super(...args)
this.opt.timeoutTips = this.opt.timeoutTips || ((t) => `(${t}s)`)
this.opt.timeout = this.opt.timeout || 10
}
_run(cb) {
this.timeout = this.opt.timeout
const timerId = setInterval(() => {
this.timeout -= 1
if (this.timeout === 0) {
clearInterval(timerId)
this.onEnd(this.opt.default === 'Y/n' ? 'Yes' : 'No')
} else {
this.render()
}
}, 1000)
/* eslint-disable-next-line */
return super._run((...args) => {
clearInterval(timerId)
return cb(...args)
})
}
render(answer?: string) {
let message = this.getQuestion()
if (this.timeout !== 0 && answer === undefined) {
message += this.opt.timeoutTips(this.timeout)
}
if (typeof answer === 'boolean') {
message += chalk.cyan(answer ? 'Yes' : 'No')
} else {
message += this.rl.line
}
this.screen.render(message)
return this
}
}
export default TimeoutConfirmPrompt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment