|
| 1 | +import { useEffect, useMemo, useRef } from "react"; |
| 2 | +import { vscode } from "../vscode-api"; |
| 3 | + |
| 4 | +/** |
| 5 | + * A react effect that outputs telemetry events whenever the value changes. |
| 6 | + * |
| 7 | + * @param value Default value to pass to React.useState |
| 8 | + * @param telemetryAction Name of the telemetry event to output |
| 9 | + * @param options Extra optional arguments, including: |
| 10 | + * filterTelemetryOnValue: If provided, only output telemetry events when the |
| 11 | + * predicate returns true. If not provided always outputs telemetry. |
| 12 | + * debounceTimeout: If provided, will not output telemetry events for every change |
| 13 | + * but will wait until specified timeout happens with no new events ocurring. |
| 14 | + */ |
| 15 | +export function useTelemetryOnChange<S>( |
| 16 | + value: S, |
| 17 | + telemetryAction: string, |
| 18 | + { |
| 19 | + filterTelemetryOnValue, |
| 20 | + debounceTimeoutMillis, |
| 21 | + }: { |
| 22 | + filterTelemetryOnValue?: (value: S) => boolean; |
| 23 | + debounceTimeoutMillis?: number; |
| 24 | + } = {}, |
| 25 | +) { |
| 26 | + const previousValue = useRef(value); |
| 27 | + |
| 28 | + const sendTelemetryFunc = useMemo<() => void>(() => { |
| 29 | + if (debounceTimeoutMillis === undefined) { |
| 30 | + return () => sendTelemetry(telemetryAction); |
| 31 | + } else { |
| 32 | + let timer: NodeJS.Timeout; |
| 33 | + return () => { |
| 34 | + clearTimeout(timer); |
| 35 | + timer = setTimeout(() => { |
| 36 | + sendTelemetry(telemetryAction); |
| 37 | + }, debounceTimeoutMillis); |
| 38 | + }; |
| 39 | + } |
| 40 | + }, [telemetryAction, debounceTimeoutMillis]); |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + if (value === previousValue.current) { |
| 44 | + return; |
| 45 | + } |
| 46 | + previousValue.current = value; |
| 47 | + |
| 48 | + if (filterTelemetryOnValue && !filterTelemetryOnValue(value)) { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + sendTelemetryFunc(); |
| 53 | + }, [sendTelemetryFunc, filterTelemetryOnValue, value, previousValue]); |
| 54 | +} |
| 55 | + |
| 56 | +export function sendTelemetry(telemetryAction: string) { |
| 57 | + vscode.postMessage({ |
| 58 | + t: "telemetry", |
| 59 | + action: telemetryAction, |
| 60 | + }); |
| 61 | +} |
0 commit comments