[READ-ONLY] Mirror of https://github.com/bombshell-dev/clack. Effortlessly build beautiful command-line apps bomb.sh/docs/clack/basics/getting-started/
cli command-line command-line-app node prompt prompts
5

Configure Feed

Select the types of activity you want to include in your feed.

cancel timeout if validation finishes

Oskar Löfgren (Mar 8, 2023, 12:00 AM +0100) 19a19035 68abb814

+31 -10
+31 -10
packages/core/src/prompts/prompt.ts
··· 4 4 import readline from 'node:readline'; 5 5 import { Readable, Writable } from 'node:stream'; 6 6 import { WriteStream } from 'node:tty'; 7 - import { setTimeout } from 'node:timers/promises'; 8 7 import { cursor, erase } from 'sisteransi'; 9 8 import wrap from 'wrap-ansi'; 9 + 10 + const VALIDATION_STATE_DELAY = 400; 10 11 11 12 function diffLines(a: string, b: string) { 12 13 if (a === b) return; ··· 20 21 } 21 22 22 23 return diff; 24 + } 25 + 26 + function raceTimeout<Value>( 27 + promise: Promise<Value>, 28 + { onTimeout, delay }: { onTimeout(): void; delay: number } 29 + ) { 30 + let timer: NodeJS.Timeout; 31 + 32 + return Promise.race([ 33 + new Promise<void>((resolve) => { 34 + timer = setTimeout(() => { 35 + onTimeout(); 36 + resolve(); 37 + }, delay); 38 + }), 39 + promise.then((value) => { 40 + clearTimeout(timer); 41 + return value; 42 + }), 43 + ]); 23 44 } 24 45 25 46 const cancel = Symbol('clack:cancel'); ··· 178 199 if (key?.name === 'return') { 179 200 if (this.opts.validate) { 180 201 this.state = 'validate'; 181 - let problem = this.opts.validate(this.value); 182 - // Only trigger validation state after 300ms. 183 - // If problem resolves first, render will be cancelled. 184 - await Promise.race([ 185 - problem, 186 - setTimeout(300).then(() => { 202 + const validation = Promise.resolve(this.opts.validate(this.value)); 203 + // Delay rendering of validation state. 204 + // If validation resolves first, render will be cancelled. 205 + await raceTimeout(validation, { 206 + onTimeout: () => { 187 207 this.render(); 188 - }), 189 - ]); 190 - problem = await problem; 208 + }, 209 + delay: VALIDATION_STATE_DELAY, 210 + }); 211 + const problem = await validation; 191 212 if (problem) { 192 213 this.error = problem; 193 214 this.state = 'error';