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