import { DropdownMenu, RadioGroup } from '@kobalte/core' import { createResizeObserver } from '@solid-primitives/resize-observer' import { rankItem } from '@tanstack/match-sorter-utils' import { For, Show, batch, createEffect, createMemo, createSignal, on, onCleanup, onMount, } from 'solid-js' import { Portal } from 'solid-js/web' import { TransitionGroup } from 'solid-transition-group' import Explorer, { SearchableExplorer } from './Explorer' import { VirtualList } from './VirtualList' import { BUTTON_POSITION, DEFAULT_FILTER_SCOPE, DEFAULT_HEIGHT, DEFAULT_MUTATION_SORT_FN_NAME, DEFAULT_SORT_FN_NAME, DEFAULT_SORT_ORDER, DEFAULT_WIDTH, FILTER_SCOPES, INITIAL_IS_OPEN, POSITION, firstBreakpoint, secondBreakpoint, thirdBreakpoint, } from './constants' import { usePiPWindow, useQueryDevtoolsContext, useTheme } from './contexts' import { useDevtoolsOffline } from './contexts/DevtoolsOfflineContext' import { useDevtoolsState } from './contexts/DevtoolsStateContext' import { useDevtoolsSubscriptions } from './contexts/DevtoolsSubscriptionsContext' import { createSearchText } from './explorerSearch' import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, CheckCircle, ChevronDown, LoadingCircle, Monitor, Moon, Offline, PauseCircle, PiPIcon, Search, Settings, Sun, TanstackLogo, Trash, Wifi, XCircle, } from './icons' import { attachStyles, createThemed } from './styles' import { tokens } from './theme' import { convertRemToPixels, displayValue, getMutationStatusColor, getQueryStatusColor, getQueryStatusColorByLabel, getQueryStatusLabel, getSidedProp, mutationSortFns, sortFns, } from './utils' import type { StorageObject, StorageSetter } from '@solid-primitives/storage' import type { Mutation, MutationCache, MutationCacheNotifyEvent, Query, QueryCache, QueryCacheNotifyEvent, } from '@tanstack/query-core' import type { Accessor, Component, JSX } from 'solid-js' import type { FilterScope } from './constants' import type { DevtoolsErrorType, DevtoolsPosition, QueryDevtoolsProps, } from './contexts' const filterScopeLabels: Record = { key: 'Key', data: 'Data', all: 'All', } const filterScopeAriaLabels: Record< 'queries' | 'mutations', Record > = { queries: { key: 'Filter queries by query key', data: 'Filter queries by query data', all: 'Filter queries by query key or data', }, mutations: { key: 'Filter mutations by mutation key', data: 'Filter mutations by variables or data', all: 'Filter mutations by mutation key, variables or data', }, } // Query data is immutable. Cached mutation text is invalidated when mutation state changes. const dataSearchTexts = new WeakMap() /** * Gets the cached search text of query or mutation data, building it if there is time left. * @param data - The query data, or mutation variables or data. * @param deadline - When to stop building search texts, compared to `performance.now()`. * @returns The search text, or undefined if it isn't built and the deadline has passed. */ const getDataSearchText = (data: unknown, deadline = Infinity) => { if (typeof data !== 'object' || data === null) return createSearchText(data) let text = dataSearchTexts.get(data) if (text === undefined && performance.now() < deadline) { text = createSearchText(data) dataSearchTexts.set(data, text) } return text } /** * Checks whether data contains the term. Missing data never matches. * @param data - The query data, or mutation variables or data. * @param term - The lowercased search term. * @returns Whether the data matches. */ const matchesData = (data: unknown, term: string) => data !== undefined && getDataSearchText(data)!.includes(term) /** * Builds data search texts for a few milliseconds per task, so filtering by data doesn't block * the page. * @returns `version`, which changes when building continued in a later task, and `prepare`, * which returns whether the search texts of all the data are built. */ const createDataSearchTexts = () => { const [version, setVersion] = createSignal(0) let timeout: ReturnType | undefined onCleanup(() => clearTimeout(timeout)) const prepare = (data: Array) => { clearTimeout(timeout) const deadline = performance.now() + 8 if (data.every((item) => getDataSearchText(item, deadline) !== undefined)) { return true } timeout = setTimeout(() => setVersion((current) => current + 1)) return false } return { version, prepare } } interface DevtoolsPanelProps { localStore: StorageObject setLocalStore: StorageSetter } interface ContentViewProps { localStore: StorageObject setLocalStore: StorageSetter showPanelViewOnly?: boolean onClose?: () => void } interface QueryStatusProps { label: string color: 'green' | 'yellow' | 'gray' | 'blue' | 'purple' | 'red' count: number } /** * The devtools component that `TanstackQueryDevtools` and `TanstackQueryDevtoolsPanel` lazily load * and render. */ export type DevtoolsComponentType = Component & { shadowDOMTarget?: ShadowRoot } /** * The floating devtools: a toggle button that opens a resizable panel, or the * panel in a picture-in-picture window when one is open. * @param props - The `localStore` that persists the devtools settings, and its * `setLocalStore` setter. * @returns The toggle button and the panel. */ export const Devtools: Component = (props) => { const pip = usePiPWindow() const buttonPosition = createMemo(() => { return useQueryDevtoolsContext().buttonPosition || BUTTON_POSITION }) const isOpen = createMemo(() => { return props.localStore.open === 'true' ? true : props.localStore.open === 'false' ? false : useQueryDevtoolsContext().initialIsOpen || INITIAL_IS_OPEN }) const position = createMemo(() => { return ( props.localStore.position || useQueryDevtoolsContext().position || POSITION ) }) let transitionsContainerRef!: HTMLDivElement onMount(() => { attachStyles( transitionsContainerRef, useQueryDevtoolsContext().shadowDOMTarget, ) }) createEffect(() => { const root = transitionsContainerRef.parentElement as HTMLElement const height = props.localStore.height || DEFAULT_HEIGHT const width = props.localStore.width || DEFAULT_WIDTH const panelPosition = position() root.style.setProperty( '--tsqd-panel-height', `${panelPosition === 'top' ? '-' : ''}${height}px`, ) root.style.setProperty( '--tsqd-panel-width', `${panelPosition === 'left' ? '-' : ''}${width}px`, ) }) // Calculates the inherited font size of the parent and sets it as a CSS variable // All the design tokens are calculated based on this variable onMount(() => { // This is to make sure that the font size is updated when the stylesheet is updated // and the user focuses back on the window const onFocus = () => { const root = transitionsContainerRef.parentElement as HTMLElement const fontSize = getComputedStyle(root).fontSize root.style.setProperty('--tsqd-font-size', fontSize) } onFocus() window.addEventListener('focus', onFocus) onCleanup(() => { window.removeEventListener('focus', onFocus) }) }) const pip_open = createMemo( () => (props.localStore.pip_open ?? 'false') as 'true' | 'false', ) return ( <>
) } const PiPPanel: Component<{ children: JSX.Element }> = (props) => { const { panelWidth, setPanelWidth } = useDevtoolsState() const pip = usePiPWindow() const theme = useTheme() const themed = createThemed(theme) let panelRef!: HTMLDivElement onMount(() => { attachStyles(panelRef) }) createEffect(() => { const win = pip().pipWindow const resizeCB = () => { if (!win) return setPanelWidth(win.innerWidth) } if (win) { win.addEventListener('resize', resizeCB) resizeCB() } onCleanup(() => { if (win) { win.removeEventListener('resize', resizeCB) } }) }) return (
{props.children}
) } /** * The container of the embedded devtools panel, which tracks its width for * the responsive layout. * @param props - The `children` to render inside the panel. * @returns The panel container. */ export const ParentPanel: Component<{ children: JSX.Element }> = (props) => { const { panelWidth, setPanelWidth } = useDevtoolsState() const theme = useTheme() const themed = createThemed(theme) let panelRef!: HTMLDivElement onMount(() => { attachStyles(panelRef, useQueryDevtoolsContext().shadowDOMTarget) createResizeObserver(panelRef, ({ width }, el) => { if (el === panelRef) { setPanelWidth(width) } }) }) return (
{props.children}
) } const DraggablePanel: Component = (props) => { const { setSelectedQueryHash, panelWidth, setPanelWidth } = useDevtoolsState() const theme = useTheme() const themed = createThemed(theme) let closeBtnRef!: HTMLButtonElement // Focus the close button when the panel opens for screen reader accessibility onMount(() => { closeBtnRef.focus() }) const [isResizing, setIsResizing] = createSignal(false) const position = createMemo( () => (props.localStore.position || useQueryDevtoolsContext().position || POSITION) as DevtoolsPosition, ) const handleDragStart: JSX.EventHandler = ( event, ) => { const panelElement = event.currentTarget.parentElement if (!panelElement) return setIsResizing(true) const { height, width } = panelElement.getBoundingClientRect() const startX = event.clientX const startY = event.clientY let newSize = 0 const minHeight = convertRemToPixels(3.5) const minWidth = convertRemToPixels(12) const runDrag = (moveEvent: MouseEvent) => { moveEvent.preventDefault() if (position() === 'left' || position() === 'right') { const valToAdd = position() === 'right' ? startX - moveEvent.clientX : moveEvent.clientX - startX newSize = Math.round(width + valToAdd) if (newSize < minWidth) { newSize = minWidth } props.setLocalStore('width', String(Math.round(newSize))) const newWidth = panelElement.getBoundingClientRect().width // If the panel size didn't decrease, this means we have reached the minimum width // of the panel so we restore the original width in local storage // Restoring the width helps in smooth open/close transitions if (Number(props.localStore.width) < newWidth) { props.setLocalStore('width', String(newWidth)) } } else { const valToAdd = position() === 'bottom' ? startY - moveEvent.clientY : moveEvent.clientY - startY newSize = Math.round(height + valToAdd) // If the panel size is less than the minimum height, // we set the size to the minimum height if (newSize < minHeight) { newSize = minHeight setSelectedQueryHash(null) } props.setLocalStore('height', String(Math.round(newSize))) } } const unsubscribe = () => { if (isResizing()) { setIsResizing(false) } document.removeEventListener('mousemove', runDrag, false) document.removeEventListener('mouseup', unsubscribe, false) } document.addEventListener('mousemove', runDrag, false) document.addEventListener('mouseup', unsubscribe, false) } let panelRef!: HTMLDivElement onMount(() => { createResizeObserver(panelRef, ({ width }, el) => { if (el === panelRef) { setPanelWidth(width) } }) }) createEffect(() => { const rootContainer = panelRef.parentElement?.parentElement?.parentElement if (!rootContainer) return const currentPosition = (props.localStore.position || POSITION) as DevtoolsPosition const styleProp = getSidedProp('padding', currentPosition) const isVertical = props.localStore.position === 'left' || props.localStore.position === 'right' const previousPaddings = (({ padding, paddingTop, paddingBottom, paddingLeft, paddingRight, }) => ({ padding, paddingTop, paddingBottom, paddingLeft, paddingRight, }))(rootContainer.style) rootContainer.style[styleProp] = `${ isVertical ? props.localStore.width : props.localStore.height }px` onCleanup(() => { Object.entries(previousPaddings).forEach(([property, previousValue]) => { rootContainer.style[property as keyof typeof previousPaddings] = previousValue }) }) }) return ( ) } /** * The content of the devtools panel: the query and mutation lists with their * filters and actions, and the details of the selected query or mutation. * @param props - The `localStore` and `setLocalStore` that persist the devtools * settings, `showPanelViewOnly` to hide the controls that only apply to the * floating devtools, and `onClose` to close an embedded panel. * @returns The panel content. */ export const ContentView: Component = (props) => { const { selectedQueryHash, setSelectedQueryHash, selectedMutationId, setSelectedMutationId, panelWidth, } = useDevtoolsState() const { offline, toggleOffline } = useDevtoolsOffline() setupQueryCacheSubscription() setupMutationCacheSubscription() let containerRef!: HTMLDivElement const theme = useTheme() const themed = createThemed(theme) const pip = usePiPWindow() const [selectedView, setSelectedView] = createSignal<'queries' | 'mutations'>( 'queries', ) const sort = createMemo(() => props.localStore.sort || DEFAULT_SORT_FN_NAME) const sortOrder = createMemo( () => Number(props.localStore.sortOrder) || DEFAULT_SORT_ORDER, ) as () => 1 | -1 const mutationSort = createMemo( () => props.localStore.mutationSort || DEFAULT_MUTATION_SORT_FN_NAME, ) const mutationSortOrder = createMemo( () => Number(props.localStore.mutationSortOrder) || DEFAULT_SORT_ORDER, ) as () => 1 | -1 const sortFn = createMemo(() => sortFns[sort() as string]) const mutationSortFn = createMemo( () => mutationSortFns[mutationSort() as string], ) const query_cache = createMemo(() => { return useQueryDevtoolsContext().client.getQueryCache() }) const mutation_cache = createMemo(() => { return useQueryDevtoolsContext().client.getMutationCache() }) const queryCount = createSubscribeToQueryCacheBatcher((queryCache) => { return queryCache().getAll().length }, false) const hideDisabledQueries = createMemo(() => { return props.localStore.hideDisabledQueries === 'true' ? true : props.localStore.hideDisabledQueries === 'false' ? false : useQueryDevtoolsContext().hideDisabledQueries || false }) const filterScope = createMemo(() => { const scope = props.localStore.filterScope as FilterScope return FILTER_SCOPES.includes(scope) ? scope : DEFAULT_FILTER_SCOPE }) const cycleFilterScope = () => { const index = FILTER_SCOPES.indexOf(filterScope()) props.setLocalStore( 'filterScope', FILTER_SCOPES[(index + 1) % FILTER_SCOPES.length]!, ) } // Data changes don't change the query count, so data searches need their own trigger const queryDataVersion = createSubscribeToQueryCacheBatcher( () => ({}), false, (event) => filterScope() !== 'key' && !!props.localStore.filter && event.type === 'updated' && (event.action.type === 'success' || event.action.type === 'setState'), ) const queryDataSearchTexts = createDataSearchTexts() const queries = createMemo( on( () => [ queryCount(), props.localStore.filter, filterScope(), queryDataVersion(), queryDataSearchTexts.version(), sort(), sortOrder(), hideDisabledQueries(), ], (_input, _prevInput, prev: Array | undefined) => { const curr = query_cache().getAll() const filter = props.localStore.filter || '' const scope = filterScope() const dataTerm = filter.toLowerCase() if ( filter && scope !== 'key' && !queryDataSearchTexts.prepare(curr.map((item) => item.state.data)) ) { // Keeps the previous results until all search texts are built return prev ?? [] } let filtered = filter ? curr.filter( (item) => (scope !== 'data' && rankItem(item.queryHash, filter).passed) || (scope !== 'key' && matchesData(item.state.data, dataTerm)), ) : [...curr] // Filter out disabled queries if hideDisabledQueries is enabled if (hideDisabledQueries()) { filtered = filtered.filter((item) => !item.isDisabled()) } const sorted = sortFn() ? filtered.sort((a, b) => sortFn()!(a, b) * sortOrder()) : filtered return sorted }, ), ) const mutationCount = createSubscribeToMutationCacheBatcher( (mutationCache) => { return mutationCache().getAll().length }, false, ) // Variables and data changes don't change the mutation count, so data searches need their own trigger const mutationDataVersion = createSubscribeToMutationCacheBatcher( () => ({}), false, (event) => { if (event.type !== 'updated') return false // Mutation functions can change variables in place, including when no data filter is active. for (const value of [ event.mutation.state.variables, event.mutation.state.data, ]) { if (typeof value === 'object' && value !== null) { dataSearchTexts.delete(value) } } return filterScope() !== 'key' && !!props.localStore.mutationFilter }, ) const mutationDataSearchTexts = createDataSearchTexts() const mutations = createMemo( on( () => [ mutationCount(), props.localStore.mutationFilter, filterScope(), mutationDataVersion(), mutationDataSearchTexts.version(), mutationSort(), mutationSortOrder(), ], (_input, _prevInput, prev: Array | undefined) => { const curr = mutation_cache().getAll() const filter = props.localStore.mutationFilter || '' const scope = filterScope() const dataTerm = filter.toLowerCase() if ( filter && scope !== 'key' && !mutationDataSearchTexts.prepare( curr.flatMap((item) => [item.state.variables, item.state.data]), ) ) { // Keeps the previous results until all search texts are built return prev ?? [] } const filtered = filter ? curr.filter((item) => { const value = `${ item.options.mutationKey ? JSON.stringify(item.options.mutationKey) + ' - ' : '' }${new Date(item.state.submittedAt).toLocaleString()}` return ( (scope !== 'data' && rankItem(value, filter).passed) || (scope !== 'key' && (matchesData(item.state.variables, dataTerm) || matchesData(item.state.data, dataTerm))) ) }) : [...curr] const sorted = mutationSortFn() ? filtered.sort( (a, b) => mutationSortFn()!(a, b) * mutationSortOrder(), ) : filtered return sorted }, ), ) const setDevtoolsPosition = (pos: DevtoolsPosition) => { props.setLocalStore('position', pos) } // Adds the styles and sets the font size variable on portal menu elements, // since they are outside the main panel container const setupPortal = (el: HTMLDivElement) => { attachStyles(el) const computedStyle = getComputedStyle(containerRef) const variable = computedStyle.getPropertyValue('--tsqd-font-size') el.style.setProperty('--tsqd-font-size', variable) } return ( <>
{ setSelectedView(value as 'queries' | 'mutations') setSelectedQueryHash(null) setSelectedMutationId(null) }} > Queries Mutations
{ if (selectedView() === 'queries') { props.setLocalStore('filter', e.currentTarget.value) } else { props.setLocalStore('mutationFilter', e.currentTarget.value) } }} class="tsqd-query-filter-textfield" name="tsqd-query-filter-input" value={ selectedView() === 'queries' ? props.localStore.filter || '' : props.localStore.mutationFilter || '' } />
setupPortal(el as HTMLDivElement)} mount={ pip().pipWindow ? pip().pipWindow!.document.body : document.body } >
Settings
Position setupPortal(el as HTMLDivElement)} mount={ pip().pipWindow ? pip().pipWindow!.document.body : document.body } > setDevtoolsPosition(value as DevtoolsPosition) } > Top Bottom Left Right Theme setupPortal(el as HTMLDivElement)} mount={ pip().pipWindow ? pip().pipWindow!.document.body : document.body } > { props.setLocalStore('theme_preference', value) }} aria-label="Theme preference" > Light Dark System Disabled Queries setupPortal(el as HTMLDivElement)} mount={ pip().pipWindow ? pip().pipWindow!.document.body : document.body } > props.setLocalStore('hideDisabledQueries', value) } > Show Hide
{(_cache) => ( query.queryHash} class="tsqd-style-overflow-query-container tsqd-queries-overflow-container" contentClass="tsqd-queries-container" > {(query) => } )} {(_cache) => ( mutation.mutationId} class="tsqd-style-overflow-query-container tsqd-mutations-overflow-container" contentClass="tsqd-mutations-container" > {(mutation) => } )}
) } const QueryRow: Component<{ query: Query }> = (props) => { const { selectedQueryHash, setSelectedQueryHash } = useDevtoolsState() const theme = useTheme() const themed = createThemed(theme) const queryState = createSubscribeToQueryCacheBatcher( (queryCache) => queryCache().get(props.query.queryHash)?.state, true, (e) => e.query.queryHash === props.query.queryHash, ) const isDisabled = createSubscribeToQueryCacheBatcher( (queryCache) => queryCache().get(props.query.queryHash)?.isDisabled() ?? false, true, (e) => e.query.queryHash === props.query.queryHash, ) const isStatic = createSubscribeToQueryCacheBatcher( (queryCache) => queryCache().get(props.query.queryHash)?.isStatic() ?? false, true, (e) => e.query.queryHash === props.query.queryHash, ) const isStale = createSubscribeToQueryCacheBatcher( (queryCache) => queryCache().get(props.query.queryHash)?.isStale() ?? false, true, (e) => e.query.queryHash === props.query.queryHash, ) const observers = createSubscribeToQueryCacheBatcher( (queryCache) => queryCache().get(props.query.queryHash)?.getObserversCount() ?? 0, true, (e) => e.query.queryHash === props.query.queryHash, ) const color = createMemo(() => getQueryStatusColor({ queryState: queryState(), observerCount: observers(), isStale: isStale(), }), ) return ( ) } const MutationRow: Component<{ mutation: Mutation }> = (props) => { const { selectedMutationId, setSelectedMutationId } = useDevtoolsState() const theme = useTheme() const themed = createThemed(theme) const mutationState = createSubscribeToMutationCacheBatcher( () => props.mutation.state, ) const isPaused = createSubscribeToMutationCacheBatcher( () => props.mutation.state.isPaused, ) const status = createSubscribeToMutationCacheBatcher( () => props.mutation.state.status, ) const color = createMemo(() => getMutationStatusColor({ isPaused: isPaused(), status: status(), }), ) return ( ) } const QueryStatusCount: Component = () => { const counts = createSubscribeToQueryCacheBatcher((queryCache) => { const tally = { fresh: 0, fetching: 0, paused: 0, stale: 0, inactive: 0 } for (const query of queryCache().getAll()) { tally[getQueryStatusLabel(query)]++ } return tally }) return (
) } const MutationStatusCount: Component = () => { const counts = createSubscribeToMutationCacheBatcher((mutationCache) => { const tally = { green: 0, yellow: 0, purple: 0, red: 0, gray: 0 } for (const mutation of mutationCache().getAll()) { tally[getMutationStatusColor(mutation.state)]++ } return tally }) return (
) } const QueryStatus: Component = (props) => { const { selectedQueryHash, panelWidth } = useDevtoolsState() const theme = useTheme() const themed = createThemed(theme) let tagRef!: HTMLButtonElement const [mouseOver, setMouseOver] = createSignal(false) const [focused, setFocused] = createSignal(false) const showLabel = createMemo(() => { if (selectedQueryHash()) { if (panelWidth() < firstBreakpoint && panelWidth() > secondBreakpoint) { return false } } if (panelWidth() < secondBreakpoint) { return false } return true }) return ( ) } const QueryDetails = (props: { initialSearch?: string }) => { const { selectedQueryHash, setSelectedQueryHash } = useDevtoolsState() const theme = useTheme() const themed = createThemed(theme) const queryClient = useQueryDevtoolsContext().client const [restoringLoading, setRestoringLoading] = createSignal(false) const [dataMode, setDataMode] = createSignal<'view' | 'edit'>('view') const [dataEditError, setDataEditError] = createSignal(false) const errorTypes = createMemo(() => { return useQueryDevtoolsContext().errorTypes || [] }) const activeQuery = createSubscribeToQueryCacheBatcher( (queryCache) => queryCache().get(selectedQueryHash() ?? ''), false, ) const activeQueryFresh = createSubscribeToQueryCacheBatcher((queryCache) => { return queryCache().get(selectedQueryHash() ?? '') }, false) const activeQueryState = createSubscribeToQueryCacheBatcher( (queryCache) => queryCache().get(selectedQueryHash() ?? '')?.state, false, ) const activeQueryStateData = createSubscribeToQueryCacheBatcher( (queryCache) => { return queryCache().get(selectedQueryHash() ?? '')?.state.data }, false, ) const statusLabel = createSubscribeToQueryCacheBatcher((queryCache) => { const query = queryCache().get(selectedQueryHash() ?? '') if (!query) return 'inactive' return getQueryStatusLabel(query) }) const queryStatus = createSubscribeToQueryCacheBatcher((queryCache) => { const query = queryCache().get(selectedQueryHash() ?? '') if (!query) return 'pending' return query.state.status }) const observerCount = createSubscribeToQueryCacheBatcher( (queryCache) => queryCache() .get(selectedQueryHash() ?? '') ?.getObserversCount() ?? 0, ) const color = createMemo(() => getQueryStatusColorByLabel(statusLabel())) const handleRefetch = () => { sendDevToolsEvent({ type: 'REFETCH', queryHash: activeQuery()?.queryHash }) const promise = activeQuery()?.fetch() promise?.catch(() => {}) } const triggerError = (errorType?: DevtoolsErrorType) => { const activeQueryVal = activeQuery() if (!activeQueryVal) return sendDevToolsEvent({ type: 'TRIGGER_ERROR', queryHash: activeQueryVal.queryHash, metadata: { error: errorType?.name }, }) const error = errorType?.initializer(activeQueryVal) ?? new Error('Unknown error from devtools') const __previousQueryOptions = activeQueryVal.options activeQueryVal.setState({ data: undefined, status: 'error', error, fetchMeta: { ...activeQueryVal.state.fetchMeta, __previousQueryOptions, } as any, }) } const restoreQueryAfterLoadingOrError = () => { const activeQueryVal = activeQuery() if (!activeQueryVal) return sendDevToolsEvent({ type: 'RESTORE_LOADING', queryHash: activeQueryVal.queryHash, }) const previousState = activeQueryVal.state const previousOptions = activeQueryVal.state.fetchMeta ? (activeQueryVal.state.fetchMeta as any).__previousQueryOptions : null activeQueryVal.cancel({ silent: true }) activeQueryVal.setState({ ...previousState, fetchStatus: 'idle', fetchMeta: null, }) if (previousOptions) { activeQueryVal.fetch(previousOptions) } } createEffect(() => { if (statusLabel() !== 'fetching') { setRestoringLoading(false) } }) return (
Query Details
              {displayValue(activeQuery()!.queryKey, true)}
            
{statusLabel()}
Observers: {observerCount()}
Last Updated: {new Date(activeQueryState()!.dataUpdatedAt).toLocaleTimeString()}
Actions
Trigger Error
Data {dataMode() === 'view' ? 'Explorer' : 'Editor'}
setDataMode('edit')} activeQuery={activeQuery()} />
{ e.preventDefault() const formData = new FormData(e.currentTarget) const data = formData.get('data') as string try { const parsedData = JSON.parse(data) activeQuery()!.setState({ ...activeQuery()!.state, data: parsedData, }) setDataMode('view') } catch (error) { setDataEditError(true) } }} >
{dataEditError() ? 'Invalid Value' : ''}
Query Explorer
) } const MutationDetails = (props: { initialSearch?: string }) => { const { selectedMutationId } = useDevtoolsState() const theme = useTheme() const themed = createThemed(theme) const isPaused = createSubscribeToMutationCacheBatcher((mutationCache) => { const mutations = mutationCache().getAll() const mutation = mutations.find( (m) => m.mutationId === selectedMutationId(), ) if (!mutation) return false return mutation.state.isPaused }) const status = createSubscribeToMutationCacheBatcher((mutationCache) => { const mutations = mutationCache().getAll() const mutation = mutations.find( (m) => m.mutationId === selectedMutationId(), ) if (!mutation) return 'idle' return mutation.state.status }) const color = createMemo(() => getMutationStatusColor({ isPaused: isPaused(), status: status(), }), ) const activeMutation = createSubscribeToMutationCacheBatcher( (mutationCache) => mutationCache() .getAll() .find((mutation) => mutation.mutationId === selectedMutationId()), false, ) const matchingSearch = (value: unknown) => props.initialSearch && matchesData(value, props.initialSearch.toLowerCase()) ? props.initialSearch : undefined return (
Mutation Details
              
                
                  {displayValue(activeMutation()!.options.mutationKey, true)}
                
              
            
pending {status()}
Submitted At: {new Date( activeMutation()!.state.submittedAt, ).toLocaleTimeString()}
Variables Details
Context Details
Data Explorer
Mutations Explorer
) } const setupQueryCacheSubscription = () => { const { queryCacheSubscriptions } = useDevtoolsSubscriptions() const queryCache = createMemo(() => { const client = useQueryDevtoolsContext().client return client.getQueryCache() }) createEffect(() => { const cache = queryCache() const unsubscribe = cache.subscribe((event) => { batch(() => { queryCacheSubscriptions.notify(() => cache, event) }) }) onCleanup(unsubscribe) }) } const createSubscribeToQueryCacheBatcher = ( callback: ( queryCache: Accessor, // oxlint-disable-next-line typescript/no-unsafe-function-type -- matches the 'Exclude' that Solid's 'Setter' accepts ) => Exclude, equalityCheck: boolean = true, shouldUpdate: (event: QueryCacheNotifyEvent) => boolean = () => true, ) => { const { queryCacheSubscriptions } = useDevtoolsSubscriptions() const queryCache = createMemo(() => { const client = useQueryDevtoolsContext().client return client.getQueryCache() }) const [value, setValue] = createSignal( callback(queryCache), !equalityCheck ? { equals: false } : undefined, ) createEffect(() => { setValue(callback(queryCache)) }) queryCacheSubscriptions.register(callback, setValue, shouldUpdate) return value } const setupMutationCacheSubscription = () => { const { mutationCacheSubscriptions } = useDevtoolsSubscriptions() const mutationCache = createMemo(() => { const client = useQueryDevtoolsContext().client return client.getMutationCache() }) createEffect(() => { const cache = mutationCache() let active = true const unsubscribe = cache.subscribe((event) => { mutationCacheSubscriptions.notify( () => cache, event, (update) => { queueMicrotask(() => { if (active) update() }) }, ) }) onCleanup(() => { active = false unsubscribe() }) }) } const createSubscribeToMutationCacheBatcher = ( callback: ( queryCache: Accessor, // oxlint-disable-next-line typescript/no-unsafe-function-type -- matches the 'Exclude' that Solid's 'Setter' accepts ) => Exclude, equalityCheck: boolean = true, shouldUpdate: (event: MutationCacheNotifyEvent) => boolean = () => true, ) => { const { mutationCacheSubscriptions } = useDevtoolsSubscriptions() const mutationCache = createMemo(() => { const client = useQueryDevtoolsContext().client return client.getMutationCache() }) const [value, setValue] = createSignal( callback(mutationCache), !equalityCheck ? { equals: false } : undefined, ) createEffect(() => { setValue(callback(mutationCache)) }) mutationCacheSubscriptions.register(callback, setValue, shouldUpdate) return value } type DevToolsActionType = | 'REFETCH' | 'INVALIDATE' | 'RESET' | 'REMOVE' | 'TRIGGER_ERROR' | 'RESTORE_ERROR' | 'TRIGGER_LOADING' | 'RESTORE_LOADING' | 'CLEAR_MUTATION_CACHE' | 'CLEAR_QUERY_CACHE' const DEV_TOOLS_EVENT = '@tanstack/query-devtools-event' const sendDevToolsEvent = ({ type, queryHash, metadata, }: { type: DevToolsActionType queryHash?: string metadata?: Record }) => { const event = new CustomEvent(DEV_TOOLS_EVENT, { detail: { type, queryHash, metadata }, bubbles: true, cancelable: true, }) window.dispatchEvent(event) }