This repository has been archived by the owner on Jun 26, 2023. It is now read-only.
/
timer.js
83 lines (77 loc) · 2.74 KB
/
timer.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
import {call, put, takeLatest, take, race, fork} from 'redux-saga/effects'
import { delay } from 'redux-saga'
// import axios from 'axios'
import { types } from '../redux/timer';
import { types as notify } from '../redux/notifications';
const { start, stop, pause, timeUpdated } = types;
// axios.defaults.headers['X-Mashape-Key'] = 'DPHo0ldO0cmshraPZ5DwFk71cDKxp1Zoeg3jsnpWGpchLsCPFY';
// unnecessary async and await, generator (saga?) handle promises for us
function* stopTimer() {
// console.log('stopping');
yield delay(5);
yield put({type: timeUpdated, elapsed: 0});
yield put({type: types.stopped, finished: true});
}
function* ticking(action) {
try {
let timeElapsed, pomoTime, restTime, notifications = {};
while (true){
const { started } = yield race({
started: take(start),
unpaused: take(types.resume),
});
if (started) {
pomoTime = started.pomoTime;
restTime = started.restTime;
timeElapsed = 0;
}
while (true) {
let timePrev = Date.now();
const { cancelled } = yield race({
ticked: call(delay, Math.round(Math.random() * 8) + 16),
cancelled: take([pause, types.stopped]),
});
if (cancelled)
break;
timeElapsed += Date.now() - timePrev;
if (!notifications.firstPomo && timeElapsed > pomoTime * 5e2){
notifications.firstPomo = true;
yield put({type: notify.issueNotification, message: 'Half way through your pomo!'})
}
if (!notifications.tfTillPomo && timeElapsed > (pomoTime - 25) * 1e3){
notifications.tfTillPomo = true;
yield put({type: notify.issueNotification, message: '25 second to the end'})
}
if (!notifications.lastPomo && timeElapsed >= pomoTime * 1e3){
notifications.lastPomo = true;
yield put({type: notify.issueNotification, message: 'You\'ve did it!'})
}
if (!notifications.firstRest && timeElapsed > (pomoTime + restTime - 25) * 1e3){
notifications.firstRest = true;
yield put({type: notify.issueNotification, message: 'Rest almost done, get ready!'});
}
if (timeElapsed > (pomoTime + restTime) * 1000)
yield fork(stopTimer);
yield put({ type: timeUpdated, elapsed: timeElapsed });
}
}
} catch (e) {
yield put({type: "Welp, we did it"});
}
}
function* rootSaga() {
yield takeLatest(stop, stopTimer);
yield takeLatest(types.updateSettings, function*(action) {
const {key, value} = action
const times = ['pomoTime', 'restTime'];
if (times.includes(key))
yield put({type: types.settingsUpdated, key, value: Math.max(+value, 0)});
else
yield put({type: types.settingsUpdated, key, value});
yield call(stopTimer);
});
yield fork(ticking);
// yield takeLatest(textUpdate, typing)
// yield takeLatest(textUpdate, spellcheckQuote); //Futura references
}
export default rootSaga;