Files
Termix/plugins/tmux-monitor/src/frontend/use-adaptive-polling.ts
T

64 lines
1.4 KiB
TypeScript

import { useEffect, useRef } from "react";
import { runAdaptivePolling } from "@termix/plugin-sdk/ui";
type AdaptivePollResult = boolean | void;
interface AdaptivePollingPolicy {
minIntervalMs: number;
maxIntervalMs: number;
stablePollsPerStep?: number;
jitterRatio?: number;
maxRequestDutyCycle?: number;
}
export function useAdaptivePolling(
poll: () => AdaptivePollResult | Promise<AdaptivePollResult>,
policy: AdaptivePollingPolicy,
enabled = true,
options: {
runImmediately?: boolean;
onError?: (error: unknown) => void;
} = {},
): void {
const pollRef = useRef(poll);
const errorRef = useRef(options.onError);
pollRef.current = poll;
errorRef.current = options.onError;
const {
minIntervalMs,
maxIntervalMs,
stablePollsPerStep,
jitterRatio,
maxRequestDutyCycle,
} = policy;
const runImmediately = options.runImmediately;
useEffect(
() =>
runAdaptivePolling(
() => pollRef.current(),
{
minIntervalMs,
maxIntervalMs,
stablePollsPerStep,
jitterRatio,
maxRequestDutyCycle,
},
{
enabled: () => enabled,
runImmediately,
onError: (error) => errorRef.current?.(error),
},
),
[
enabled,
jitterRatio,
maxIntervalMs,
minIntervalMs,
runImmediately,
stablePollsPerStep,
maxRequestDutyCycle,
],
);
}