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

devtools.tsx

873 lines25.7 KB

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