/
withTimeout.tsx
62 lines (53 loc) · 1.78 KB
/
withTimeout.tsx
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Common
*/
import * as React from "react";
import { Timer } from "../utils/Timer";
/** Properties for [[withTimeout]] React higher-order component
* @public
*/
export interface WithTimeoutProps {
/** Timeout duration in milliseconds */
timeout: number;
/** Callback function for timeout */
onTimeout?: () => void;
}
/** withTimeout is a React higher-order component that adds timeout support.
* @public
*/
export const withTimeout = <ComponentProps extends {}>(
Component: React.ComponentType<ComponentProps>
) => {
return class WithTimeout extends React.PureComponent<
ComponentProps & WithTimeoutProps
> {
public timer: Timer = new Timer(0);
public override componentDidMount(): void {
this.timer.setOnExecute(
() => this.props.onTimeout && this.props.onTimeout()
);
this.startTimer(this.props.timeout);
}
public override componentDidUpdate(
_prevProps: Readonly<ComponentProps & WithTimeoutProps>
): void {
this.startTimer(this.props.timeout);
}
public override componentWillUnmount(): void {
this.timer.stop();
}
public override render() {
const { timeout, onTimeout, ...props } = this.props;
return <Component {...(props as any)} {...this.state} />;
}
public startTimer(timeout: number) {
if (this.timer.isRunning) return;
this.timer.delay = timeout;
this.timer.start();
}
};
};