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

devtools.tsx

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