alpinesmuseum-public/assets/js/components/AppMenu/Redirecter.js

74 lines
1.4 KiB
JavaScript

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import animateScrollTo from 'animated-scroll-to';
import autobind from 'autobind-decorator';
const user_events = [
'mousemove',
'mousedown',
'keydown',
'scroll',
'touchstart',
'resize',
'visibilitychange'
];
const idle_timeout = 5 * 60 * 1000; // 5 minutes
const inactivityTime = (callback, idleTimeout) => {
var time;
user_events.forEach(function(name) {
document.addEventListener(name, resetTimer, true);
});
function resetTimer(destroy) {
clearTimeout(time);
if (destroy === true) {
user_events.forEach(function(name) {
document.removeEventListener(name, resetTimer, true);
});
} else {
time = setTimeout(callback, idleTimeout);
}
}
resetTimer();
return resetTimer;
};
@autobind
export default class Redirecter extends Component {
constructor(props) {
super(props);
this.state = {
goBackHome: false
};
}
setNewTimer() {
if (this.resetTimer) {
// destroy the current timer
this.resetTimer(true);
}
this.resetTimer = inactivityTime(() => {
this.setState({ goBackHome: true });
this.setState({ goBackHome: false });
}, idle_timeout);
}
componentDidMount() {
this.setNewTimer();
}
componentDidUpdate() {
this.setNewTimer();
}
render() {
if (this.state.goBackHome) {
animateScrollTo(document.getElementById('root'));
return <Redirect to='/' />;
}
return null;
}
}