forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusePerformanceAudit.ts
More file actions
62 lines (54 loc) · 1.53 KB
/
Copy pathusePerformanceAudit.ts
File metadata and controls
62 lines (54 loc) · 1.53 KB
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
import { useCallback, useEffect, useRef } from "react";
import {
startAudit,
type AuditEntry,
type AuditScope,
} from "@/lib/observability/performanceAudit";
interface UsePerformanceAuditOptions {
scope: AuditScope;
metadata?: Record<string, string | number | boolean>;
autoStart?: boolean;
}
interface UsePerformanceAuditResult {
markDone: (
_extraMetadata?: Record<string, string | number | boolean>
) => AuditEntry | null;
restart: () => void;
}
export function usePerformanceAudit({
scope,
metadata,
autoStart = true,
}: UsePerformanceAuditOptions): UsePerformanceAuditResult {
const stopRef = useRef<((_?: Record<string, string | number | boolean>) => AuditEntry) | null>(
null
);
const start = useCallback(() => {
stopRef.current = startAudit(scope);
}, [scope]);
useEffect(() => {
if (autoStart) {
start();
}
return () => {
// If the component unmounts before markDone is called, record with whatever was set.
stopRef.current?.(metadata);
stopRef.current = null;
};
// eslint-disable-next-line
}, [scope, autoStart]);
const markDone = useCallback(
(extraMetadata?: Record<string, string | number | boolean>): AuditEntry | null => {
if (!stopRef.current) return null;
const entry = stopRef.current({ ...metadata, ...extraMetadata });
stopRef.current = null;
return entry;
},
[metadata]
);
const restart = useCallback(() => {
stopRef.current = null;
start();
}, [start]);
return { markDone, restart };
}