deno_std
deno_std copied to clipboard
`@std/cli`: Support multiple spinners at the same time
Currently, if one tries to display multiple spinners at the same time, the spinners "override" each other.
import { Spinner } from "@std/cli";
const spinner1 = new Spinner({
color: "yellow",
message: "Loading..."
});
const spinner2 = new Spinner({
color: "red",
message: "Loading..."
});
const spinner3 = new Spinner({
color: "blue",
message: "Loading..."
});
spinner1.start();
setTimeout(() => {
spinner1.stop();
console.info("Finished loading!");
}, 3_000);
setTimeout(() => {
spinner2.start();
setTimeout(() => {
spinner2.stop();
console.info("Finished loading!");
}, 3_000);
}, 1_000);
setTimeout(() => {
spinner3.start();
setTimeout(() => {
spinner3.stop();
console.info("Finished loading!");
}, 2_000);
}, 4_000);
Running the above code looks like this:
https://github.com/denoland/deno_std/assets/20396367/d5904ab4-5f57-4969-8629-1cf5dfd443f2
Therefore I propose enhancing the existing Spinner class or even adding a new MultiSpinner class to avoid introducing breaking changes, that is able to handle multiple spinners, like so:
import { Spinner } from "@std/cli";
import { ansi } from "@cliffy/ansi";
const activeMultiSpinners = [];
const MultiSpinner = class extends Spinner {
static #updateMultiSpinners = () => {
const runningMultiSpinners = activeMultiSpinners
.filter((multiSpinner) => multiSpinner.running);
for (const [index, multiSpinner] of runningMultiSpinners.entries()) {
if (runningMultiSpinners.length > 1) {
multiSpinner.message = index === runningMultiSpinners.length - 1
? `${multiSpinner.actualMessage}${ansi.cursorUp(index)}`
: `${multiSpinner.actualMessage}${ansi.cursorDown(1)}`;
}
else {
multiSpinner.message = multiSpinner.actualMessage;
}
}
};
actualMessage = "";
running = false;
constructor({
color,
message
} = {}) {
super({
color,
message
});
this.actualMessage = message;
activeMultiSpinners.push(this);
}
start() {
this.running = true;
MultiSpinner.#updateMultiSpinners();
super.start();
}
stop(message) {
this.running = false;
MultiSpinner.#updateMultiSpinners();
super.stop();
}
};
export default MultiSpinner;
Running the example from before with this new MultiSpinner class looks like this:
https://github.com/denoland/deno_std/assets/20396367/2591502e-4dbe-43c1-9cc6-79c0f5ed9daa
Obviously my code was just a quick test to see if this even works, I used @cliffy/ansi to make it simpler, a global activeMultiSpinners array is probably not the way to go and timing might also be buggy (no idea in which order updateMultiSpinners and stop should be called). And I don't even want to know what happens if something like ⏎ is pressed. 😅
But yeah, what do you think about this addition? I personally was a bit surprised it was that easy to augment the base Spinner class, so it might not be that difficult to actually add this, using the same cursorDown(1) and cursorUp(length - 1) logic.
Is this common pattern in cli tool development? I personally don't often see the multiple spinners in cli tools in general.
I also don't see it often, but maybe that's because there is no popular library for this yet? I could only find these two:
- https://github.com/jbcarpanelli/spinnies (last commit 5 years ago)
- https://github.com/codekirei/node-multispinner (last commit 9 years ago)
It's quite common for multiple progress bars (ie docker) and less so for spinners.
Minikube is an example that uses multiple spinners on setup to show a series of async tasks running.
Multiple spinners can be useful for anytime you need to do tasks in parallel, but can't really track individual progress steps.
This is a reasonable expectation for a spinner implementation. SGTM.
Btw, the snippet I shared above is broken in so many ways, so whoever implements this shouldn't take much inspiration from it. It turned out to be a bit more challenging to do this right, especially when trying to support "nested" spinners (s1 starts - s2 starts - s2 stops - s1 stops) or when trying to combine spinners with normal console.log output.
Popular npm packages (ora, cli-spinners) that implement spinners don't support multiple spinners. I'm skeptical the users need this feature.
If we add this feature, I expect the added complexity won't be small. I wonder if it's worth the effort for such rarely used feature.
Minikube is an example that uses multiple spinners on setup to show a series of async tasks running.
Can anybody give more examples of multiple loading indicators in CLI tools? If minikube is only common example, then it feels too rare feature to provide support in the standard library.
Hmm, fair point. This may not be worth the added complexity incurred. I think this is fine as long as we provide justification and possible workarounds in the documentation.
(Sharing another point raised in an offline discussion.)
When there are multiple things going on in CLI tools, I often see the single loading indicator with the message part changing quickly (e.g. npm install shows its progress in this way). I guess that would be more common way to show the progress of multiple things in a terminal app.
Yeah...currently in my project, I went forward with a "single-line" approach as well, to track multiple, especially nested, processes, looking like this:
import { Spinner } from "@std/cli";
/**
* @implements {Spinner}
* @extends {Spinner}
* @example
* const loader = new Loader({
* color: "blue",
* message: "Loading..."
* });
*
* loader.start(); // "Loading..."
*
* await new Promise((resolve) => setTimeout(resolve, 1000));
*
* loader.setBlock("block1", "a"); // "1 | a"
*
* await new Promise((resolve) => setTimeout(resolve, 1000));
*
* loader.setBlock("block1", "b"); // "2 | b"
* loader.setBlock("block2", "c"); // "3 | b | c"
*
* await new Promise((resolve) => setTimeout(resolve, 1000));
*
* loader.removeBlock("block1"); // "4 | c"
*
* await new Promise((resolve) => setTimeout(resolve, 1000));
*
* loader.stop();
*/
const Loader = class extends Spinner {
/**
* @type {Map<unknown, string>}
*/
#blocks = new Map();
/**
* @type {Map<unknown, number>}
*/
#maximumLengths = new Map();
/**
* @type {number}
*/
#messageCount = 0;
/**
* @type {unknown[]}
*/
#order = [];
/**
* Updates the message.
*
* @example
* this.#updateMessage();
*/
#updateMessage = () => {
this.message = [
this.#messageCount,
...this.#order
.filter((blockId) => this.#blocks.has(blockId))
.map((blockId, index) => {
const blockValue = this.#blocks.get(blockId);
return (
index === 0
? blockValue
: blockValue.padStart(this.#maximumLengths.get(blockId))
);
})
]
.join(" | ");
};
/**
*
* @param {unknown} id - The id of the block.
* @example
* const loader = new Loader({
* color: "blue",
* message: "Loading..."
* });
*
* loader.start();
*
* loader.setBlock("block1", "value1");
*
* loader.removeBlock("block1");
*
* loader.stop();
*/
removeBlock = (id) => {
this.#blocks.delete(id);
this.#messageCount += 1;
if (this.#messageCount % 1 === 0) {
this.#updateMessage();
}
};
/**
* Set the value of a block.
*
* @param {unknown} id - The id of the block.
* @param {string|number|boolean} value - The value of the block.
* @example
* const loader = new Loader({
* color: "blue",
* message: "Loading..."
* });
*
* loader.start();
*
* loader.setBlock("block1", "value1");
*
* loader.stop();
*/
setBlock = (id, value) => {
const valueString = String(value);
this.#maximumLengths.set(id, Math.max(
this.#maximumLengths.get(id) ?? 0,
valueString.length
));
this.#blocks.set(id, valueString);
if (!this.#order.includes(id)) {
this.#order.push(id);
}
this.#messageCount += 1;
this.#updateMessage();
};
};
export default Loader;
https://github.com/denoland/deno_std/assets/20396367/38ee1b51-8b62-4329-9820-96b423984bd9
https://github.com/denoland/deno_std/assets/20396367/78f78527-4f08-40e5-b298-c7072ddee819
It works for now, but if the list of things I want to track gets longer, one line might just not be enough.
I think it may be worth to evaluate the complexity of adding such a feature.
If it's too complicated then I agree it could be too much of a burden to maintain, but if it can be done without adding much complexity then we should add it (didn't look in details into spinnies code but it doesn't seem much is involved)
I agree with what has been precedly said in this thread:
- The fact that
Spinneris a class suggests that you could instantiate multiple instances but the fact that you actually can't is confusing - The fact that there are no really "up-to-date"/"maintained" popular libraries is what also make people not wanting to use this kind of feature (no-one want to maintain a loading/progress indicators in their own app 😅)
I think it's not democratized because few apps tends to offer actual proper parallelization
But this kind of addition is not only an improvement for developpers and their app, but also to end-users who can benefit a much better experience by having nice qol like this
I've had this same thought for a while now as well and want to introduce it to both the spinner and progress bar classes, but struggling to figure out exactly how something like this should work while also supporting random console.log calls.
I've had this same thought for a while now as well and want to introduce it to both the spinner and progress bar classes, but struggling to figure out exactly how something like this should work while also supporting random
console.logcalls.
I played around with that idea and managed to make multiple spinners and random log calls work by tracking the cursor position. Problem is that the console content cannot be moved if the spinner gets cleared which means an empty line will remain. This would only be preventable if write/writeSync and console methods would be overwritten to track the console content which sounds like a breeding ground for bugs.