Open History to see the last commit
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 }
57}
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[]
100}
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[]
148}
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 )
423}
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 )
444}
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 }}
1004 >
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 }}
1014 >
1015 Invalidate
1016 </Button>{' '}
1017 <Button
1018 type="button"
1019 onClick={() => queryClient.resetQueries(activeQuery)}
1020 style={{
1021 background: theme.gray,
1022 }}
1023 >
1024 Reset
1025 </Button>{' '}
1026 <Button
1027 type="button"
1028 onClick={() => queryClient.removeQueries(activeQuery)}
1029 style={{
1030 background: theme.danger,
1031 }}
1032 >
1033 Remove
1034 </Button>{' '}
1035 <Button
1036 type="button"
1037 onClick={() => {
1038 // Return early if the query is already restoring
1039 if (
1040 activeQuery.state.fetchStatus === 'fetching' &&
1041 typeof activeQuery.state.fetchMeta?.__previousQueryOptions ===
1042 'undefined'
1043 ) {
1044 return
1045 }
1046
1047 if (activeQuery.state.data === undefined) {
1048 restoreQueryAfterLoadingOrError()
1049 } else {
1050 const __previousQueryOptions = activeQuery.options
1051 // Trigger a fetch in order to trigger suspense as well.
1052 activeQuery.fetch({
1053 ...__previousQueryOptions,
1054 queryFn: () => {
1055 return new Promise(() => {
1056 // Never resolve
1057 })
1058 },
1059 cacheTime: -1,
1060 })
1061 activeQuery.setState({
1062 data: undefined,
1063 status: 'loading',
1064 fetchMeta: {
1065 ...activeQuery.state.fetchMeta,
1066 __previousQueryOptions,
1067 },
1068 })
1069 }
1070 }}
1071 style={{
1072 background: theme.paused,
1073 }}
1074 >
1075 {activeQuery.state.status === 'loading' ? 'Restore' : 'Trigger'}{' '}
1076 loading
1077 </Button>{' '}
1078 {errorTypes.length === 0 || activeQuery.state.status === 'error' ? (
1079 <Button
1080 type="button"
1081 onClick={() => {
1082 if (!activeQuery.state.error) {
1083 triggerError()
1084 } else {
1085 queryClient.resetQueries(activeQuery)
1086 }
1087 }}
1088 style={{
1089 background: theme.danger,
1090 }}
1091 >
1092 {activeQuery.state.status === 'error' ? 'Restore' : 'Trigger'} error
1093 </Button>
1094 ) : (
1095 <label>
1096 Trigger error:
1097 <Select
1098 value={currentErrorTypeName ?? ''}
1099 style={{ marginInlineStart: '.5em' }}
1100 onChange={(e) => {
1101 const errorType = errorTypes.find(
1102 (t) => t.name === e.target.value,
1103 )
1104
1105 triggerError(errorType)
1106 }}
1107 >
1108 <option key="" value="" />
1109 {errorTypes.map((errorType) => (
1110 <option key={errorType.name} value={errorType.name}>
1111 {errorType.name}
1112 </option>
1113 ))}
1114 </Select>
1115 </label>
1116 )}
1117 </div>
1118 <div
1119 style={{
1120 background: theme.backgroundAlt,
1121 padding: '.5em',
1122 position: 'sticky',
1123 top: 0,
1124 zIndex: 1,
1125 }}
1126 >
1127 Data Explorer
1128 </div>
1129 <div
1130 style={{
1131 padding: '.5em',
1132 }}
1133 >
1134 <Explorer
1135 label="Data"
1136 value={activeQueryState.data}
1137 defaultExpanded={{}}
1138 copyable
1139 />
1140 </div>
1141 <div
1142 style={{
1143 background: theme.backgroundAlt,
1144 padding: '.5em',
1145 position: 'sticky',
1146 top: 0,
1147 zIndex: 1,
1148 }}
1149 >
1150 Query Explorer
1151 </div>
1152 <div
1153 style={{
1154 padding: '.5em',
1155 }}
1156 >
1157 <Explorer
1158 label="Query"
1159 value={activeQuery}
1160 defaultExpanded={{
1161 queryKey: true,
1162 }}
1163 />
1164 </div>
1165 </ActiveQueryPanel>
1166 )
1167}
1168
1169const QueryStatusCount = ({ queryCache }: { queryCache: QueryCache }) => {
1170 const hasFresh = useSubscribeToQueryCache(
1171 queryCache,
1172 () =>
1173 queryCache.getAll().filter((q) => getQueryStatusLabel(q) === 'fresh')
1174 .length,
1175 )
1176 const hasFetching = useSubscribeToQueryCache(
1177 queryCache,
1178 () =>
1179 queryCache.getAll().filter((q) => getQueryStatusLabel(q) === 'fetching')
1180 .length,
1181 )
1182 const hasPaused = useSubscribeToQueryCache(
1183 queryCache,
1184 () =>
1185 queryCache.getAll().filter((q) => getQueryStatusLabel(q) === 'paused')
1186 .length,
1187 )
1188 const hasStale = useSubscribeToQueryCache(
1189 queryCache,
1190 () =>
1191 queryCache.getAll().filter((q) => getQueryStatusLabel(q) === 'stale')
1192 .length,
1193 )
1194 const hasInactive = useSubscribeToQueryCache(
1195 queryCache,
1196 () =>
1197 queryCache.getAll().filter((q) => getQueryStatusLabel(q) === 'inactive')
1198 .length,
1199 )
1200 return (
1201 <QueryKeys>
1202 <QueryKey
1203 style={{
1204 background: theme.success,
1205 opacity: hasFresh ? 1 : 0.3,
1206 }}
1207 >
1208 fresh <Code>({hasFresh})</Code>
1209 </QueryKey>{' '}
1210 <QueryKey
1211 style={{
1212 background: theme.active,
1213 opacity: hasFetching ? 1 : 0.3,
1214 }}
1215 >
1216 fetching <Code>({hasFetching})</Code>
1217 </QueryKey>{' '}
1218 <QueryKey
1219 style={{
1220 background: theme.paused,
1221 opacity: hasPaused ? 1 : 0.3,
1222 }}
1223 >
1224 paused <Code>({hasPaused})</Code>
1225 </QueryKey>{' '}
1226 <QueryKey
1227 style={{
1228 background: theme.warning,
1229 color: 'black',
1230 textShadow: '0',
1231 opacity: hasStale ? 1 : 0.3,
1232 }}
1233 >
1234 stale <Code>({hasStale})</Code>
1235 </QueryKey>{' '}
1236 <QueryKey
1237 style={{
1238 background: theme.gray,
1239 opacity: hasInactive ? 1 : 0.3,
1240 }}
1241 >
1242 inactive <Code>({hasInactive})</Code>
1243 </QueryKey>
1244 </QueryKeys>
1245 )
1246}
1247
1248interface QueryRowProps {
1249 queryKey: QueryKeyType
1250 setActiveQueryHash: (hash: string) => void
1251 activeQueryHash?: string
1252 queryCache: QueryCache
1253}
1254
1255const QueryRow = React.memo(
1256 ({
1257 queryKey,
1258 setActiveQueryHash,
1259 activeQueryHash,
1260 queryCache,
1261 }: QueryRowProps) => {
1262 const queryHash =
1263 useSubscribeToQueryCache(
1264 queryCache,
1265 () => queryCache.find(queryKey)?.queryHash,
1266 ) ?? ''
1267
1268 const queryState = useSubscribeToQueryCache(
1269 queryCache,
1270 () => queryCache.find(queryKey)?.state,
1271 )
1272
1273 const isStale =
1274 useSubscribeToQueryCache(queryCache, () =>
1275 queryCache.find(queryKey)?.isStale(),
1276 ) ?? false
1277
1278 const isDisabled =
1279 useSubscribeToQueryCache(queryCache, () =>
1280 queryCache.find(queryKey)?.isDisabled(),
1281 ) ?? false
1282
1283 const observerCount =
1284 useSubscribeToQueryCache(queryCache, () =>
1285 queryCache.find(queryKey)?.getObserversCount(),
1286 ) ?? 0
1287
1288 if (!queryState) {
1289 return null
1290 }
1291
1292 return (
1293 <div
1294 role="button"
1295 aria-label={`Open query details for ${queryHash}`}
1296 onClick={() =>
1297 setActiveQueryHash(activeQueryHash === queryHash ? '' : queryHash)
1298 }
1299 style={{
1300 display: 'flex',
1301 borderBottom: `solid 1px ${theme.grayAlt}`,
1302 cursor: 'pointer',
1303 background:
1304 queryHash === activeQueryHash ? 'rgba(255,255,255,.1)' : undefined,
1305 }}
1306 >
1307 <div
1308 style={{
1309 flex: '0 0 auto',
1310 width: '2em',
1311 height: '2em',
1312 background: getQueryStatusColor({
1313 queryState,
1314 isStale,
1315 observerCount,
1316 theme,
1317 }),
1318 display: 'flex',
1319 alignItems: 'center',
1320 justifyContent: 'center',
1321 fontWeight: 'bold',
1322 textShadow: isStale ? '0' : '0 0 10px black',
1323 color: isStale ? 'black' : 'white',
1324 }}
1325 >
1326 {observerCount}
1327 </div>
1328 {isDisabled ? (
1329 <div
1330 style={{
1331 flex: '0 0 auto',
1332 height: '2em',
1333 background: theme.gray,
1334 display: 'flex',
1335 alignItems: 'center',
1336 fontWeight: 'bold',
1337 padding: '0 0.5em',
1338 }}
1339 >
1340 disabled
1341 </div>
1342 ) : null}
1343 <Code
1344 style={{
1345 padding: '.5em',
1346 }}
1347 >
1348 {`${queryHash}`}
1349 </Code>
1350 </div>
1351 )
1352 },
1353)
1354
1355QueryRow.displayName = 'QueryRow'
1356
1357// eslint-disable-next-line @typescript-eslint/no-empty-function
1358function noop() {}