-
Notifications
You must be signed in to change notification settings - Fork 585
/
Copy pathuse-cpu.ts
53 lines (47 loc) · 1.2 KB
/
use-cpu.ts
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
import {sort} from 'remeda'
import {LOADING_DASH} from '@/constants'
import {trpcReact} from '@/trpc/trpc'
import {t} from '@/utils/i18n'
export function useCpu(options: {poll?: boolean} = {}) {
const cpuQ = trpcReact.system.cpuUsage.useQuery(undefined, {
// Sometimes we won't be able to get disk usage, so prevent retry
retry: false,
// We do want refetching to happen on a schedule though
refetchInterval: options.poll ? 1000 : undefined,
})
return {
data: cpuQ.data,
isLoading: cpuQ.isLoading,
//
percentUsed: cpuQ.data?.totalUsed ?? 0,
threads: cpuQ.data?.threads ?? 0,
apps: sort(
[
...(cpuQ.data?.apps ?? []),
{
id: 'umbreld-system',
used: cpuQ.data?.system ?? 0,
},
],
(a, b) => b.used - a.used,
),
}
}
export function useCpuForUi(options: {poll?: boolean} = {}) {
const {isLoading, percentUsed, threads, apps} = useCpu({poll: options.poll})
if (isLoading) {
return {
isLoading: true,
value: LOADING_DASH,
progress: 0,
secondaryValue: LOADING_DASH,
} as const
}
return {
isLoading: false,
value: Math.ceil(percentUsed) + '%',
progress: percentUsed / 100,
secondaryValue: t('cpu-core-count', {cores: threads}),
apps,
} as const
}