Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

utils.tsx

267 lines6.2 KB

1import { serialize } from 'superjson'
2import { createSignal, onCleanup, onMount } from 'solid-js'
3import type { Query } from '@tanstack/query-core'
4import type { DevtoolsPosition } from './Context'
5​
6export function getQueryStatusLabel(query: Query) {
7 return query.state.fetchStatus === 'fetching'
8 ? 'fetching'
9 : !query.getObserversCount()
10 ? 'inactive'
11 : query.state.fetchStatus === 'paused'
12 ? 'paused'
13 : query.isStale()
14 ? 'stale'
15 : 'fresh'
17​
18export const queryStatusLabels = [
19 'fresh',
20 'stale',
21 'paused',
22 'inactive',
23 'fetching',
24] as const
25export type IQueryStatusLabel = (typeof queryStatusLabels)[number]
26​
27export function getSidedProp<T extends string>(
28 prop: T,
29 side: DevtoolsPosition,
30) {
31 return `${prop}${
32 side.charAt(0).toUpperCase() + side.slice(1)
33 }` as `${T}${Capitalize<DevtoolsPosition>}`
35​
36export function getQueryStatusColor({
37 queryState,
38 observerCount,
39 isStale,
40}: {
41 queryState: Query['state']
42 observerCount: number
43 isStale: boolean
44}) {
45 return queryState.fetchStatus === 'fetching'
46 ? 'blue'
47 : !observerCount
48 ? 'gray'
49 : queryState.fetchStatus === 'paused'
50 ? 'purple'
51 : isStale
52 ? 'yellow'
53 : 'green'
55​
56export function getQueryStatusColorByLabel(label: IQueryStatusLabel) {
57 return label === 'fresh'
58 ? 'green'
59 : label === 'stale'
60 ? 'yellow'
61 : label === 'paused'
62 ? 'purple'
63 : label === 'inactive'
64 ? 'gray'
65 : 'blue'
67​
68/**
69 * Displays a string regardless the type of the data
70 * @param {unknown} value Value to be stringified
71 * @param {boolean} beautify Formats json to multiline
72 */
73export const displayValue = (value: unknown, beautify: boolean = false) => {
74 const { json } = serialize(value)
75​
76 return JSON.stringify(json, null, beautify ? 2 : undefined)
78​
79// Sorting functions
80type SortFn = (a: Query, b: Query) => number
81​
82const getStatusRank = (q: Query) =>
83 q.state.fetchStatus !== 'idle'
84 ? 0
85 : !q.getObserversCount()
86 ? 3
87 : q.isStale()
88 ? 2
89 : 1
90​
91const queryHashSort: SortFn = (a, b) => a.queryHash.localeCompare(b.queryHash)
92​
93const dateSort: SortFn = (a, b) =>
94 a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1
95​
96const statusAndDateSort: SortFn = (a, b) => {
97 if (getStatusRank(a) === getStatusRank(b)) {
98 return dateSort(a, b)
99 }
100​
101 return getStatusRank(a) > getStatusRank(b) ? 1 : -1
103​
104export const sortFns: Record<string, SortFn> = {
105 status: statusAndDateSort,
106 'query hash': queryHashSort,
107 'last updated': dateSort,
109​
110export const convertRemToPixels = (rem: number) => {
111 return rem * parseFloat(getComputedStyle(document.documentElement).fontSize)
113​
114export const convertPixelsToRem = (px: number) => px / convertRemToPixels(1)
115​
116export const getPreferredColorScheme = () => {
117 const [colorScheme, setColorScheme] = createSignal<'light' | 'dark'>('dark')
118​
119 onMount(() => {
120 const query = window.matchMedia('(prefers-color-scheme: dark)')
121 setColorScheme(query.matches ? 'dark' : 'light')
122 const listener = (e: MediaQueryListEvent) => {
123 setColorScheme(e.matches ? 'dark' : 'light')
124 }
125 query.addEventListener('change', listener)
126 onCleanup(() => query.removeEventListener('change', listener))
127 })
128​
129 return colorScheme
131​
132/**
133 * updates nested data by path
134 *
135 * @param {unknown} oldData Data to be updated
136 * @param {Array<string>} updatePath Path to the data to be updated
137 * @param {unknown} value New value
138 */
139export const updateNestedDataByPath = (
140 oldData: unknown,
141 updatePath: Array<string>,
142 value: unknown,
143): any => {
144 if (updatePath.length === 0) {
145 return value
146 }
147​
148 if (oldData instanceof Map) {
149 const newData = new Map(oldData)
150​
151 if (updatePath.length === 1) {
152 newData.set(updatePath[0], value)
153 return newData
154 }
155​
156 const [head, ...tail] = updatePath
157 newData.set(head, updateNestedDataByPath(newData.get(head), tail, value))
158 return newData
159 }
160​
161 if (oldData instanceof Set) {
162 const setAsArray = updateNestedDataByPath(
163 Array.from(oldData),
164 updatePath,
165 value,
166 )
167​
168 return new Set(setAsArray)
169 }
170​
171 if (Array.isArray(oldData)) {
172 const newData = [...oldData]
173​
174 if (updatePath.length === 1) {
175 // @ts-expect-error
176 newData[updatePath[0]] = value
177 return newData
178 }
179​
180 const [head, ...tail] = updatePath
181 // @ts-expect-error
182 newData[head] = updateNestedDataByPath(newData[head], tail, value)
183​
184 return newData
185 }
186​
187 if (oldData instanceof Object) {
188 const newData = { ...oldData }
189​
190 if (updatePath.length === 1) {
191 // @ts-expect-error
192 newData[updatePath[0]] = value
193 return newData
194 }
195​
196 const [head, ...tail] = updatePath
197 // @ts-expect-error
198 newData[head] = updateNestedDataByPath(newData[head], tail, value)
199​
200 return newData
201 }
202​
203 return oldData
205​
206/**
207 * Deletes nested data by path
208 *
209 * @param {unknown} oldData Data to be updated
210 * @param {Array<string>} deletePath Path to the data to be deleted
211 * @returns newData without the deleted items by path
212 */
213export const deleteNestedDataByPath = (
214 oldData: unknown,
215 deletePath: Array<string>,
216): any => {
217 if (oldData instanceof Map) {
218 const newData = new Map(oldData)
219​
220 if (deletePath.length === 1) {
221 newData.delete(deletePath[0])
222 return newData
223 }
224​
225 const [head, ...tail] = deletePath
226 newData.set(head, deleteNestedDataByPath(newData.get(head), tail))
227 return newData
228 }
229​
230 if (oldData instanceof Set) {
231 const setAsArray = deleteNestedDataByPath(Array.from(oldData), deletePath)
232 return new Set(setAsArray)
233 }
234​
235 if (Array.isArray(oldData)) {
236 const newData = [...oldData]
237​
238 if (deletePath.length === 1) {
239 return newData.filter((_, idx) => idx.toString() !== deletePath[0])
240 }
241​
242 const [head, ...tail] = deletePath
243​
244 // @ts-expect-error
245 newData[head] = deleteNestedDataByPath(newData[head], tail)
246​
247 return newData
248 }
249​
250 if (oldData instanceof Object) {
251 const newData = { ...oldData }
252​
253 if (deletePath.length === 1) {
254 // @ts-expect-error
255 delete newData[deletePath[0]]
256 return newData
257 }
258​
259 const [head, ...tail] = deletePath
260 // @ts-expect-error
261 newData[head] = deleteNestedDataByPath(newData[head], tail)
262​
263 return newData
264 }
265​
266 return oldData