Open History to see the last commit
1import React from 'react'
2import type { QueryClient } from '@tanstack/react-query'
3import { useQueryClient, onlineManager } from '@tanstack/react-query'
4import { rankItem } from '@tanstack/match-sorter-utils'
5β
6import { Panel, Button, Input, Select } from '../styledComponents'
7import useSubscribeToQueryCache from '../useSubscribeToQueryCache'
8import QueryStatusCount from './Header/QueryStatusCount'
9import QueryRow from './QueryRow'
10import ActiveQuery from './ActiveQuery'
11import type { Side } from '../utils'
12import { sortFns, getResizeHandleStyle, defaultPanelSize } from '../utils'
13import { ThemeProvider, defaultTheme as theme } from '../theme'
14import type { DevToolsErrorType } from '../types'
15import useLocalStorage from '../useLocalStorage'
16import Logo from '../Logo'
17import ScreenReader from '../screenreader'
18β
19interface DevtoolsPanelOptions {
20 /**
21 * The standard React style object used to style a component with inline styles
22 */
23 style?: React.CSSProperties
24 /**
25 * The standard React className property used to style a component with classes
26 */
27 className?: string
28 /**
29 * A boolean variable indicating whether the panel is open or closed
30 */
31 isOpen?: boolean
32 /**
33 * nonce for style element for CSP
34 */
35 styleNonce?: string
36 /**
37 * A function that toggles the open and close state of the panel
38 */
39 setIsOpen: (isOpen: boolean) => void
40 /**
41 * Handles the opening and closing the devtools panel
42 */
43 onDragStart: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
44 /**
45 * The position of the React Query devtools panel.
46 * Defaults to 'bottom'.
47 */
48 position?: Side
49 /**
50 * Handles the panel position select change
51 */
52 onPositionChange?: (side: Side) => void
53 /**
54 * Show a close button inside the panel
55 */
56 showCloseButton?: boolean
57 /**
58 * Use this to add props to the close button. For example, you can add className, style (merge and override default style), onClick (extend default handler), etc.
59 */
60 closeButtonProps?: React.ComponentPropsWithoutRef<'button'>
61 /**
62 * Custom instance of QueryClient
63 */
64 queryClient?: QueryClient
65 /**
66 * Use this so you can define custom errors that can be shown in the devtools.
67 */
68 errorTypes?: DevToolsErrorType[]
69}
70β
71export const ReactQueryDevtoolsPanel = React.forwardRef<
72 HTMLDivElement,
73 DevtoolsPanelOptions
74>(function ReactQueryDevtoolsPanel(props, ref): React.ReactElement {
75 const {
76 isOpen = true,
77 styleNonce,
78 setIsOpen,
79 queryClient,
80 onDragStart,
81 onPositionChange,
82 showCloseButton,
83 position,
84 closeButtonProps = {},
85 errorTypes = [],
86 ...panelProps
87 } = props
88β
89 const { onClick: onCloseClick, ...otherCloseButtonProps } = closeButtonProps
90β
91 const client = useQueryClient(queryClient)
92 const queryCache = client.getQueryCache()
93β
94 const [sort, setSort] = useLocalStorage(
95 'reactQueryDevtoolsSortFn',
96 Object.keys(sortFns)[0],
97 )
98β
99 const [filter, setFilter] = useLocalStorage('reactQueryDevtoolsFilter', '')
100β
101 const [baseSort, setBaseSort] = useLocalStorage(
102 'reactQueryDevtoolsBaseSort',
103 1,
104 )
105β
106 const sortFn = React.useMemo(() => sortFns[sort as string], [sort])
107β
108 const queriesCount = useSubscribeToQueryCache(
109 queryCache,
110 () => queryCache.getAll().length,
111 !isOpen,
112 )
113β
114 const [activeQueryHash, setActiveQueryHash] = useLocalStorage(
115 'reactQueryDevtoolsActiveQueryHash',
116 '',
117 )
118β
119 const queries = React.useMemo(() => {
120 const unsortedQueries = queryCache.getAll()
121β
122 if (queriesCount === 0) {
123 return []
124 }
125β
126 const filtered = filter
127 ? unsortedQueries.filter(
128 (item) => rankItem(item.queryHash, filter).passed,
129 )
130 : [...unsortedQueries]
131β
132 const sorted = sortFn
133 ? filtered.sort((a, b) => sortFn(a, b) * (baseSort as number))
134 : filtered
135β
136 return sorted
137 }, [baseSort, sortFn, filter, queriesCount, queryCache])
138β
139 const [isMockOffline, setMockOffline] = React.useState(false)
140β
141 return (
142 <ThemeProvider theme={theme}>
143 <Panel
144 ref={ref}
145 className="ReactQueryDevtoolsPanel"
146 aria-label="React Query Devtools Panel"
147 id="ReactQueryDevtoolsPanel"
148 {...panelProps}
149 style={{
150 height: defaultPanelSize,
151 position: 'relative',
152 ...panelProps.style,
153 }}
154 >
155 <style
156 nonce={styleNonce}
157 dangerouslySetInnerHTML={{
158 __html: `
159 .ReactQueryDevtoolsPanel * {
160 scrollbar-color: ${theme.backgroundAlt} ${theme.gray};
161 }
162β
163 .ReactQueryDevtoolsPanel *::-webkit-scrollbar, .ReactQueryDevtoolsPanel scrollbar {
164 width: 1em;
165 height: 1em;
166 }
167β
168 .ReactQueryDevtoolsPanel *::-webkit-scrollbar-track, .ReactQueryDevtoolsPanel scrollbar-track {
169 background: ${theme.backgroundAlt};
170 }
171β
172 .ReactQueryDevtoolsPanel *::-webkit-scrollbar-thumb, .ReactQueryDevtoolsPanel scrollbar-thumb {
173 background: ${theme.gray};
174 border-radius: .5em;
175 border: 3px solid ${theme.backgroundAlt};
176 }
177 `,
178 }}
179 />
180 <div
181 style={getResizeHandleStyle(position)}
182 onMouseDown={onDragStart}
183 ></div>
184β
185 {isOpen && (
186 <div
187 style={{
188 flex: '1 1 500px',
189 minHeight: '40%',
190 maxHeight: '100%',
191 overflow: 'auto',
192 borderRight: `1px solid ${theme.grayAlt}`,
193 display: 'flex',
194 flexDirection: 'column',
195 }}
196 >
197 <div
198 style={{
199 padding: '.5em',
200 background: theme.backgroundAlt,
201 display: 'flex',
202 justifyContent: 'space-between',
203 alignItems: 'center',
204 }}
205 >
206 <button
207 type="button"
208 aria-label="Close React Query Devtools"
209 aria-controls="ReactQueryDevtoolsPanel"
210 aria-haspopup="true"
211 aria-expanded="true"
212 onClick={() => setIsOpen(false)}
213 style={{
214 display: 'inline-flex',
215 background: 'none',
216 border: 0,
217 padding: 0,
218 marginRight: '.5em',
219 cursor: 'pointer',
220 }}
221 >
222 <Logo aria-hidden />
223 <ScreenReader text="Close React Query Devtools" />
224 </button>
225 <div
226 style={{
227 display: 'flex',
228 flexDirection: 'column',
229 }}
230 >
231 <div
232 style={{
233 display: 'flex',
234 justifyContent: 'space-between',
235 alignItems: 'center',
236 marginBottom: '.5em',
237 }}
238 >
239 <QueryStatusCount queryCache={queryCache} />
240 {position && onPositionChange ? (
241 <Select
242 aria-label="Panel position"
243 value={position}
244 style={{ marginInlineStart: '.5em' }}
245 onChange={(e) => onPositionChange(e.target.value as Side)}
246 >
247 <option value="left">Left</option>
248 <option value="right">Right</option>
249 <option value="top">Top</option>
250 <option value="bottom">Bottom</option>
251 </Select>
252 ) : null}
253 </div>
254 <div
255 style={{
256 display: 'flex',
257 alignItems: 'center',
258 flexWrap: 'wrap',
259 gap: '0.5em',
260 }}
261 >
262 <Input
263 placeholder="Filter"
264 aria-label="Filter by queryhash"
265 value={filter ?? ''}
266 onChange={(e) => setFilter(e.target.value)}
267 onKeyDown={(e) => {
268 if (e.key === 'Escape') setFilter('')
269 }}
270 style={{
271 flex: '1',
272 width: '100%',
273 }}
274 />
275 <Select
276 aria-label="Sort queries"
277 value={sort}
278 onChange={(e) => setSort(e.target.value)}
279 style={{
280 flex: '1',
281 minWidth: 75,
282 marginRight: '.5em',
283 }}
284 >
285 {Object.keys(sortFns).map((key) => (
286 <option key={key} value={key}>
287 Sort by {key}
288 </option>
289 ))}
290 </Select>
291 <Button
292 type="button"
293 onClick={() => setBaseSort((old) => old * -1)}
294 style={{
295 padding: '.3em .4em',
296 marginRight: '.5em',
297 }}
298 >
299 {baseSort === 1 ? 'β¬ Asc' : 'β¬ Desc'}
300 </Button>
301 <Button
302 title="Clear cache"
303 aria-label="Clear cache"
304 type="button"
305 onClick={() => queryCache.clear()}
306 style={{
307 padding: '.3em .4em',
308 marginRight: '.5em',
309 }}
310 >
311 Clear
312 </Button>
313 <Button
314 type="button"
315 onClick={() => {
316 if (isMockOffline) {
317 onlineManager.setOnline(undefined)
318 setMockOffline(false)
319 window.dispatchEvent(new Event('online'))
320 } else {
321 onlineManager.setOnline(false)
322 setMockOffline(true)
323 window.dispatchEvent(new Event('offline'))
324 }
325 }}
326 aria-label={
327 isMockOffline
328 ? 'Restore offline mock'
329 : 'Mock offline behavior'
330 }
331 title={
332 isMockOffline
333 ? 'Restore offline mock'
334 : 'Mock offline behavior'
335 }
336 style={{
337 padding: '0',
338 height: '2em',
339 }}
340 >
341 <svg
342 xmlns="http://www.w3.org/2000/svg"
343 width="2em"
344 height="2em"
345 viewBox="0 0 24 24"
346 stroke={isMockOffline ? theme.danger : 'currentColor'}
347 fill="none"
348 >
349 {isMockOffline ? (
350 <>
351 <path stroke="none" d="M0 0h24v24H0z" fill="none" />
352 <line x1="12" y1="18" x2="12.01" y2="18" />
353 <path d="M9.172 15.172a4 4 0 0 1 5.656 0" />
354 <path d="M6.343 12.343a7.963 7.963 0 0 1 3.864 -2.14m4.163 .155a7.965 7.965 0 0 1 3.287 2" />
355 <path d="M3.515 9.515a12 12 0 0 1 3.544 -2.455m3.101 -.92a12 12 0 0 1 10.325 3.374" />
356 <line x1="3" y1="3" x2="21" y2="21" />
357 </>
358 ) : (
359 <>
360 <path stroke="none" d="M0 0h24v24H0z" fill="none" />
361 <line x1="12" y1="18" x2="12.01" y2="18" />
362 <path d="M9.172 15.172a4 4 0 0 1 5.656 0" />
363 <path d="M6.343 12.343a8 8 0 0 1 11.314 0" />
364 <path d="M3.515 9.515c4.686 -4.687 12.284 -4.687 17 0" />
365 </>
366 )}
367 </svg>
368 <ScreenReader
369 text={
370 isMockOffline
371 ? 'Restore offline mock'
372 : 'Mock offline behavior'
373 }
374 />
375 </Button>
376 </div>
377 </div>
378 </div>
379 <div
380 style={{
381 overflowY: 'auto',
382 flex: '1',
383 }}
384 >
385 {queries.map((query) => {
386 return (
387 <QueryRow
388 queryKey={query.queryKey}
389 activeQueryHash={activeQueryHash}
390 setActiveQueryHash={setActiveQueryHash}
391 key={query.queryHash}
392 queryCache={queryCache}
393 />
394 )
395 })}
396 </div>
397 </div>
398 )}
399β
400 {activeQueryHash && isOpen ? (
401 <ActiveQuery
402 activeQueryHash={activeQueryHash}
403 queryCache={queryCache}
404 queryClient={client}
405 errorTypes={errorTypes}
406 />
407 ) : null}
408β
409 {showCloseButton ? (
410 <Button
411 type="button"
412 aria-controls="ReactQueryDevtoolsPanel"
413 aria-haspopup="true"
414 aria-expanded="true"
415 {...(otherCloseButtonProps as Record<string, unknown>)}
416 style={{
417 position: 'absolute',
418 zIndex: 99999,
419 margin: '.5em',
420 bottom: 0,
421 left: 0,
422 ...otherCloseButtonProps.style,
423 }}
424 onClick={(e) => {
425 setIsOpen(false)
426 onCloseClick?.(e)
427 }}
428 >
429 Close
430 </Button>
431 ) : null}
432 </Panel>
433 </ThemeProvider>
434 )
435})
436β
437ReactQueryDevtoolsPanel.displayName = 'ReactQueryDevtoolsPanel'
438β
439export default ReactQueryDevtoolsPanel