grafana/public/app/features/explore/ElapsedTime.tsx

77 lines
1.8 KiB
TypeScript
Raw Normal View History

2018-04-26 04:58:42 -05:00
import React, { PureComponent } from 'react';
import { toDuration } from '@grafana/data';
2018-04-26 04:58:42 -05:00
const INTERVAL = 150;
export interface Props {
time?: number;
// Use this to reset the timer. Any value is allowed just need to be !== from the previous.
// Keep in mind things like [] !== [] or {} !== {}.
resetKey?: any;
className?: string;
humanize?: boolean;
}
export interface State {
elapsed: number;
}
/**
* Shows an incremental time ticker of elapsed time from some event.
*/
export default class ElapsedTime extends PureComponent<Props, State> {
2018-04-26 04:58:42 -05:00
offset: number;
2018-04-27 04:49:11 -05:00
timer: number;
2018-04-26 04:58:42 -05:00
state = {
elapsed: 0,
};
start() {
this.offset = Date.now();
2018-04-27 04:49:11 -05:00
this.timer = window.setInterval(this.tick, INTERVAL);
2018-04-26 04:58:42 -05:00
}
tick = () => {
const jetzt = Date.now();
const elapsed = jetzt - this.offset;
this.setState({ elapsed });
};
UNSAFE_componentWillReceiveProps(nextProps: Props) {
2018-04-26 04:58:42 -05:00
if (nextProps.time) {
clearInterval(this.timer);
} else if (this.props.time) {
this.start();
}
if (nextProps.resetKey !== this.props.resetKey) {
clearInterval(this.timer);
this.start();
}
2018-04-26 04:58:42 -05:00
}
componentDidMount() {
this.start();
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
const { elapsed } = this.state;
const { className, time, humanize } = this.props;
2018-04-26 04:58:42 -05:00
const value = (time || elapsed) / 1000;
let displayValue = `${value.toFixed(1)}s`;
if (humanize) {
const duration = toDuration(elapsed);
const hours = duration.hours();
const minutes = duration.minutes();
const seconds = duration.seconds();
displayValue = hours ? `${hours}h ${minutes}m ${seconds}s` : minutes ? ` ${minutes}m ${seconds}s` : `${seconds}s`;
}
return <span className={`elapsed-time ${className}`}>{displayValue}</span>;
2018-04-26 04:58:42 -05:00
}
}