UNPKG

3.22 kBJavaScriptView Raw
1const _GenericBar = require('./generic-bar');
2const _options = require('./options');
3
4// Progress-Bar constructor
5module.exports = class SingleBar extends _GenericBar{
6
7 constructor(options, preset){
8 super(_options.parse(options, preset));
9
10 // the update timer
11 this.timer = null;
12
13 // disable synchronous updates in notty mode
14 if (this.options.noTTYOutput && this.terminal.isTTY() === false){
15 this.options.synchronousUpdate = false;
16 }
17
18 // update interval
19 this.schedulingRate = (this.terminal.isTTY() ? this.options.throttleTime : this.options.notTTYSchedule);
20 }
21
22 // internal render function
23 render(){
24 // stop timer
25 if (this.timer){
26 clearTimeout(this.timer);
27 this.timer = null;
28 }
29
30 // run internal rendering
31 super.render();
32
33 // add new line in notty mode!
34 if (this.options.noTTYOutput && this.terminal.isTTY() === false){
35 this.terminal.newline();
36 }
37
38 // next update
39 this.timer = setTimeout(this.render.bind(this), this.schedulingRate);
40 }
41
42 update(current, payload){
43 // timer inactive ?
44 if (!this.timer) {
45 return;
46 }
47
48 super.update(current, payload);
49
50 // trigger synchronous update ?
51 // check for throttel time
52 if (this.options.synchronousUpdate && (this.lastRedraw + this.options.throttleTime*2) < Date.now()){
53 // force update
54 this.render();
55 }
56 }
57
58 // start the progress bar
59 start(total, startValue, payload){
60 // progress updates are only visible in TTY mode!
61 if (this.options.noTTYOutput === false && this.terminal.isTTY() === false){
62 return;
63 }
64
65 // save current cursor settings
66 this.terminal.cursorSave();
67
68 // hide the cursor ?
69 if (this.options.hideCursor === true){
70 this.terminal.cursor(false);
71 }
72
73 // disable line wrpaping ?
74 if (this.options.linewrap === false){
75 this.terminal.lineWrapping(false);
76 }
77
78 // initialize bar
79 super.start(total, startValue, payload);
80
81 // redraw on start!
82 this.render();
83 }
84
85 // stop the bar
86 stop(){
87 // timer inactive ?
88 if (!this.timer) {
89 return;
90 }
91
92 // trigger final rendering
93 this.render();
94
95 // restore state
96 super.stop();
97
98 // stop timer
99 clearTimeout(this.timer);
100 this.timer = null;
101
102 // cursor hidden ?
103 if (this.options.hideCursor === true){
104 this.terminal.cursor(true);
105 }
106
107 // re-enable line wrpaping ?
108 if (this.options.linewrap === false){
109 this.terminal.lineWrapping(true);
110 }
111
112 // restore cursor on complete (position + settings)
113 this.terminal.cursorRestore();
114
115 // clear line on complete ?
116 if (this.options.clearOnComplete){
117 this.terminal.cursorTo(0, null);
118 this.terminal.clearLine();
119 }else{
120 // new line on complete
121 this.terminal.newline();
122 }
123 }
124}
\No newline at end of file