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