-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathSpinner.ts
More file actions
71 lines (63 loc) · 1.62 KB
/
Copy pathSpinner.ts
File metadata and controls
71 lines (63 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
export class Spinner {
private stopped = false;
private timer: NodeJS.Timeout | null = null;
private spinnerIndex = 0;
public constructor(
private text: string,
private readonly outputStream: NodeJS.WriteStream = process.stdout,
) {
this.timer = setInterval(() => {
this.spinnerIndex++;
this.refresh();
}, 80);
}
public stopIfNotStopped() {
if (this.stopped === false) {
this.stop();
}
}
public stop() {
if (this.stopped === true) {
throw new Error("Spinner already stopped");
}
this.stopped = true;
if (this.timer !== null) {
clearInterval(this.timer);
this.timer = null;
}
this.outputStream.write("\r\x1B[K");
this.outputStream.write("\x1B[?25h");
}
public stopWithoutClear() {
if (this.stopped === true) {
throw new Error("Spinner already stopped");
}
this.stopped = true;
if (this.timer !== null) {
clearInterval(this.timer);
this.timer = null;
}
this.outputStream.write("\x1B[?25h");
}
public start() {
if (this.stopped === false) {
throw new Error("Spinner already started");
}
this.stopped = false;
this.timer = setInterval(() => {
this.spinnerIndex++;
this.refresh();
}, 80);
}
public setText(text: string) {
this.text = text;
this.refresh();
}
private refresh() {
this.outputStream.write("\x1B[?25l");
this.outputStream.write(
`\r${this.text} ${SPINNER_FRAMES[this.spinnerIndex % SPINNER_FRAMES.length]}`,
);
}
}