pomodoro/client/components/Timer.jsx
Linus Miller 47ce0a2a33 Huge commit
- Update all deps
 - Apply midwest changes
 - Convert all templates to JSX
 - Preact instead of Marko
 - Babel & Eslint
2016-11-10 14:34:44 +01:00

110 lines
2.1 KiB
JavaScript

import { h, Component } from 'preact';
import { bindAll } from 'lowline';
import timeFilter from '../util/time-filter';
const length = 25 * 60 * 1000;
export default class Timer extends Component {
constructor() {
super();
this.state = {
time: length,
totalTime: length,
startTime: undefined,
};
bindAll(this, ['start', 'pause', 'reset', 'updateTimer', 'end']);
}
componentDidMount() {
this.reset();
}
start() {
this.setState({
startTime: Date.now(),
});
this.interval = setInterval(this.updateTimer.bind(this), 10);
}
pause() {
clearInterval(this.interval);
}
reset() {
clearInterval(this.interval);
this.setState({
time: length,
totalTime: length,
startTime: undefined,
});
}
updateTimer() {
let time = this.state.totalTime - (Date.now() - this.state.startTime);
if (time <= 0) {
this.pause();
this.end();
time = 0;
}
document.title = timeFilter(time).slice(0, 5);
this.setState({
time,
});
}
end() {
const data = {
startTime: this.state.startTime,
endTime: new Date(),
};
document.title = 'Pling!';
if (Notification.permission !== 'granted') {
Notification.requestPermission();
} else {
const notification = new Notification('Pomodoro complete!', {
icon: 'https://www.planetnatural.com/wp-content/uploads/2014/03/tomato-supplies.jpg',
body: 'Time for a break!',
});
}
fetch('/api/pomodoros', {
method: 'POST',
body: JSON.stringify(data),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((json) => {
console.log('succes');
});
}
render(props, state) {
return (
<div class="timer">
<div class="time">{timeFilter(state.time || 0)}</div>
<div class="buttons">
<button onClick={this.start}>Start</button>
<button>Pause</button>
<button>Reset</button>
</div>
</div>
);
}
}