Open History to see the last commit
1import React from 'react'
2import { useSyncExternalStore } from '../reactjs/useSyncExternalStore'
3import {
4 Query,
5 useQueryClient,
6 onlineManager,
7 notifyManager,
8 QueryCache,
9 QueryClient,
10 QueryKey as QueryKeyType,
11 ContextOptions,
12} from 'react-query'
13import { matchSorter } from 'match-sorter'
14import useLocalStorage from './useLocalStorage'
15import { useIsMounted } from './utils'
16β
17import {
18 Panel,
19 QueryKeys,
20 QueryKey,
21 Button,
22 Code,
23 Input,
24 Select,
25 ActiveQueryPanel,
26} from './styledComponents'
27import { ThemeProvider, defaultTheme as theme } from './theme'
28import { getQueryStatusLabel, getQueryStatusColor } from './utils'
29import Explorer from './Explorer'
30import Logo from './Logo'
31import { noop } from '../core/utils'
32β
33interface DevtoolsOptions extends ContextOptions {
34 /**
35 * Set this true if you want the dev tools to default to being open
36 */
37 initialIsOpen?: boolean
38 /**
39 * Use this to add props to the panel. For example, you can add className, style (merge and override default style), etc.
40 */
41 panelProps?: React.DetailedHTMLProps<
42 React.HTMLAttributes<HTMLDivElement>,
43 HTMLDivElement
44 >
45 /**
46 * 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.
47 */
48 closeButtonProps?: React.DetailedHTMLProps<
49 React.ButtonHTMLAttributes<HTMLButtonElement>,
50 HTMLButtonElement
51 >
52 /**
53 * 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.
54 */
55 toggleButtonProps?: React.DetailedHTMLProps<
56 React.ButtonHTMLAttributes<HTMLButtonElement>,
57 HTMLButtonElement
58 >
59 /**
60 * The position of the React Query logo to open and close the devtools panel.
61 * Defaults to 'bottom-left'.
62 */
63 position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
64 /**
65 * Use this to render the devtools inside a different type of container element for a11y purposes.
66 * Any string which corresponds to a valid intrinsic JSX element is allowed.
67 * Defaults to 'aside'.
68 */
69 containerElement?: string | any
70 /**
71 * nonce for style element for CSP
72 */
73 styleNonce?: string
74}
75β
76interface DevtoolsPanelOptions extends ContextOptions {
77 /**
78 * The standard React style object used to style a component with inline styles
79 */
80 style?: React.CSSProperties
81 /**
82 * The standard React className property used to style a component with classes
83 */
84 className?: string
85 /**
86 * A boolean variable indicating whether the panel is open or closed
87 */
88 isOpen?: boolean
89 /**
90 * nonce for style element for CSP
91 */
92 styleNonce?: string
93 /**
94 * A function that toggles the open and close state of the panel
95 */
96 setIsOpen: (isOpen: boolean) => void
97 /**
98 * Handles the opening and closing the devtools panel
99 */
100 handleDragStart: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
101}
102β
103const isServer = typeof window === 'undefined'
104β
105export function ReactQueryDevtools({
106 initialIsOpen,
107 panelProps = {},
108 closeButtonProps = {},
109 toggleButtonProps = {},
110 position = 'bottom-left',
111 containerElement: Container = 'aside',
112 context,
113 styleNonce,
114}: DevtoolsOptions): React.ReactElement | null {
115 const rootRef = React.useRef<HTMLDivElement>(null)
116 const panelRef = React.useRef<HTMLDivElement>(null)
117 const [isOpen, setIsOpen] = useLocalStorage(
118 'reactQueryDevtoolsOpen',
119 initialIsOpen
120 )
121 const [devtoolsHeight, setDevtoolsHeight] = useLocalStorage<number | null>(
122 'reactQueryDevtoolsHeight',
123 null
124 )
125 const [isResolvedOpen, setIsResolvedOpen] = React.useState(false)
126 const [isResizing, setIsResizing] = React.useState(false)
127 const isMounted = useIsMounted()
128β
129 const handleDragStart = (
130 panelElement: HTMLDivElement | null,
131 startEvent: React.MouseEvent<HTMLDivElement, MouseEvent>
132 ) => {
133 if (startEvent.button !== 0) return // Only allow left click for drag
134β
135 setIsResizing(true)
136β
137 const dragInfo = {
138 originalHeight: panelElement?.getBoundingClientRect().height ?? 0,
139 pageY: startEvent.pageY,
140 }
141β
142 const run = (moveEvent: MouseEvent) => {
143 const delta = dragInfo.pageY - moveEvent.pageY
144 const newHeight = dragInfo.originalHeight + delta
145β
146 setDevtoolsHeight(newHeight)
147β
148 if (newHeight < 70) {
149 setIsOpen(false)
150 } else {
151 setIsOpen(true)
152 }
153 }
154β
155 const unsub = () => {
156 setIsResizing(false)
157 document.removeEventListener('mousemove', run)
158 document.removeEventListener('mouseUp', unsub)
159 }
160β
161 document.addEventListener('mousemove', run)
162 document.addEventListener('mouseup', unsub)
163 }
164β
165 React.useEffect(() => {
166 setIsResolvedOpen(isOpen ?? false)
167 }, [isOpen, isResolvedOpen, setIsResolvedOpen])
168β
169 // Toggle panel visibility before/after transition (depending on direction).
170 // Prevents focusing in a closed panel.
171 React.useEffect(() => {
172 const ref = panelRef.current
173 if (ref) {
174 const handlePanelTransitionStart = () => {
175 if (isResolvedOpen) {
176 ref.style.visibility = 'visible'
177 }
178 }
179β
180 const handlePanelTransitionEnd = () => {
181 if (!isResolvedOpen) {
182 ref.style.visibility = 'hidden'
183 }
184 }
185β
186 ref.addEventListener('transitionstart', handlePanelTransitionStart)
187 ref.addEventListener('transitionend', handlePanelTransitionEnd)
188β
189 return () => {
190 ref.removeEventListener('transitionstart', handlePanelTransitionStart)
191 ref.removeEventListener('transitionend', handlePanelTransitionEnd)
192 }
193 }
194 }, [isResolvedOpen])
195β
196 React[isServer ? 'useEffect' : 'useLayoutEffect'](() => {
197 if (isResolvedOpen) {
198 const previousValue = rootRef.current?.parentElement?.style.paddingBottom
199β
200 const run = () => {
201 const containerHeight = panelRef.current?.getBoundingClientRect().height
202 if (rootRef.current?.parentElement) {
203 rootRef.current.parentElement.style.paddingBottom = `${containerHeight}px`
204 }
205 }
206β
207 run()
208β
209 if (typeof window !== 'undefined') {
210 window.addEventListener('resize', run)
211β
212 return () => {
213 window.removeEventListener('resize', run)
214 if (
215 rootRef.current?.parentElement &&
216 typeof previousValue === 'string'
217 ) {
218 rootRef.current.parentElement.style.paddingBottom = previousValue
219 }
220 }
221 }
222 }
223 }, [isResolvedOpen])
224β
225 const { style: panelStyle = {}, ...otherPanelProps } = panelProps
226β
227 const {
228 style: closeButtonStyle = {},
229 onClick: onCloseClick,
230 ...otherCloseButtonProps
231 } = closeButtonProps
232β
233 const {
234 style: toggleButtonStyle = {},
235 onClick: onToggleClick,
236 ...otherToggleButtonProps
237 } = toggleButtonProps
238β
239 // Do not render on the server
240 if (!isMounted()) return null
241β
242 return (
243 <Container
244 ref={rootRef}
245 className="ReactQueryDevtools"
246 aria-label="React Query Devtools"
247 >
248 <ThemeProvider theme={theme}>
249 <ReactQueryDevtoolsPanel
250 ref={panelRef as any}
251 context={context}
252 styleNonce={styleNonce}
253 {...otherPanelProps}
254 style={{
255 position: 'fixed',
256 bottom: '0',
257 right: '0',
258 zIndex: 99999,
259 width: '100%',
260 height: devtoolsHeight ?? 500,
261 maxHeight: '90%',
262 boxShadow: '0 0 20px rgba(0,0,0,.3)',
263 borderTop: `1px solid ${theme.gray}`,
264 transformOrigin: 'top',
265 // visibility will be toggled after transitions, but set initial state here
266 visibility: isOpen ? 'visible' : 'hidden',
267 ...panelStyle,
268 ...(isResizing
269 ? {
270 transition: `none`,
271 }
272 : { transition: `all .2s ease` }),
273 ...(isResolvedOpen
274 ? {
275 opacity: 1,
276 pointerEvents: 'all',
277 transform: `translateY(0) scale(1)`,
278 }
279 : {
280 opacity: 0,
281 pointerEvents: 'none',
282 transform: `translateY(15px) scale(1.02)`,
283 }),
284 }}
285 isOpen={isResolvedOpen}
286 setIsOpen={setIsOpen}
287 handleDragStart={e => handleDragStart(panelRef.current, e)}
288 />
289 {isResolvedOpen ? (
290 <Button
291 type="button"
292 aria-controls="ReactQueryDevtoolsPanel"
293 aria-haspopup="true"
294 aria-expanded="true"
295 {...(otherCloseButtonProps as unknown)}
296 onClick={e => {
297 setIsOpen(false)
298 onCloseClick?.(e)
299 }}
300 style={{
301 position: 'fixed',
302 zIndex: 99999,
303 margin: '.5em',
304 bottom: 0,
305 ...(position === 'top-right'
306 ? {
307 right: '0',
308 }
309 : position === 'top-left'
310 ? {
311 left: '0',
312 }
313 : position === 'bottom-right'
314 ? {
315 right: '0',
316 }
317 : {
318 left: '0',
319 }),
320 ...closeButtonStyle,
321 }}
322 >
323 Close
324 </Button>
325 ) : null}
326 </ThemeProvider>
327 {!isResolvedOpen ? (
328 <button
329 type="button"
330 {...otherToggleButtonProps}
331 aria-label="Open React Query Devtools"
332 aria-controls="ReactQueryDevtoolsPanel"
333 aria-haspopup="true"
334 aria-expanded="false"
335 onClick={e => {
336 setIsOpen(true)
337 onToggleClick?.(e)
338 }}
339 style={{
340 background: 'none',
341 border: 0,
342 padding: 0,
343 position: 'fixed',
344 zIndex: 99999,
345 display: 'inline-flex',
346 fontSize: '1.5em',
347 margin: '.5em',
348 cursor: 'pointer',
349 width: 'fit-content',
350 ...(position === 'top-right'
351 ? {
352 top: '0',
353 right: '0',
354 }
355 : position === 'top-left'
356 ? {
357 top: '0',
358 left: '0',
359 }
360 : position === 'bottom-right'
361 ? {
362 bottom: '0',
363 right: '0',
364 }
365 : {
366 bottom: '0',
367 left: '0',
368 }),
369 ...toggleButtonStyle,
370 }}
371 >
372 <Logo aria-hidden />
373 </button>
374 ) : null}
375 </Container>
376 )
377}
378β
379const getStatusRank = (q: Query) =>
380 q.state.fetchStatus !== 'idle'
381 ? 0
382 : !q.getObserversCount()
383 ? 3
384 : q.isStale()
385 ? 2
386 : 1
387β
388const sortFns: Record<string, (a: Query, b: Query) => number> = {
389 'Status > Last Updated': (a, b) =>
390 getStatusRank(a) === getStatusRank(b)
391 ? (sortFns['Last Updated']?.(a, b) as number)
392 : getStatusRank(a) > getStatusRank(b)
393 ? 1
394 : -1,
395 'Query Hash': (a, b) => (a.queryHash > b.queryHash ? 1 : -1),
396 'Last Updated': (a, b) =>
397 a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1,
398}
399β
400const useSubscribeToQueryCache = <T,>(
401 queryCache: QueryCache,
402 getSnapshot: () => T
403): T => {
404 return useSyncExternalStore(
405 React.useCallback(
406 onStoreChange =>
407 queryCache.subscribe(notifyManager.batchCalls(onStoreChange)),
408 [queryCache]
409 ),
410 getSnapshot,
411 getSnapshot
412 )
413}
414β
415export const ReactQueryDevtoolsPanel = React.forwardRef<
416 HTMLDivElement,
417 DevtoolsPanelOptions
418>(function ReactQueryDevtoolsPanel(props, ref): React.ReactElement {
419 const {
420 isOpen = true,
421 styleNonce,
422 setIsOpen,
423 handleDragStart,
424 context,
425 ...panelProps
426 } = props
427β
428 const queryClient = useQueryClient({ context })
429 const queryCache = queryClient.getQueryCache()
430β
431 const [sort, setSort] = useLocalStorage(
432 'reactQueryDevtoolsSortFn',
433 Object.keys(sortFns)[0]
434 )
435β
436 const [filter, setFilter] = useLocalStorage('reactQueryDevtoolsFilter', '')
437β
438 const [sortDesc, setSortDesc] = useLocalStorage(
439 'reactQueryDevtoolsSortDesc',
440 false
441 )
442β
443 const sortFn = React.useMemo(() => sortFns[sort as string], [sort])
444β
445 React[isServer ? 'useEffect' : 'useLayoutEffect'](() => {
446 if (!sortFn) {
447 setSort(Object.keys(sortFns)[0] as string)
448 }
449 }, [setSort, sortFn])
450β
451 const queriesCount = useSubscribeToQueryCache(
452 queryCache,
453 () => queryCache.getAll().length
454 )
455β
456 const [activeQueryHash, setActiveQueryHash] = useLocalStorage(
457 'reactQueryDevtoolsActiveQueryHash',
458 ''
459 )
460β
461 const queries = React.useMemo(() => {
462 const unsortedQueries = queryCache.getAll()
463 const sorted = queriesCount > 0 ? [...unsortedQueries].sort(sortFn) : []
464β
465 if (sortDesc) {
466 sorted.reverse()
467 }
468β
469 if (!filter) {
470 return sorted
471 }
472β
473 return matchSorter(sorted, filter, { keys: ['queryHash'] }).filter(
474 d => d.queryHash
475 )
476 }, [sortDesc, sortFn, filter, queriesCount, queryCache])
477β
478 const [isMockOffline, setMockOffline] = React.useState(false)
479β
480 return (
481 <ThemeProvider theme={theme}>
482 <Panel
483 ref={ref}
484 className="ReactQueryDevtoolsPanel"
485 aria-label="React Query Devtools Panel"
486 id="ReactQueryDevtoolsPanel"
487 {...panelProps}
488 >
489 <style
490 nonce={styleNonce}
491 dangerouslySetInnerHTML={{
492 __html: `
493 .ReactQueryDevtoolsPanel * {
494 scrollbar-color: ${theme.backgroundAlt} ${theme.gray};
495 }
496β
497 .ReactQueryDevtoolsPanel *::-webkit-scrollbar, .ReactQueryDevtoolsPanel scrollbar {
498 width: 1em;
499 height: 1em;
500 }
501β
502 .ReactQueryDevtoolsPanel *::-webkit-scrollbar-track, .ReactQueryDevtoolsPanel scrollbar-track {
503 background: ${theme.backgroundAlt};
504 }
505β
506 .ReactQueryDevtoolsPanel *::-webkit-scrollbar-thumb, .ReactQueryDevtoolsPanel scrollbar-thumb {
507 background: ${theme.gray};
508 border-radius: .5em;
509 border: 3px solid ${theme.backgroundAlt};
510 }
511 `,
512 }}
513 />
514 <div
515 style={{
516 position: 'absolute',
517 left: 0,
518 top: 0,
519 width: '100%',
520 height: '4px',
521 marginBottom: '-4px',
522 cursor: 'row-resize',
523 zIndex: 100000,
524 }}
525 onMouseDown={handleDragStart}
526 ></div>
527 <div
528 style={{
529 flex: '1 1 500px',
530 minHeight: '40%',
531 maxHeight: '100%',
532 overflow: 'auto',
533 borderRight: `1px solid ${theme.grayAlt}`,
534 display: isOpen ? 'flex' : 'none',
535 flexDirection: 'column',
536 }}
537 >
538 <div
539 style={{
540 padding: '.5em',
541 background: theme.backgroundAlt,
542 display: 'flex',
543 justifyContent: 'space-between',
544 alignItems: 'center',
545 }}
546 >
547 <button
548 type="button"
549 aria-label="Close React Query Devtools"
550 aria-controls="ReactQueryDevtoolsPanel"
551 aria-haspopup="true"
552 aria-expanded="true"
553 onClick={() => setIsOpen(false)}
554 style={{
555 display: 'inline-flex',
556 background: 'none',
557 border: 0,
558 padding: 0,
559 marginRight: '.5em',
560 cursor: 'pointer',
561 }}
562 >
563 <Logo aria-hidden />
564 </button>
565 <div
566 style={{
567 display: 'flex',
568 flexDirection: 'column',
569 }}
570 >
571 <QueryStatusCount queryCache={queryCache} />
572 <div
573 style={{
574 display: 'flex',
575 alignItems: 'center',
576 }}
577 >
578 <Input
579 placeholder="Filter"
580 aria-label="Filter by queryhash"
581 value={filter ?? ''}
582 onChange={e => setFilter(e.target.value)}
583 onKeyDown={e => {
584 if (e.key === 'Escape') setFilter('')
585 }}
586 style={{
587 flex: '1',
588 marginRight: '.5em',
589 width: '100%',
590 }}
591 />
592 {!filter ? (
593 <>
594 <Select
595 aria-label="Sort queries"
596 value={sort}
597 onChange={e => setSort(e.target.value)}
598 style={{
599 flex: '1',
600 minWidth: 75,
601 marginRight: '.5em',
602 }}
603 >
604 {Object.keys(sortFns).map(key => (
605 <option key={key} value={key}>
606 Sort by {key}
607 </option>
608 ))}
609 </Select>
610 <Button
611 type="button"
612 onClick={() => setSortDesc(old => !old)}
613 style={{
614 padding: '.3em .4em',
615 marginRight: '.5em',
616 }}
617 >
618 {sortDesc ? 'β¬ Desc' : 'β¬ Asc'}
619 </Button>
620 <Button
621 type="button"
622 onClick={() => {
623 if (isMockOffline) {
624 onlineManager.setOnline(undefined)
625 setMockOffline(false)
626 window.dispatchEvent(new Event('online'))
627 } else {
628 onlineManager.setOnline(false)
629 setMockOffline(true)
630 }
631 }}
632 aria-label={
633 isMockOffline
634 ? 'Restore offline mock'
635 : 'Mock offline behavior'
636 }
637 title={
638 isMockOffline
639 ? 'Restore offline mock'
640 : 'Mock offline behavior'
641 }
642 style={{
643 padding: '0',
644 height: '2em',
645 }}
646 >
647 <svg
648 xmlns="http://www.w3.org/2000/svg"
649 width="2em"
650 height="2em"
651 viewBox="0 0 24 24"
652 stroke={isMockOffline ? theme.danger : 'currentColor'}
653 fill="none"
654 >
655 {isMockOffline ? (
656 <>
657 <path stroke="none" d="M0 0h24v24H0z" fill="none" />
658 <line x1="12" y1="18" x2="12.01" y2="18" />
659 <path d="M9.172 15.172a4 4 0 0 1 5.656 0" />
660 <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" />
661 <path d="M3.515 9.515a12 12 0 0 1 3.544 -2.455m3.101 -.92a12 12 0 0 1 10.325 3.374" />
662 <line x1="3" y1="3" x2="21" y2="21" />
663 </>
664 ) : (
665 <>
666 <path stroke="none" d="M0 0h24v24H0z" fill="none" />
667 <line x1="12" y1="18" x2="12.01" y2="18" />
668 <path d="M9.172 15.172a4 4 0 0 1 5.656 0" />
669 <path d="M6.343 12.343a8 8 0 0 1 11.314 0" />
670 <path d="M3.515 9.515c4.686 -4.687 12.284 -4.687 17 0" />
671 </>
672 )}
673 </svg>
674 </Button>
675 </>
676 ) : null}
677 </div>
678 </div>
679 </div>
680 <div
681 style={{
682 overflowY: 'auto',
683 flex: '1',
684 }}
685 >
686 {queries.map(query => {
687 return (
688 <QueryRow
689 queryKey={query.queryKey}
690 activeQueryHash={activeQueryHash}
691 setActiveQueryHash={setActiveQueryHash}
692 key={query.queryHash}
693 queryCache={queryCache}
694 />
695 )
696 })}
697 </div>
698 </div>
699β
700 {activeQueryHash ? (
701 <ActiveQuery
702 activeQueryHash={activeQueryHash}
703 queryCache={queryCache}
704 queryClient={queryClient}
705 />
706 ) : null}
707 </Panel>
708 </ThemeProvider>
709 )
710})
711β
712const ActiveQuery = ({
713 queryCache,
714 activeQueryHash,
715 queryClient,
716}: {
717 queryCache: QueryCache
718 activeQueryHash: string
719 queryClient: QueryClient
720}) => {
721 const activeQuery = useSubscribeToQueryCache(queryCache, () =>
722 queryCache.getAll().find(query => query.queryHash === activeQueryHash)
723 )
724β
725 const activeQueryState = useSubscribeToQueryCache(
726 queryCache,
727 () =>
728 queryCache.getAll().find(query => query.queryHash === activeQueryHash)
729 ?.state
730 )
731β
732 const isStale =
733 useSubscribeToQueryCache(queryCache, () =>
734 queryCache
735 .getAll()
736 .find(query => query.queryHash === activeQueryHash)
737 ?.isStale()
738 ) ?? false
739β
740 const observerCount =
741 useSubscribeToQueryCache(queryCache, () =>
742 queryCache
743 .getAll()
744 .find(query => query.queryHash === activeQueryHash)
745 ?.getObserversCount()
746 ) ?? 0
747β
748 const handleRefetch = () => {
749 const promise = activeQuery?.fetch()
750 promise?.catch(noop)
751 }
752β
753 if (!activeQuery || !activeQueryState) {
754 return null
755 }
756β
757 return (
758 <ActiveQueryPanel>
759 <div
760 style={{
761 padding: '.5em',
762 background: theme.backgroundAlt,
763 position: 'sticky',
764 top: 0,
765 zIndex: 1,
766 }}
767 >
768 Query Details
769 </div>
770 <div
771 style={{
772 padding: '.5em',
773 }}
774 >
775 <div
776 style={{
777 marginBottom: '.5em',
778 display: 'flex',
779 alignItems: 'stretch',
780 justifyContent: 'space-between',
781 }}
782 >
783 <Code
784 style={{
785 lineHeight: '1.8em',
786 }}
787 >
788 <pre
789 style={{
790 margin: 0,
791 padding: 0,
792 overflow: 'auto',
793 }}
794 >
795 {JSON.stringify(activeQuery.queryKey, null, 2)}
796 </pre>
797 </Code>
798 <span
799 style={{
800 padding: '0.3em .6em',
801 borderRadius: '0.4em',
802 fontWeight: 'bold',
803 textShadow: '0 2px 10px black',
804 background: getQueryStatusColor({
805 queryState: activeQueryState,
806 isStale: isStale,
807 observerCount: observerCount,
808 theme,
809 }),
810 flexShrink: 0,
811 }}
812 >
813 {getQueryStatusLabel(activeQuery)}
814 </span>
815 </div>
816 <div
817 style={{
818 marginBottom: '.5em',
819 display: 'flex',
820 alignItems: 'center',
821 justifyContent: 'space-between',
822 }}
823 >
824 Observers: <Code>{observerCount}</Code>
825 </div>
826 <div
827 style={{
828 display: 'flex',
829 alignItems: 'center',
830 justifyContent: 'space-between',
831 }}
832 >
833 Last Updated:{' '}
834 <Code>
835 {new Date(activeQueryState.dataUpdatedAt).toLocaleTimeString()}
836 </Code>
837 </div>
838 </div>
839 <div
840 style={{
841 background: theme.backgroundAlt,
842 padding: '.5em',
843 position: 'sticky',
844 top: 0,
845 zIndex: 1,
846 }}
847 >
848 Actions
849 </div>
850 <div
851 style={{
852 padding: '0.5em',
853 }}
854 >
855 <Button
856 type="button"
857 onClick={handleRefetch}
858 disabled={activeQueryState.fetchStatus === 'fetching'}
859 style={{
860 background: theme.active,
861 }}
862 >
863 Refetch
864 </Button>{' '}
865 <Button
866 type="button"
867 onClick={() => queryClient.invalidateQueries(activeQuery)}
868 style={{
869 background: theme.warning,
870 color: theme.inputTextColor,
871 }}
872 >
873 Invalidate
874 </Button>{' '}
875 <Button
876 type="button"
877 onClick={() => queryClient.resetQueries(activeQuery)}
878 style={{
879 background: theme.gray,
880 }}
881 >
882 Reset
883 </Button>{' '}
884 <Button
885 type="button"
886 onClick={() => queryClient.removeQueries(activeQuery)}
887 style={{
888 background: theme.danger,
889 }}
890 >
891 Remove
892 </Button>
893 </div>
894 <div
895 style={{
896 background: theme.backgroundAlt,
897 padding: '.5em',
898 position: 'sticky',
899 top: 0,
900 zIndex: 1,
901 }}
902 >
903 Data Explorer
904 </div>
905 <div
906 style={{
907 padding: '.5em',
908 }}
909 >
910 <Explorer
911 label="Data"
912 value={activeQueryState.data}
913 defaultExpanded={{}}
914 />
915 </div>
916 <div
917 style={{
918 background: theme.backgroundAlt,
919 padding: '.5em',
920 position: 'sticky',
921 top: 0,
922 zIndex: 1,
923 }}
924 >
925 Query Explorer
926 </div>
927 <div
928 style={{
929 padding: '.5em',
930 }}
931 >
932 <Explorer
933 label="Query"
934 value={activeQuery}
935 defaultExpanded={{
936 queryKey: true,
937 }}
938 />
939 </div>
940 </ActiveQueryPanel>
941 )
942}
943β
944const QueryStatusCount = ({ queryCache }: { queryCache: QueryCache }) => {
945 const hasFresh = useSubscribeToQueryCache(
946 queryCache,
947 () =>
948 queryCache.getAll().filter(q => getQueryStatusLabel(q) === 'fresh').length
949 )
950 const hasFetching = useSubscribeToQueryCache(
951 queryCache,
952 () =>
953 queryCache.getAll().filter(q => getQueryStatusLabel(q) === 'fetching')
954 .length
955 )
956 const hasPaused = useSubscribeToQueryCache(
957 queryCache,
958 () =>
959 queryCache.getAll().filter(q => getQueryStatusLabel(q) === 'paused')
960 .length
961 )
962 const hasStale = useSubscribeToQueryCache(
963 queryCache,
964 () =>
965 queryCache.getAll().filter(q => getQueryStatusLabel(q) === 'stale').length
966 )
967 const hasInactive = useSubscribeToQueryCache(
968 queryCache,
969 () =>
970 queryCache.getAll().filter(q => getQueryStatusLabel(q) === 'inactive')
971 .length
972 )
973 return (
974 <QueryKeys style={{ marginBottom: '.5em' }}>
975 <QueryKey
976 style={{
977 background: theme.success,
978 opacity: hasFresh ? 1 : 0.3,
979 }}
980 >
981 fresh <Code>({hasFresh})</Code>
982 </QueryKey>{' '}
983 <QueryKey
984 style={{
985 background: theme.active,
986 opacity: hasFetching ? 1 : 0.3,
987 }}
988 >
989 fetching <Code>({hasFetching})</Code>
990 </QueryKey>{' '}
991 <QueryKey
992 style={{
993 background: theme.paused,
994 opacity: hasPaused ? 1 : 0.3,
995 }}
996 >
997 paused <Code>({hasPaused})</Code>
998 </QueryKey>{' '}
999 <QueryKey
1000 style={{
1001 background: theme.warning,
1002 color: 'black',
1003 textShadow: '0',
1004 opacity: hasStale ? 1 : 0.3,
1005 }}
1006 >
1007 stale <Code>({hasStale})</Code>
1008 </QueryKey>{' '}
1009 <QueryKey
1010 style={{
1011 background: theme.gray,
1012 opacity: hasInactive ? 1 : 0.3,
1013 }}
1014 >
1015 inactive <Code>({hasInactive})</Code>
1016 </QueryKey>
1017 </QueryKeys>
1018 )
1019}
1020β
1021interface QueryRowProps {
1022 queryKey: QueryKeyType
1023 setActiveQueryHash: (hash: string) => void
1024 activeQueryHash?: string
1025 queryCache: QueryCache
1026}
1027β
1028const QueryRow = ({
1029 queryKey,
1030 setActiveQueryHash,
1031 activeQueryHash,
1032 queryCache,
1033}: QueryRowProps) => {
1034 const queryHash =
1035 useSubscribeToQueryCache(
1036 queryCache,
1037 () => queryCache.find(queryKey)?.queryHash
1038 ) ?? ''
1039β
1040 const queryState = useSubscribeToQueryCache(
1041 queryCache,
1042 () => queryCache.find(queryKey)?.state
1043 )
1044β
1045 const isStale =
1046 useSubscribeToQueryCache(queryCache, () =>
1047 queryCache.find(queryKey)?.isStale()
1048 ) ?? false
1049β
1050 const isDisabled =
1051 useSubscribeToQueryCache(queryCache, () =>
1052 queryCache.find(queryKey)?.isDisabled()
1053 ) ?? false
1054β
1055 const observerCount =
1056 useSubscribeToQueryCache(queryCache, () =>
1057 queryCache.find(queryKey)?.getObserversCount()
1058 ) ?? 0
1059β
1060 if (!queryState) {
1061 return null
1062 }
1063β
1064 return (
1065 <div
1066 role="button"
1067 aria-label={`Open query details for ${queryHash}`}
1068 onClick={() =>
1069 setActiveQueryHash(activeQueryHash === queryHash ? '' : queryHash)
1070 }
1071 style={{
1072 display: 'flex',
1073 borderBottom: `solid 1px ${theme.grayAlt}`,
1074 cursor: 'pointer',
1075 background:
1076 queryHash === activeQueryHash ? 'rgba(255,255,255,.1)' : undefined,
1077 }}
1078 >
1079 <div
1080 style={{
1081 flex: '0 0 auto',
1082 width: '2em',
1083 height: '2em',
1084 background: getQueryStatusColor({
1085 queryState,
1086 isStale,
1087 observerCount,
1088 theme,
1089 }),
1090 display: 'flex',
1091 alignItems: 'center',
1092 justifyContent: 'center',
1093 fontWeight: 'bold',
1094 textShadow: isStale ? '0' : '0 0 10px black',
1095 color: isStale ? 'black' : 'white',
1096 }}
1097 >
1098 {observerCount}
1099 </div>
1100 {isDisabled ? (
1101 <div
1102 style={{
1103 flex: '0 0 auto',
1104 height: '2em',
1105 background: theme.gray,
1106 display: 'flex',
1107 alignItems: 'center',
1108 fontWeight: 'bold',
1109 padding: '0 0.5em',
1110 }}
1111 >
1112 disabled
1113 </div>
1114 ) : null}
1115 <Code
1116 style={{
1117 padding: '.5em',
1118 }}
1119 >
1120 {`${queryHash}`}
1121 </Code>
1122 </div>
1123 )
1124}