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β
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'] | undefined
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 const diff = b.state.dataUpdatedAt - a.state.dataUpdatedAt
106 return diff < 0 ? -1 : diff > 0 ? 1 : 0
107}
108β
109const statusAndDateSort: SortFn = (a, b) => {
110 if (getStatusRank(a) === getStatusRank(b)) {
111 return dateSort(a, b)
112 }
113β
114 return getStatusRank(a) > getStatusRank(b) ? 1 : -1
115}
116β
117export const sortFns: Record<string, SortFn> = {
118 status: statusAndDateSort,
119 'query hash': queryHashSort,
120 'last updated': dateSort,
121}
122β
123type MutationSortFn = (a: Mutation, b: Mutation) => number
124β
125const getMutationStatusRank = (m: Mutation) =>
126 m.state.isPaused
127 ? 0
128 : m.state.status === 'error'
129 ? 2
130 : m.state.status === 'pending'
131 ? 1
132 : 3
133β
134const mutationDateSort: MutationSortFn = (a, b) =>
135 a.state.submittedAt < b.state.submittedAt ? 1 : -1
136β
137const mutationStatusSort: MutationSortFn = (a, b) => {
138 if (getMutationStatusRank(a) === getMutationStatusRank(b)) {
139 return mutationDateSort(a, b)
140 }
141β
142 return getMutationStatusRank(a) > getMutationStatusRank(b) ? 1 : -1
143}
144β
145export const mutationSortFns: Record<string, MutationSortFn> = {
146 status: mutationStatusSort,
147 'last updated': mutationDateSort,
148}
149β
150export const convertRemToPixels = (rem: number) => {
151 return rem * parseFloat(getComputedStyle(document.documentElement).fontSize)
152}
153β
154export const getPreferredColorScheme = () => {
155 const [colorScheme, setColorScheme] = createSignal<'light' | 'dark'>('dark')
156β
157 onMount(() => {
158 const query = window.matchMedia('(prefers-color-scheme: dark)')
159 setColorScheme(query.matches ? 'dark' : 'light')
160 const listener = (e: MediaQueryListEvent) => {
161 setColorScheme(e.matches ? 'dark' : 'light')
162 }
163 query.addEventListener('change', listener)
164 onCleanup(() => query.removeEventListener('change', listener))
165 })
166β
167 return colorScheme
168}
169β
170/**
171 * updates nested data by path
172 *
173 * @param {unknown} oldData Data to be updated
174 * @param {Array<string>} updatePath Path to the data to be updated
175 * @param {unknown} value New value
176 */
177export const updateNestedDataByPath = (
178 oldData: unknown,
179 updatePath: Array<string>,
180 value: unknown,
181): any => {
182 if (updatePath.length === 0) {
183 return value
184 }
185β
186 if (oldData instanceof Map) {
187 const newData = new Map(oldData)
188β
189 if (updatePath.length === 1) {
190 newData.set(updatePath[0], value)
191 return newData
192 }
193β
194 const [head, ...tail] = updatePath
195 newData.set(head, updateNestedDataByPath(newData.get(head), tail, value))
196 return newData
197 }
198β
199 if (oldData instanceof Set) {
200 const setAsArray = updateNestedDataByPath(
201 Array.from(oldData),
202 updatePath,
203 value,
204 )
205β
206 return new Set(setAsArray)
207 }
208β
209 if (Array.isArray(oldData)) {
210 const newData = [...oldData]
211β
212 if (updatePath.length === 1) {
213 // @ts-expect-error
214 newData[updatePath[0]] = value
215 return newData
216 }
217β
218 const [head, ...tail] = updatePath
219 // @ts-expect-error
220 newData[head] = updateNestedDataByPath(newData[head], tail, value)
221β
222 return newData
223 }
224β
225 if (oldData instanceof Object) {
226 const newData = { ...oldData }
227β
228 if (updatePath.length === 1) {
229 // @ts-expect-error
230 newData[updatePath[0]] = value
231 return newData
232 }
233β
234 const [head, ...tail] = updatePath
235 // @ts-expect-error
236 newData[head] = updateNestedDataByPath(newData[head], tail, value)
237β
238 return newData
239 }
240β
241 return oldData
242}
243β
244/**
245 * Deletes nested data by path
246 *
247 * @param {unknown} oldData Data to be updated
248 * @param {Array<string>} deletePath Path to the data to be deleted
249 * @returns newData without the deleted items by path
250 */
251export const deleteNestedDataByPath = (
252 oldData: unknown,
253 deletePath: Array<string>,
254): any => {
255 if (oldData instanceof Map) {
256 const newData = new Map(oldData)
257β
258 if (deletePath.length === 1) {
259 newData.delete(deletePath[0])
260 return newData
261 }
262β
263 const [head, ...tail] = deletePath
264 newData.set(head, deleteNestedDataByPath(newData.get(head), tail))
265 return newData
266 }
267β
268 if (oldData instanceof Set) {
269 const setAsArray = deleteNestedDataByPath(Array.from(oldData), deletePath)
270 return new Set(setAsArray)
271 }
272β
273 if (Array.isArray(oldData)) {
274 const newData = [...oldData]
275β
276 if (deletePath.length === 1) {
277 return newData.filter((_, idx) => idx.toString() !== deletePath[0])
278 }
279β
280 const [head, ...tail] = deletePath
281β
282 // @ts-expect-error
283 newData[head] = deleteNestedDataByPath(newData[head], tail)
284β
285 return newData
286 }
287β
288 if (oldData instanceof Object) {
289 const newData = { ...oldData }
290β
291 if (deletePath.length === 1) {
292 // @ts-expect-error
293 delete newData[deletePath[0]]
294 return newData
295 }
296β
297 const [head, ...tail] = deletePath
298 // @ts-expect-error
299 newData[head] = deleteNestedDataByPath(newData[head], tail)
300β
301 return newData
302 }
303β
304 return oldData
305}
306β
307// Sets up the goober stylesheet
308// Adds a nonce to the style tag if needed
309export const setupStyleSheet = (nonce?: string, target?: ShadowRoot) => {
310 if (!nonce)
311 return // Goober reads window.__nonce__ every time it creates or accesses its style
312 // element (el.nonce = window.__nonce__). Without this, goober overwrites the
313 // nonce we set on the pre-created element with undefined, clearing it.
314 ;(window as any).__nonce__ = nonce
315β
316 const root = target ?? document.head
317 if (root.querySelector('#_goober')) return
318 const styleTag = document.createElement('style')
319 const textNode = document.createTextNode('')
320 styleTag.appendChild(textNode)
321 styleTag.id = '_goober'
322 styleTag.setAttribute('nonce', nonce)
323 root.appendChild(styleTag)
324}