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