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