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

devtools.tsx

1,192 lines32.6 KB

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