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

devtools.tsx

1,132 lines31.0 KB

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