Skip to content

Commit

Permalink
Fix(@inquirer/core): Delay showing any loader by 300ms to avoid spinn…
Browse files Browse the repository at this point in the history
…er flickering. Ref #1407
  • Loading branch information
SBoudrias committed Jun 19, 2024
1 parent c7583fc commit 47cbb40
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
4 changes: 4 additions & 0 deletions packages/core/core.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ describe('createPrompt()', () => {

it('usePrefix() renders loader and prefix', async () => {
vi.useFakeTimers();
const delay = 300;
const { interval } = spinners.dots;
const totalDuration = interval * spinners.dots.frames.length;

Expand Down Expand Up @@ -390,6 +391,9 @@ describe('createPrompt()', () => {

const prompt = createPrompt(Prompt);
const { answer, events, getScreen } = await render(prompt, { message: 'Question' });
expect(getScreen()).toMatchInlineSnapshot(`"? Question"`);

vi.advanceTimersByTime(delay + interval);
expect(getScreen()).toMatchInlineSnapshot(`"⠋ Question"`);

vi.advanceTimersByTime(interval);
Expand Down
11 changes: 8 additions & 3 deletions packages/core/src/lib/use-prefix.mts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export function usePrefix({
isLoading?: boolean;
theme?: Theme;
}): string {
const [showLoader, setShowLoader] = useState(false);
const [tick, setTick] = useState(0);
const { prefix, spinner } = makeTheme(theme);

Expand All @@ -19,24 +20,28 @@ export function usePrefix({
let tickInterval: NodeJS.Timeout | undefined;
let inc = -1;
// Delay displaying spinner by 300ms, to avoid flickering
const delayTimeout = setTimeout(() => {
const delayTimeout = setTimeout(AsyncResource.bind(() => {
setShowLoader(true);

tickInterval = setInterval(
AsyncResource.bind(() => {
inc = inc + 1;
setTick(inc % spinner.frames.length);
}),
spinner.interval,
);
}, 300);
}), 300);

return () => {
clearTimeout(delayTimeout);
clearInterval(tickInterval);
};
} else {
setShowLoader(false);
}
}, [isLoading]);

if (isLoading) {
if (showLoader) {
return spinner.frames[tick]!;
}

Expand Down

0 comments on commit 47cbb40

Please sign in to comment.