Open History to see the last commit
1import type { Query } from '@tanstack/query-core'
2import { serialize } from 'superjson'
3import type { DevtoolsPosition } from './Context'
4β
5export function getQueryStatusLabel(query: Query) {
6 return query.state.fetchStatus === 'fetching'
7 ? 'fetching'
8 : !query.getObserversCount()
9 ? 'inactive'
10 : query.state.fetchStatus === 'paused'
11 ? 'paused'
12 : query.isStale()
13 ? 'stale'
14 : 'fresh'
15}
16β
17export const queryStatusLabels = [
18 'fresh',
19 'stale',
20 'paused',
21 'inactive',
22 'fetching',
23] as const
24export type IQueryStatusLabel = (typeof queryStatusLabels)[number]
25β
26export function getSidedProp<T extends string>(
27 prop: T,
28 side: DevtoolsPosition,
29) {
30 return `${prop}${
31 side.charAt(0).toUpperCase() + side.slice(1)
32 }` as `${T}${Capitalize<DevtoolsPosition>}`
33}
34β
35export function getQueryStatusColor({
36 queryState,
37 observerCount,
38 isStale,
39}: {
40 queryState: Query['state']
41 observerCount: number
42 isStale: boolean
43}) {
44 return queryState.fetchStatus === 'fetching'
45 ? 'blue'
46 : !observerCount
47 ? 'gray'
48 : queryState.fetchStatus === 'paused'
49 ? 'purple'
50 : isStale
51 ? 'yellow'
52 : 'green'
53}
54β
55export function getQueryStatusColorByLabel(label: IQueryStatusLabel) {
56 return label === 'fresh'
57 ? 'green'
58 : label === 'stale'
59 ? 'yellow'
60 : label === 'paused'
61 ? 'purple'
62 : label === 'inactive'
63 ? 'gray'
64 : 'blue'
65}
66β
67/**
68 * Displays a string regardless the type of the data
69 * @param {unknown} value Value to be stringified
70 * @param {boolean} beautify Formats json to multiline
71 */
72export const displayValue = (value: unknown, beautify: boolean = false) => {
73 const { json } = serialize(value)
74β
75 return JSON.stringify(json, null, beautify ? 2 : undefined)
76}
77β
78// Sorting functions
79type SortFn = (a: Query, b: Query) => number
80β
81const getStatusRank = (q: Query) =>
82 q.state.fetchStatus !== 'idle'
83 ? 0
84 : !q.getObserversCount()
85 ? 3
86 : q.isStale()
87 ? 2
88 : 1
89β
90const queryHashSort: SortFn = (a, b) => a.queryHash.localeCompare(b.queryHash)
91β
92const dateSort: SortFn = (a, b) =>
93 a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1
94β
95const statusAndDateSort: SortFn = (a, b) => {
96 if (getStatusRank(a) === getStatusRank(b)) {
97 return dateSort(a, b)
98 }
99β
100 return getStatusRank(a) > getStatusRank(b) ? 1 : -1
101}
102β
103export const sortFns: Record<string, SortFn> = {
104 status: statusAndDateSort,
105 'query hash': queryHashSort,
106 'last updated': dateSort,
107}
108β
109export const convertRemToPixels = (rem: number) => {
110 return rem * parseFloat(getComputedStyle(document.documentElement).fontSize)
111}
112β
113export const convertPixelsToRem = (px: number) => px / convertRemToPixels(1)