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

devtools.tsx

1,134 lines30.6 KB

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