Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

devtools.tsx

813 lines24.1 KB

1// @ts-nocheck
2​
3import React from 'react'
4import { matchSorter } from 'match-sorter'
5import { useQueryClient } from '../react'
6import useLocalStorage from './useLocalStorage'
7import { useSafeState, isStale } from './utils'
8​
9import {
10 Panel,
11 QueryKeys,
12 QueryKey,
13 Button,
14 Code,
15 Input,
16 Select,
17 ActiveQueryPanel,
18} from './styledComponents'
19import { ThemeProvider } from './theme'
20import { getQueryStatusLabel, getQueryStatusColor } from './utils'
21import Explorer from './Explorer'
22import Logo from './Logo'
23​
24interface DevtoolsOptions {
25 /**
26 * Set this true if you want the dev tools to default to being open
27 */
28 initialIsOpen?: boolean
29 /**
30 * Use this to add props to the panel. For example, you can add className, style (merge and override default style), etc.
31 */
32 panelProps?: React.DetailedHTMLProps<
33 React.HTMLAttributes<HTMLDivElement>,
34 HTMLDivElement
35 >
36 /**
37 * 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.
38 */
39 closeButtonProps?: React.DetailedHTMLProps<
40 React.ButtonHTMLAttributes<HTMLButtonElement>,
41 HTMLButtonElement
42 >
43 /**
44 * Use this to add props to the toggle button. For example, you can add className, style (merge and override default style), onClick (extend default handler), etc.
45 */
46 toggleButtonProps?: React.DetailedHTMLProps<
47 React.ButtonHTMLAttributes<HTMLButtonElement>,
48 HTMLButtonElement
49 >
50 /**
51 * The position of the React Query logo to open and close the devtools panel.
52 * Defaults to 'bottom-left'.
53 */
54 position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
55 /**
56 * Use this to render the devtools inside a different type of container element for a11y purposes.
57 * Any string which corresponds to a valid intrinsic JSX element is allowed.
58 * Defaults to 'footer'.
59 */
60 containerElement?: string | any
62​
63interface DevtoolsPanelOptions {
64 /**
65 * The standard React style object used to style a component with inline styles
66 */
67 style?: React.CSSProperties
68 /**
69 * The standard React className property used to style a component with classes
70 */
71 className?: string
73​
74const isServer = typeof window === 'undefined'
75​
76const theme = {
77 background: '#0b1521',
78 backgroundAlt: '#132337',
79 foreground: 'white',
80 gray: '#3f4e60',
81 grayAlt: '#222e3e',
82 inputBackgroundColor: '#fff',
83 inputTextColor: '#000',
84 success: '#00ab52',
85 danger: '#ff0085',
86 active: '#006bff',
87 warning: '#ffb200',
89​
90export function ReactQueryDevtools({
91 initialIsOpen,
92 panelProps = {},
93 closeButtonProps = {},
94 toggleButtonProps = {},
95 position = 'bottom-left',
96 containerElement: Container = 'footer',
97}: DevtoolsOptions): React.ReactElement {
98 const rootRef = React.useRef()
99 const panelRef = React.useRef()
100 const [isOpen, setIsOpen] = useLocalStorage(
101 'reactQueryDevtoolsOpen',
102 initialIsOpen
103 )
104 const [devtoolsHeight, setDevtoolsHeight] = useLocalStorage(
105 'reactQueryDevtoolsHeight',
106 null
107 )
108 const [isResolvedOpen, setIsResolvedOpen] = useSafeState(false)
109 const [isResizing, setIsResizing] = useSafeState(false)
110​
111 const handleDragStart = (panelElement, startEvent) => {
112 if (startEvent.button !== 0) return // Only allow left click for drag
113​
114 setIsResizing(true)
115​
116 const dragInfo = {
117 originalHeight: panelElement.getBoundingClientRect().height,
118 pageY: startEvent.pageY,
119 }
120​
121 const run = moveEvent => {
122 const delta = dragInfo.pageY - moveEvent.pageY
123 const newHeight = dragInfo.originalHeight + delta
124​
125 setDevtoolsHeight(newHeight)
126​
127 if (newHeight < 70) {
128 setIsOpen(false)
129 } else {
130 setIsOpen(true)
131 }
132 }
133​
134 const unsub = () => {
135 setIsResizing(false)
136 document.removeEventListener('mousemove', run)
137 document.removeEventListener('mouseUp', unsub)
138 }
139​
140 document.addEventListener('mousemove', run)
141 document.addEventListener('mouseup', unsub)
142 }
143​
144 React.useEffect(() => {
145 setIsResolvedOpen(isOpen)
146 }, [isOpen, isResolvedOpen, setIsResolvedOpen])
147​
148 React[isServer ? 'useEffect' : 'useLayoutEffect'](() => {
149 if (isResolvedOpen) {
150 const previousValue = rootRef.current?.parentElement.style.paddingBottom
151​
152 const run = () => {
153 const containerHeight = panelRef.current?.getBoundingClientRect().height
154 rootRef.current.parentElement.style.paddingBottom = `${containerHeight}px`
155 }
156​
157 run()
158​
159 if (typeof window !== 'undefined') {
160 window.addEventListener('resize', run)
161​
162 return () => {
163 window.removeEventListener('resize', run)
164 rootRef.current.parentElement.style.paddingBottom = previousValue
165 }
166 }
167 }
168 }, [isResolvedOpen])
169​
170 const { style: panelStyle = {}, ...otherPanelProps } = panelProps
171​
172 const {
173 style: closeButtonStyle = {},
174 onClick: onCloseClick,
175 ...otherCloseButtonProps
176 } = closeButtonProps
177​
178 const {
179 style: toggleButtonStyle = {},
180 onClick: onToggleClick,
181 ...otherToggleButtonProps
182 } = toggleButtonProps
183​
184 return (
185 <Container ref={rootRef} className="ReactQueryDevtools">
186 <ThemeProvider theme={theme}>
187 <ReactQueryDevtoolsPanel
188 ref={panelRef}
189 {...otherPanelProps}
190 style={{
191 position: 'fixed',
192 bottom: '0',
193 right: '0',
194 zIndex: '99999',
195 width: '100%',
196 height: devtoolsHeight ?? 500,
197 maxHeight: '90%',
198 boxShadow: '0 0 20px rgba(0,0,0,.3)',
199 borderTop: `1px solid ${theme.gray}`,
200 transformOrigin: 'top',
201 ...panelStyle,
202 ...(isResizing
203 ? {
204 transition: `none`,
205 }
206 : { transition: `all .2s ease` }),
207 ...(isResolvedOpen
208 ? {
209 opacity: 1,
210 pointerEvents: 'all',
211 transform: `translateY(0) scale(1)`,
212 }
213 : {
214 opacity: 0,
215 pointerEvents: 'none',
216 transform: `translateY(15px) scale(1.02)`,
217 }),
218 }}
219 setIsOpen={setIsOpen}
220 handleDragStart={e => handleDragStart(panelRef.current, e)}
221 />
222 {isResolvedOpen ? (
223 <Button
224 type="button"
225 {...otherCloseButtonProps}
226 onClick={() => {
227 setIsOpen(false)
228 onCloseClick && onCloseClick()
229 }}
230 style={{
231 position: 'fixed',
232 zIndex: '99999',
233 margin: '.5rem',
234 bottom: 0,
235 ...(position === 'top-right'
236 ? {
237 right: '0',
238 }
239 : position === 'top-left'
240 ? {
241 left: '0',
242 }
243 : position === 'bottom-right'
244 ? {
245 right: '0',
246 }
247 : {
248 left: '0',
249 }),
250 ...closeButtonStyle,
251 }}
252 >
253 Close
254 </Button>
255 ) : null}
256 </ThemeProvider>
257 {!isResolvedOpen ? (
258 <button
259 type="button"
260 {...otherToggleButtonProps}
261 aria-label="Open React Query Devtools"
262 onClick={() => {
263 setIsOpen(true)
264 onToggleClick && onToggleClick()
265 }}
266 style={{
267 background: 'none',
268 border: 0,
269 padding: 0,
270 position: 'fixed',
271 bottom: '0',
272 right: '0',
273 zIndex: '99999',
274 display: 'inline-flex',
275 fontSize: '1.5rem',
276 margin: '.5rem',
277 cursor: 'pointer',
278 width: 'fit-content',
279 ...(position === 'top-right'
280 ? {
281 top: '0',
282 right: '0',
283 }
284 : position === 'top-left'
285 ? {
286 top: '0',
287 left: '0',
288 }
289 : position === 'bottom-right'
290 ? {
291 bottom: '0',
292 right: '0',
293 }
294 : {
295 bottom: '0',
296 left: '0',
297 }),
298 ...toggleButtonStyle,
299 }}
300 >
301 <Logo aria-hidden />
302 </button>
303 ) : null}
304 </Container>
305 )
307​
308const getStatusRank = q =>
309 q.state.isFetching ? 0 : !q.observers.length ? 3 : isStale(q) ? 2 : 1
310​
311const sortFns = {
312 'Status > Last Updated': (a, b) =>
313 getStatusRank(a) === getStatusRank(b)
314 ? sortFns['Last Updated'](a, b)
315 : getStatusRank(a) > getStatusRank(b)
316 ? 1
317 : -1,
318 'Query Hash': (a, b) => (a.queryHash > b.queryHash ? 1 : -1),
319 'Last Updated': (a, b) => (a.state.updatedAt < b.state.updatedAt ? 1 : -1),
321​
322export const ReactQueryDevtoolsPanel = React.forwardRef(
323 function ReactQueryDevtoolsPanel(
324 props: DevtoolsPanelOptions,
325 ref
326 ): React.ReactElement {
327 const { setIsOpen, handleDragStart, ...panelProps } = props
328​
329 const queryClient = useQueryClient()
330 const queryCache = queryClient.getQueryCache()
331​
332 const [sort, setSort] = useLocalStorage(
333 'reactQueryDevtoolsSortFn',
334 Object.keys(sortFns)[0]
335 )
336​
337 const [filter, setFilter] = useLocalStorage('reactQueryDevtoolsFilter', '')
338​
339 const [sortDesc, setSortDesc] = useLocalStorage(
340 'reactQueryDevtoolsSortDesc',
341 false
342 )
343​
344 const sortFn = React.useMemo(() => sortFns[sort], [sort])
345​
346 React[isServer ? 'useEffect' : 'useLayoutEffect'](() => {
347 if (!sortFn) {
348 setSort(Object.keys(sortFns)[0])
349 }
350 }, [setSort, sortFn])
351​
352 const [unsortedQueries, setUnsortedQueries] = useSafeState(
353 Object.values(queryCache.findAll())
354 )
355​
356 const [activeQueryHash, setActiveQueryHash] = useLocalStorage(
357 'reactQueryDevtoolsActiveQueryHash',
358 ''
359 )
360​
361 const queries = React.useMemo(() => {
362 const sorted = [...unsortedQueries].sort(sortFn)
363​
364 if (sortDesc) {
365 sorted.reverse()
366 }
367​
368 if (!filter) {
369 return sorted
370 }
371​
372 return matchSorter(sorted, filter, { keys: ['queryHash'] }).filter(
373 d => d.queryHash
374 )
375 }, [sortDesc, sortFn, unsortedQueries, filter])
376​
377 const activeQuery = React.useMemo(() => {
378 return queries.find(query => query.queryHash === activeQueryHash)
379 }, [activeQueryHash, queries])
380​
381 const hasFresh = queries.filter(q => getQueryStatusLabel(q) === 'fresh')
382 .length
383 const hasFetching = queries.filter(
384 q => getQueryStatusLabel(q) === 'fetching'
385 ).length
386 const hasStale = queries.filter(q => getQueryStatusLabel(q) === 'stale')
387 .length
388 const hasInactive = queries.filter(
389 q => getQueryStatusLabel(q) === 'inactive'
390 ).length
391​
392 React.useEffect(() => {
393 return queryCache.subscribe(() => {
394 setUnsortedQueries(Object.values(queryCache.getAll()))
395 })
396 }, [sort, sortFn, sortDesc, setUnsortedQueries, queryCache])
397​
398 return (
399 <ThemeProvider theme={theme}>
400 <Panel
401 ref={ref}
402 className="ReactQueryDevtoolsPanel"
403 {...panelProps}
404 suppressHydrationWarning
405 >
406 <style
407 dangerouslySetInnerHTML={{
408 __html: `
409 .ReactQueryDevtoolsPanel * {
410 scrollbar-color: ${theme.backgroundAlt} ${theme.gray};
411 }
413 .ReactQueryDevtoolsPanel *::-webkit-scrollbar, .ReactQueryDevtoolsPanel scrollbar {
414 width: 1rem;
415 height: 1rem;
416 }
418 .ReactQueryDevtoolsPanel *::-webkit-scrollbar-track, .ReactQueryDevtoolsPanel scrollbar-track {
419 background: ${theme.backgroundAlt};
420 }
422 .ReactQueryDevtoolsPanel *::-webkit-scrollbar-thumb, .ReactQueryDevtoolsPanel scrollbar-thumb {
423 background: ${theme.gray};
424 border-radius: .5rem;
425 border: 3px solid ${theme.backgroundAlt};
426 }
427 `,
428 }}
429 />
430 <div
431 style={{
432 position: 'absolute',
433 left: 0,
434 top: 0,
435 width: '100%',
436 height: '4px',
437 marginBottom: '-4px',
438 cursor: 'row-resize',
439 zIndex: 100000,
440 }}
441 onMouseDown={handleDragStart}
442 ></div>
443 <div
444 style={{
445 flex: '1 1 500px',
446 minHeight: '40%',
447 maxHeight: '100%',
448 overflow: 'auto',
449 borderRight: `1px solid ${theme.grayAlt}`,
450 display: 'flex',
451 flexDirection: 'column',
452 }}
453 >
454 <div
455 style={{
456 padding: '.5rem',
457 background: theme.backgroundAlt,
458 display: 'flex',
459 justifyContent: 'space-between',
460 alignItems: 'center',
461 }}
462 >
463 <Logo
464 aria-hidden
465 style={{
466 marginRight: '.5rem',
467 }}
468 />
469 <div
470 style={{
471 display: 'flex',
472 flexDirection: 'column',
473 }}
474 >
475 <QueryKeys style={{ marginBottom: '.5rem' }}>
476 <QueryKey
477 suppressHydrationWarning
478 style={{
479 background: theme.success,
480 opacity: hasFresh ? 1 : 0.3,
481 }}
482 >
483 fresh <Code suppressHydrationWarning>({hasFresh})</Code>
484 </QueryKey>{' '}
485 <QueryKey
486 suppressHydrationWarning
487 style={{
488 background: theme.active,
489 opacity: hasFetching ? 1 : 0.3,
490 }}
491 >
492 fetching{' '}
493 <Code suppressHydrationWarning>({hasFetching})</Code>
494 </QueryKey>{' '}
495 <QueryKey
496 suppressHydrationWarning
497 style={{
498 background: theme.warning,
499 color: 'black',
500 textShadow: '0',
501 opacity: hasStale ? 1 : 0.3,
502 }}
503 >
504 stale <Code suppressHydrationWarning>({hasStale})</Code>
505 </QueryKey>{' '}
506 <QueryKey
507 suppressHydrationWarning
508 style={{
509 background: theme.gray,
510 opacity: hasInactive ? 1 : 0.3,
511 }}
512 >
513 inactive{' '}
514 <Code suppressHydrationWarning>({hasInactive})</Code>
515 </QueryKey>
516 </QueryKeys>
517 <div
518 style={{
519 display: 'flex',
520 alignItems: 'center',
521 }}
522 >
523 <Input
524 placeholder="Filter"
525 value={filter ?? ''}
526 onChange={e => setFilter(e.target.value)}
527 onKeyDown={e => {
528 if (e.key === 'Escape') setFilter('')
529 }}
530 style={{
531 flex: '1',
532 marginRight: '.5rem',
533 }}
534 />
535 {!filter ? (
536 <>
537 <Select
538 value={sort}
539 onChange={e => setSort(e.target.value)}
540 style={{
541 flex: '1',
542 minWidth: 75,
543 marginRight: '.5rem',
544 }}
545 >
546 {Object.keys(sortFns).map(key => (
547 <option key={key} value={key}>
548 Sort by {key}
549 </option>
550 ))}
551 </Select>
552 <Button
553 type="button"
554 onClick={() => setSortDesc(old => !old)}
555 style={{
556 padding: '.3rem .4rem',
557 }}
558 >
559 {sortDesc ? '⬇ Desc' : '⬆ Asc'}
560 </Button>
561 </>
562 ) : null}
563 </div>
564 </div>
565 </div>
566 <div
567 suppressHydrationWarning
568 style={{
569 overflowY: 'auto',
570 flex: '1',
571 }}
572 >
573 {queries.map((query, i) => (
574 <div
575 suppressHydrationWarning
576 key={query.queryHash || i}
577 onClick={() =>
578 setActiveQueryHash(
579 activeQueryHash === query.queryHash ? '' : query.queryHash
580 )
581 }
582 style={{
583 display: 'flex',
584 borderBottom: `solid 1px ${theme.grayAlt}`,
585 cursor: 'pointer',
586 background:
587 query === activeQuery
588 ? 'rgba(255,255,255,.1)'
589 : undefined,
590 }}
591 >
592 <div
593 suppressHydrationWarning
594 style={{
595 flex: '0 0 auto',
596 width: '2rem',
597 height: '2rem',
598 background: getQueryStatusColor(query, theme),
599 display: 'flex',
600 alignItems: 'center',
601 justifyContent: 'center',
602 fontWeight: 'bold',
603 textShadow:
604 getQueryStatusLabel(query) === 'stale'
605 ? '0'
606 : '0 0 10px black',
607 color:
608 getQueryStatusLabel(query) === 'stale'
609 ? 'black'
610 : 'white',
611 }}
612 >
613 {query.observers.length}
614 </div>
615 <Code
616 suppressHydrationWarning
617 style={{
618 padding: '.5rem',
619 }}
620 >
621 {`${query.queryHash}`}
622 </Code>
623 </div>
624 ))}
625 </div>
626 </div>
627 {activeQuery ? (
628 <ActiveQueryPanel>
629 <div
630 style={{
631 padding: '.5rem',
632 background: theme.backgroundAlt,
633 position: 'sticky',
634 top: 0,
635 zIndex: 1,
636 }}
637 >
638 Query Details
639 </div>
640 <div
641 style={{
642 padding: '.5rem',
643 }}
644 >
645 <div
646 style={{
647 marginBottom: '.5rem',
648 display: 'flex',
649 alignItems: 'stretch',
650 justifyContent: 'space-between',
651 }}
652 >
653 <Code
654 style={{
655 lineHeight: '1.8rem',
656 }}
657 >
658 <pre
659 style={{
660 margin: 0,
661 padding: 0,
662 overflow: 'auto',
663 }}
664 >
665 {JSON.stringify(activeQuery.queryKey, null, 2)}
666 </pre>
667 </Code>
668 <span
669 style={{
670 padding: '0.3rem .6rem',
671 borderRadius: '0.4rem',
672 fontWeight: 'bold',
673 textShadow: '0 2px 10px black',
674 background: getQueryStatusColor(activeQuery, theme),
675 flexShrink: 0,
676 }}
677 >
678 {getQueryStatusLabel(activeQuery)}
679 </span>
680 </div>
681 <div
682 style={{
683 marginBottom: '.5rem',
684 display: 'flex',
685 alignItems: 'center',
686 justifyContent: 'space-between',
687 }}
688 >
689 Observers: <Code>{activeQuery.observers.length}</Code>
690 </div>
691 <div
692 style={{
693 display: 'flex',
694 alignItems: 'center',
695 justifyContent: 'space-between',
696 }}
697 >
698 Last Updated:{' '}
699 <Code>
700 {new Date(
701 activeQuery.state.dataUpdatedAt
702 ).toLocaleTimeString()}
703 </Code>
704 </div>
705 </div>
706 <div
707 style={{
708 background: theme.backgroundAlt,
709 padding: '.5rem',
710 position: 'sticky',
711 top: 0,
712 zIndex: 1,
713 }}
714 >
715 Actions
716 </div>
717 <div
718 style={{
719 padding: '0.5rem',
720 }}
721 >
722 <Button
723 type="button"
724 onClick={() => activeQuery.fetch()}
725 disabled={activeQuery.state.isFetching}
726 style={{
727 background: theme.active,
728 }}
729 >
730 Refetch
731 </Button>{' '}
732 <Button
733 type="button"
734 onClick={() => queryClient.invalidateQueries(activeQuery)}
735 style={{
736 background: theme.warning,
737 color: theme.inputTextColor,
738 }}
739 >
740 Invalidate
741 </Button>{' '}
742 <Button
743 type="button"
744 onClick={() => queryClient.resetQueries(activeQuery)}
745 style={{
746 background: theme.gray,
747 }}
748 >
749 Reset
750 </Button>{' '}
751 <Button
752 type="button"
753 onClick={() => queryClient.removeQueries(activeQuery)}
754 style={{
755 background: theme.danger,
756 }}
757 >
758 Remove
759 </Button>
760 </div>
761 <div
762 style={{
763 background: theme.backgroundAlt,
764 padding: '.5rem',
765 position: 'sticky',
766 top: 0,
767 zIndex: 1,
768 }}
769 >
770 Data Explorer
771 </div>
772 <div
773 style={{
774 padding: '.5rem',
775 }}
776 >
777 <Explorer
778 label="Data"
779 value={activeQuery?.state?.data}
780 defaultExpanded={{}}
781 />
782 </div>
783 <div
784 style={{
785 background: theme.backgroundAlt,
786 padding: '.5rem',
787 position: 'sticky',
788 top: 0,
789 zIndex: 1,
790 }}
791 >
792 Query Explorer
793 </div>
794 <div
795 style={{
796 padding: '.5rem',
797 }}
798 >
799 <Explorer
800 label="Query"
801 value={activeQuery}
802 defaultExpanded={{
803 queryKey: true,
804 }}
805 />
806 </div>
807 </ActiveQueryPanel>
808 ) : null}
809 </Panel>
810 </ThemeProvider>
811 )
812 }