Open History to see the last commit
1import { createSignal, onCleanup, onMount } from 'solid-js'
2import { serialize } from 'superjson'
3import { getNativeObjectType } from './nativeObjectType'
4import type { Mutation, Query } from '@tanstack/query-core'
5import type { DevtoolsPosition } from './contexts'
6β
7/**
8 * Returns the status label of a query: fetching, inactive (no observers), paused, stale, or fresh,
9 * checked in that order.
10 * @param query - The query to label.
11 * @returns One of `'fetching'`, `'inactive'`, `'paused'`, `'stale'`, or `'fresh'`.
12 */
13export function getQueryStatusLabel(query: Query) {
14 return query.state.fetchStatus === 'fetching'
15 ? 'fetching'
16 : !query.getObserversCount()
17 ? 'inactive'
18 : query.state.fetchStatus === 'paused'
19 ? 'paused'
20 : query.isStale()
21 ? 'stale'
22 : 'fresh'
23}
24β
25type QueryStatusLabel = 'fresh' | 'stale' | 'paused' | 'inactive' | 'fetching'
26β
27/**
28 * Appends a capitalized side to a CSS property name, e.g. `border` and `left` to `borderLeft`.
29 * @param prop - The property name.
30 * @param side - The side to append.
31 * @returns The sided property name.
32 */
33export function getSidedProp<T extends string>(
34 prop: T,
35 side: DevtoolsPosition,
36) {
37 return `${prop}${
38 side.charAt(0).toUpperCase() + side.slice(1)
39 }` as `${T}${Capitalize<DevtoolsPosition>}`
40}
41β
42/**
43 * Returns the color of a query's status: blue while fetching, gray without observers, purple while
44 * paused, yellow when stale, otherwise green.
45 * @param params - The query's `queryState`, `observerCount`, and `isStale`.
46 * @returns The color name.
47 */
48export function getQueryStatusColor({
49 queryState,
50 observerCount,
51 isStale,
52}: {
53 queryState: Query['state'] | undefined
54 observerCount: number
55 isStale: boolean
56}) {
57 return queryState?.fetchStatus === 'fetching'
58 ? 'blue'
59 : !observerCount
60 ? 'gray'
61 : queryState?.fetchStatus === 'paused'
62 ? 'purple'
63 : isStale
64 ? 'yellow'
65 : 'green'
66}
67β
68/**
69 * Returns the color of a mutation's status: purple while paused, red on error, yellow while pending,
70 * green on success, otherwise gray.
71 * @param params - The mutation's `status` and `isPaused`.
72 * @returns The color name.
73 */
74export function getMutationStatusColor({
75 status,
76 isPaused,
77}: {
78 status: Mutation['state']['status']
79 isPaused: boolean
80}) {
81 return isPaused
82 ? 'purple'
83 : status === 'error'
84 ? 'red'
85 : status === 'pending'
86 ? 'yellow'
87 : status === 'success'
88 ? 'green'
89 : 'gray'
90}
91β
92/**
93 * Returns the color of a query status label.
94 * @param label - A label returned by {@link getQueryStatusLabel}.
95 * @returns The color name.
96 */
97export function getQueryStatusColorByLabel(label: QueryStatusLabel) {
98 return label === 'fresh'
99 ? 'green'
100 : label === 'stale'
101 ? 'yellow'
102 : label === 'paused'
103 ? 'purple'
104 : label === 'inactive'
105 ? 'gray'
106 : 'blue'
107}
108β
109/**
110 * Displays a string regardless of the type of the data.
111 * @param value - Value to be stringified
112 * @param beautify - Formats json to multiline
113 * @returns The value serialized with `superjson`, as a JSON string.
114 */
115export const displayValue = (value: unknown, beautify: boolean = false) => {
116 const { json } = serialize(value)
117β
118 return JSON.stringify(json, null, beautify ? 2 : undefined)
119}
120β
121// Sorting functions
122type SortFn = (a: Query, b: Query) => number
123β
124const getStatusRank = (q: Query) =>
125 q.state.fetchStatus !== 'idle'
126 ? 0
127 : !q.getObserversCount()
128 ? 3
129 : q.isStale()
130 ? 2
131 : 1
132β
133const queryHashSort: SortFn = (a, b) => a.queryHash.localeCompare(b.queryHash)
134β
135const dateSort: SortFn = (a, b) => {
136 const diff = b.state.dataUpdatedAt - a.state.dataUpdatedAt
137 return diff < 0 ? -1 : diff > 0 ? 1 : 0
138}
139β
140const statusAndDateSort: SortFn = (a, b) => {
141 if (getStatusRank(a) === getStatusRank(b)) {
142 return dateSort(a, b)
143 }
144β
145 return getStatusRank(a) > getStatusRank(b) ? 1 : -1
146}
147β
148export const sortFns: Record<string, SortFn> = {
149 status: statusAndDateSort,
150 'query hash': queryHashSort,
151 'last updated': dateSort,
152}
153β
154type MutationSortFn = (a: Mutation, b: Mutation) => number
155β
156const getMutationStatusRank = (m: Mutation) =>
157 m.state.isPaused
158 ? 0
159 : m.state.status === 'error'
160 ? 2
161 : m.state.status === 'pending'
162 ? 1
163 : 3
164β
165const mutationDateSort: MutationSortFn = (a, b) =>
166 a.state.submittedAt < b.state.submittedAt ? 1 : -1
167β
168const mutationStatusSort: MutationSortFn = (a, b) => {
169 if (getMutationStatusRank(a) === getMutationStatusRank(b)) {
170 return mutationDateSort(a, b)
171 }
172β
173 return getMutationStatusRank(a) > getMutationStatusRank(b) ? 1 : -1
174}
175β
176export const mutationSortFns: Record<string, MutationSortFn> = {
177 status: mutationStatusSort,
178 'last updated': mutationDateSort,
179}
180β
181/**
182 * Converts a length in `rem` to pixels, using the root element's font size.
183 * @param rem - The length in `rem`.
184 * @returns The length in pixels.
185 */
186export const convertRemToPixels = (rem: number) => {
187 return rem * parseFloat(getComputedStyle(document.documentElement).fontSize)
188}
189β
190/**
191 * Tracks the user's `prefers-color-scheme` setting.
192 * @returns An accessor of `'light'` or `'dark'`, updated when the setting
193 * changes.
194 */
195export const getPreferredColorScheme = () => {
196 const [colorScheme, setColorScheme] = createSignal<'light' | 'dark'>('dark')
197β
198 onMount(() => {
199 const query = window.matchMedia('(prefers-color-scheme: dark)')
200 setColorScheme(query.matches ? 'dark' : 'light')
201 const listener = (e: MediaQueryListEvent) => {
202 setColorScheme(e.matches ? 'dark' : 'light')
203 }
204 query.addEventListener('change', listener)
205 onCleanup(() => query.removeEventListener('change', listener))
206 })
207β
208 return colorScheme
209}
210β
211/**
212 * Checks whether a value is a plain object without invoking accessors, including across realms.
213 * @param value - The data to inspect.
214 * @returns Whether the value can be copied as a record.
215 */
216export function isPlainObject(value: unknown): boolean {
217 if (value === null || typeof value !== 'object') return false
218 try {
219 const prototype = Object.getPrototypeOf(value)
220 if (prototype === null) return true
221 const constructor = Object.getOwnPropertyDescriptor(
222 prototype,
223 'constructor',
224 )?.value
225 return (
226 typeof constructor === 'function' &&
227 Object.getOwnPropertyDescriptor(constructor, 'prototype')?.value ===
228 prototype &&
229 Function.prototype.toString.call(constructor) ===
230 Function.prototype.toString.call(Object)
231 )
232 } catch {
233 return false
234 }
235}
236β
237/**
238 * Updates nested data by path.
239 * @param oldData - Data to be updated
240 * @param updatePath - Path to the data to be updated
241 * @param value - New value
242 * @returns A copy of `oldData` with the value at `updatePath` replaced.
243 */
244export const updateNestedDataByPath = (
245 oldData: unknown,
246 updatePath: Array<string>,
247 value: unknown,
248): any => {
249 if (updatePath.length === 0) {
250 return value
251 }
252β
253 const type = getNativeObjectType(oldData)
254 if (type === 'Map') {
255 const newData = new Map<unknown, unknown>(
256 Map.prototype.entries.call(oldData),
257 )
258β
259 if (updatePath.length === 1) {
260 newData.set(updatePath[0], value)
261 return newData
262 }
263β
264 const [head, ...tail] = updatePath
265 newData.set(head, updateNestedDataByPath(newData.get(head), tail, value))
266 return newData
267 }
268β
269 if (type === 'Set') {
270 const setAsArray = updateNestedDataByPath(
271 Array.from(Set.prototype.values.call(oldData)),
272 updatePath,
273 value,
274 )
275β
276 return new Set(setAsArray)
277 }
278β
279 if (Array.isArray(oldData)) {
280 const newData = [...oldData]
281β
282 if (updatePath.length === 1) {
283 // @ts-expect-error
284 newData[updatePath[0]] = value
285 return newData
286 }
287β
288 const [head, ...tail] = updatePath
289 // @ts-expect-error
290 newData[head] = updateNestedDataByPath(newData[head], tail, value)
291β
292 return newData
293 }
294β
295 if (isPlainObject(oldData)) {
296 const descriptors = Object.getOwnPropertyDescriptors(oldData)
297 const [head, ...tail] = updatePath
298 if (head === undefined) return oldData
299 const previous = Object.getOwnPropertyDescriptor(oldData, head)
300 if (tail.length && (!previous || !('value' in previous))) return oldData
301 return Object.create(Object.getPrototypeOf(oldData), {
302 ...descriptors,
303 [head]: {
304 value: tail.length
305 ? updateNestedDataByPath(previous?.value, tail, value)
306 : value,
307 enumerable: previous?.enumerable ?? true,
308 configurable: true,
309 writable: true,
310 },
311 })
312 }
313β
314 return oldData
315}
316β
317/**
318 * Deletes nested data by path.
319 * @param oldData - Data to be updated
320 * @param deletePath - Path to the data to be deleted
321 * @returns newData without the deleted items by path
322 */
323export const deleteNestedDataByPath = (
324 oldData: unknown,
325 deletePath: Array<string>,
326): any => {
327 const type = getNativeObjectType(oldData)
328 if (type === 'Map') {
329 const newData = new Map<unknown, unknown>(
330 Map.prototype.entries.call(oldData),
331 )
332β
333 if (deletePath.length === 1) {
334 newData.delete(deletePath[0])
335 return newData
336 }
337β
338 const [head, ...tail] = deletePath
339 newData.set(head, deleteNestedDataByPath(newData.get(head), tail))
340 return newData
341 }
342β
343 if (type === 'Set') {
344 const setAsArray = deleteNestedDataByPath(
345 Array.from(Set.prototype.values.call(oldData)),
346 deletePath,
347 )
348 return new Set(setAsArray)
349 }
350β
351 if (Array.isArray(oldData)) {
352 const newData = [...oldData]
353β
354 if (deletePath.length === 1) {
355 return newData.filter((_, idx) => idx.toString() !== deletePath[0])
356 }
357β
358 const [head, ...tail] = deletePath
359β
360 // @ts-expect-error
361 newData[head] = deleteNestedDataByPath(newData[head], tail)
362β
363 return newData
364 }
365β
366 if (isPlainObject(oldData)) {
367 const descriptors = Object.getOwnPropertyDescriptors(oldData)
368 const [head, ...tail] = deletePath
369 if (head === undefined) return oldData
370 if (tail.length === 0) {
371 delete descriptors[head]
372 } else {
373 const previous = Object.getOwnPropertyDescriptor(oldData, head)
374 if (!previous || !('value' in previous)) return oldData
375 descriptors[head] = {
376 ...previous,
377 value: deleteNestedDataByPath(previous.value, tail),
378 }
379 }
380 return Object.create(Object.getPrototypeOf(oldData), descriptors)
381 }
382β
383 return oldData
384}