Skip to content

Commit

Permalink
Fix frame handling
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Nov 1, 2024
1 parent 5117dfb commit 818ca34
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
14 changes: 11 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ class Ora {
#linesToClear = 0;
#isDiscardingStdin = false;
#lineCount = 0;
#frameIndex = 0;
#frameIndex = -1;
#lastSpinnerFrameTime = 0;
#options;
#spinner;
#stream;
Expand Down Expand Up @@ -109,7 +110,7 @@ class Ora {
}

set spinner(spinner) {
this.#frameIndex = 0;
this.#frameIndex = -1;
this.#initialInterval = undefined;

if (typeof spinner === 'object') {
Expand Down Expand Up @@ -222,14 +223,21 @@ class Ora {
}

frame() {
// Ensure we only update the spinner frame at the wanted interval,
// even if the render method is called more often.
const now = Date.now();
if (this.#frameIndex === -1 || now - this.#lastSpinnerFrameTime >= this.interval) {
this.#frameIndex = ++this.#frameIndex % this.#spinner.frames.length;
this.#lastSpinnerFrameTime = now;
}

const {frames} = this.#spinner;
let frame = frames[this.#frameIndex];

if (this.color) {
frame = chalk[this.color](frame);
}

this.#frameIndex = ++this.#frameIndex % frames.length;
const fullPrefixText = (typeof this.#prefixText === 'string' && this.#prefixText !== '') ? this.#prefixText + ' ' : '';
const fullText = typeof this.text === 'string' ? ' ' + this.text : '';
const fullSuffixText = (typeof this.#suffixText === 'string' && this.#suffixText !== '') ? ' ' + this.#suffixText : '';
Expand Down
4 changes: 3 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,10 @@ test('reset frameIndex when setting new spinner', async t => {
},
});

t.is(spinner._frameIndex, -1);

spinner.render();
t.is(spinner._frameIndex, 1);
t.is(spinner._frameIndex, 0);

spinner.spinner = {frames: ['baz']};
spinner.render();
Expand Down

0 comments on commit 818ca34

Please sign in to comment.