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

devtools.tsx

1,100 lines29.6 KB

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