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 './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'
16}
17β
18type QueryStatusLabel = 'fresh' | 'stale' | 'paused' | 'inactive' | 'fetching'
19β
20export function getSidedProp<T extends string>(
21 prop: T,
22 side: DevtoolsPosition,
23) {
24 return `${prop}${
25 side.charAt(0).toUpperCase() + side.slice(1)
26 }` as `${T}${Capitalize<DevtoolsPosition>}`
27}
28β
29export function getQueryStatusColor({
30 queryState,
31 observerCount,
32 isStale,
33}: {
34 queryState: Query['state']
35 observerCount: number
36 isStale: boolean
37}) {
38 return queryState.fetchStatus === 'fetching'
39 ? 'blue'
40 : !observerCount
41 ? 'gray'
42 : queryState.fetchStatus === 'paused'
43 ? 'purple'
44 : isStale
45 ? 'yellow'
46 : 'green'
47}
48β
49export function getMutationStatusColor({
50 status,
51 isPaused,
52}: {
53 status: Mutation['state']['status']
54 isPaused: boolean
55}) {
56 return isPaused
57 ? 'purple'
58 : status === 'error'
59 ? 'red'
60 : status === 'pending'
61 ? 'yellow'
62 : status === 'success'
63 ? 'green'
64 : 'gray'
65}
66β
67export function getQueryStatusColorByLabel(label: QueryStatusLabel) {
68 return label === 'fresh'
69 ? 'green'
70 : label === 'stale'
71 ? 'yellow'
72 : label === 'paused'
73 ? 'purple'
74 : label === 'inactive'
75 ? 'gray'
76 : 'blue'
77}
78β
79/**
80 * Displays a string regardless the type of the data
81 * @param {unknown} value Value to be stringified
82 * @param {boolean} beautify Formats json to multiline
83 */
84export const displayValue = (value: unknown, beautify: boolean = false) => {
85 const { json } = serialize(value)
86β
87 return JSON.stringify(json, null, beautify ? 2 : undefined)
88}
89β
90// Sorting functions
91type SortFn = (a: Query, b: Query) => number
92β
93const getStatusRank = (q: Query) =>
94 q.state.fetchStatus !== 'idle'
95 ? 0
96 : !q.getObserversCount()
97 ? 3
98 : q.isStale()
99 ? 2
100 : 1
101β
102const queryHashSort: SortFn = (a, b) => a.queryHash.localeCompare(b.queryHash)
103β
104const dateSort: SortFn = (a, b) =>
105 a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1
106β
107const statusAndDateSort: SortFn = (a, b) => {
108 if (getStatusRank(a) === getStatusRank(b)) {
109 return dateSort(a, b)
110 }
111β
112 return getStatusRank(a) > getStatusRank(b) ? 1 : -1
113}
114β
115export const sortFns: Record<string, SortFn> = {
116 status: statusAndDateSort,
117 'query hash': queryHashSort,
118 'last updated': dateSort,
119}
120β
121type MutationSortFn = (a: Mutation, b: Mutation) => number
122β
123const getMutationStatusRank = (m: Mutation) =>
124 m.state.isPaused
125 ? 0
126 : m.state.status === 'error'
127 ? 2
128 : m.state.status === 'pending'
129 ? 1
130 : 3
131β
132const mutationDateSort: MutationSortFn = (a, b) =>
133 a.state.submittedAt < b.state.submittedAt ? 1 : -1
134β
135const mutationStatusSort: MutationSortFn = (a, b) => {
136 if (getMutationStatusRank(a) === getMutationStatusRank(b)) {
137 return mutationDateSort(a, b)
138 }
139β
140 return getMutationStatusRank(a) > getMutationStatusRank(b) ? 1 : -1
141}
142β
143export const mutationSortFns: Record<string, MutationSortFn> = {
144 status: mutationStatusSort,
145 'last updated': mutationDateSort,
146}
147β
148export const convertRemToPixels = (rem: number) => {
149 return rem * parseFloat(getComputedStyle(document.documentElement).fontSize)
150}
151β
152export const getPreferredColorScheme = () => {
153 const [colorScheme, setColorScheme] = createSignal<'light' | 'dark'>('dark')
154β
155 onMount(() => {
156 const query = window.matchMedia('(prefers-color-scheme: dark)')
157 setColorScheme(query.matches ? 'dark' : 'light')
158 const listener = (e: MediaQueryListEvent) => {
159 setColorScheme(e.matches ? 'dark' : 'light')
160 }
161 query.addEventListener('change', listener)
162 onCleanup(() => query.removeEventListener('change', listener))
163 })
164β
165 return colorScheme
166}
167β
168/**
169 * updates nested data by path
170 *
171 * @param {unknown} oldData Data to be updated
172 * @param {Array<string>} updatePath Path to the data to be updated
173 * @param {unknown} value New value
174 */
175export const updateNestedDataByPath = (
176 oldData: unknown,
177 updatePath: Array<string>,
178 value: unknown,
179): any => {
180 if (updatePath.length === 0) {
181 return value
182 }
183β
184 if (oldData instanceof Map) {
185 const newData = new Map(oldData)
186β
187 if (updatePath.length === 1) {
188 newData.set(updatePath[0], value)
189 return newData
190 }
191β
192 const [head, ...tail] = updatePath
193 newData.set(head, updateNestedDataByPath(newData.get(head), tail, value))
194 return newData
195 }
196β
197 if (oldData instanceof Set) {
198 const setAsArray = updateNestedDataByPath(
199 Array.from(oldData),
200 updatePath,
201 value,
202 )
203β
204 return new Set(setAsArray)
205 }
206β
207 if (Array.isArray(oldData)) {
208 const newData = [...oldData]
209β
210 if (updatePath.length === 1) {
211 // @ts-expect-error
212 newData[updatePath[0]] = value
213 return newData
214 }
215β
216 const [head, ...tail] = updatePath
217 // @ts-expect-error
218 newData[head] = updateNestedDataByPath(newData[head], tail, value)
219β
220 return newData
221 }
222β
223 if (oldData instanceof Object) {
224 const newData = { ...oldData }
225β
226 if (updatePath.length === 1) {
227 // @ts-expect-error
228 newData[updatePath[0]] = value
229 return newData
230 }
231β
232 const [head, ...tail] = updatePath
233 // @ts-expect-error
234 newData[head] = updateNestedDataByPath(newData[head], tail, value)
235β
236 return newData
237 }
238β
239 return oldData
240}
241β
242/**
243 * Deletes nested data by path
244 *
245 * @param {unknown} oldData Data to be updated
246 * @param {Array<string>} deletePath Path to the data to be deleted
247 * @returns newData without the deleted items by path
248 */
249export const deleteNestedDataByPath = (
250 oldData: unknown,
251 deletePath: Array<string>,
252): any => {
253 if (oldData instanceof Map) {
254 const newData = new Map(oldData)
255β
256 if (deletePath.length === 1) {
257 newData.delete(deletePath[0])
258 return newData
259 }
260β
261 const [head, ...tail] = deletePath
262 newData.set(head, deleteNestedDataByPath(newData.get(head), tail))
263 return newData
264 }
265β
266 if (oldData instanceof Set) {
267 const setAsArray = deleteNestedDataByPath(Array.from(oldData), deletePath)
268 return new Set(setAsArray)
269 }
270β
271 if (Array.isArray(oldData)) {
272 const newData = [...oldData]
273β
274 if (deletePath.length === 1) {
275 return newData.filter((_, idx) => idx.toString() !== deletePath[0])
276 }
277β
278 const [head, ...tail] = deletePath
279β
280 // @ts-expect-error
281 newData[head] = deleteNestedDataByPath(newData[head], tail)
282β
283 return newData
284 }
285β
286 if (oldData instanceof Object) {
287 const newData = { ...oldData }
288β
289 if (deletePath.length === 1) {
290 // @ts-expect-error
291 delete newData[deletePath[0]]
292 return newData
293 }
294β
295 const [head, ...tail] = deletePath
296 // @ts-expect-error
297 newData[head] = deleteNestedDataByPath(newData[head], tail)
298β
299 return newData
300 }
301β
302 return oldData
303}
304β
305// Sets up the goober stylesheet
306// Adds a nonce to the style tag if needed
307export const setupStyleSheet = (nonce?: string, target?: ShadowRoot) => {
308 if (!nonce) return
309 const styleExists =
310 document.querySelector('#_goober') || target?.querySelector('#_goober')
311β
312 if (styleExists) return
313 const styleTag = document.createElement('style')
314 const textNode = document.createTextNode('')
315 styleTag.appendChild(textNode)
316 styleTag.id = '_goober'
317 styleTag.setAttribute('nonce', nonce)
318 if (target) {
319 target.appendChild(styleTag)
320 } else {
321 document.head.appendChild(styleTag)
322 }
323}