prompts
prompts copied to clipboard
Auto-select choice by timeout
I have a problem: For my application need to add a timer for a user's ansfer
How can I stop the dialog (promts)? So that it does not intercept the keypress?
My temporary solution (without stopping):
let isPausedAutoSelect = false;
let isStoppedMessageWithTimer = false;
const messageAutoSelect = 'The [Last choice] will be auto-selected in ${count} second(s)';
async function messageWithTimer(count) {
const stream = process.stderr;
if (!stream.isTTY) {
console.log(messageAutoSelect.replace('${count}', count));
await new Promise(resolve => setTimeout(resolve, count * 1000));
return;
}
for(let localCount = count; localCount > 0; localCount -= 1) {
if (isStoppedPromiseMessageWithTimer) {
return;
}
if (isPausedAutoSelect) {
isPausedAutoSelect = false;
localCount = count;
stream.cursorTo(0);
stream.clearLine(1);
}
await new Promise(resolve => setTimeout(resolve, 1000));
if (localCount <= 10) {
stream.cursorTo(0);
stream.write(messageAutoSelect.replace('${count}', localCount));
stream.clearLine(1);
}
}
console.log('');
}
after that
const responseFromUser = prompts(
{
type: 'select',
name: 'value',
message: 'Pick a mode',
choices,
initial: 0,
onState() {
isPausedAutoSelect = true;
},
},
{
onSubmit() {
isStoppedPromiseMessageWithTimer = true;
},
onCancel() {
isStoppedPromiseMessageWithTimer = true;
},
},
);
const responseFromTimeout = lastChoice
? messageWithTimer(15).then(()=>lastChoice)
: new Promise(()=>{});
const response = await Promise.race([responseFromUser, responseFromTimeout]);
// ...
P.s. Inject after init don't work
setTimeout(()=>{
prompts.inject([lastChoice.value]);
}, 1000);