-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
108 lines (96 loc) · 2.56 KB
/
index.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const log = require('single-line-log').stdout;
const say = require('say');
const notifier = require('node-notifier');
const stdin = process.stdin;
stdin.setRawMode( true );
stdin.resume();
stdin.setEncoding( 'utf8' );
module.exports = function createIntervals(sets, intervals, speak) {
let intervalSet = [];
while(sets > 0) {
intervalSet = intervalSet.concat(intervals);
sets--;
}
function runTimer() {
if (intervalSet.length <= 0) {
process.exit();
return;
}
startTimer(intervalSet.shift(), runTimer, speak);
}
runTimer();
};
function startTimer(minutes, callback, speak) {
const currentSet = {
minutes: minutes,
startTime: Date.now(),
now: Date.now(),
speak: speak,
paused: false
};
const removeListener = setKeybindingsForCurrentSet(currentSet);
tick(currentSet);
function tick () {
if (!currentSet.paused) {
currentSet.now+=1000;
const timeInSeconds = getRemainingTimeInSeconds(currentSet);
if (timeInSeconds <= 0) {
const message = 'interval complete';
console.log(message, '\n');
notifier.notify({
title: 'interval-timer',
message
});
if (currentSet.speak) {
say.speak(message);
}
removeListener();
callback();
} else {
updateTimer(currentSet);
setTimeout(tick, 1000);
}
} else {
setTimeout(tick, 1000);
}
}
}
function getRemainingTimeInSeconds(intervalSet) {
var minutesInMs = intervalSet.minutes * 60 * 1000;
return (intervalSet.startTime + minutesInMs - intervalSet.now)/1000;
}
function setKeybindingsForCurrentSet(intervalSet) {
var listener = function (key) {
if ( key === '\u0003' ) {
process.exit();
}
if (key === "p" ) {
intervalSet.paused = !intervalSet.paused;
updateTimer(intervalSet);
}
if (!isNaN(parseFloat(key))) {
intervalSet.minutes+= +key;
updateTimer(intervalSet);
}
if (key === '-') {
intervalSet.minutes-= 1;
updateTimer(intervalSet);
}
};
stdin.on('data', listener);
return function() {
stdin.removeListener('data', listener);
};
}
function updateTimer(intervalSet) {
var timeRemaining = getRemainingTimeInSeconds(intervalSet);
var pPaused = intervalSet.paused ? 'paused' : '';
if (timeRemaining <= 0) {
timeRemaining = 0;
}
var pTime = {
seconds:Math.floor(timeRemaining % 60),
minutes:Math.floor(timeRemaining / 60)
};
log(`Current timer: ${pTime.minutes}:${pTime.seconds} ${pPaused} \n`);
}