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, 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, ], ); }