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

devtools.tsx

848 lines25.5 KB

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