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

with-devtools.ts

180 lines5.5 KB

1import { isPlatformBrowser } from '@angular/common'
2import {
3 DestroyRef,
4 ENVIRONMENT_INITIALIZER,
5 InjectionToken,
6 Injector,
7 PLATFORM_ID,
8 computed,
9 effect,
10 inject,
11 isDevMode,
12} from '@angular/core'
13import { QueryClient, noop, onlineManager } from '@tanstack/query-core'
14import { queryFeature } from '../providers'
15import type { Signal } from '@angular/core'
16import type {
17 DevtoolsOptions,
18 WithDevtools,
19 WithDevtoolsFn,
20 WithDevtoolsOptions,
21} from './types'
22import type { TanstackQueryDevtools } from '@tanstack/query-devtools'
23​
24/**
25 * Internal token used to prevent double providing of devtools in child injectors
26 */
27const DEVTOOLS_PROVIDED = new InjectionToken('', {
28 factory: () => ({
29 isProvided: false,
30 }),
31})
32​
33/**
34 * Internal token for providing devtools options
35 */
36const DEVTOOLS_OPTIONS_SIGNAL = new InjectionToken<Signal<DevtoolsOptions>>('')
37​
38/**
39 * Enables developer tools in Angular development builds.
40 *
41 * **Example**
42 *
43 * ```ts
44 * export const appConfig: ApplicationConfig = {
45 * providers: [
46 * provideTanStackQuery(new QueryClient(), withDevtools())
47 * ]
48 * }
49 * ```
50 * The devtools will be rendered in `<body>`.
51 *
52 * If you need more control over when devtools are loaded, you can use the `loadDevtools` option.
53 *
54 * If you need more control over where devtools are rendered, consider `injectDevtoolsPanel`. This allows rendering devtools inside your own devtools for example.
55 * @param withDevtoolsFn - A function that returns `DevtoolsOptions`.
56 * @param options - Additional options for configuring `withDevtools`.
57 * @returns A set of providers for use with `provideTanStackQuery`.
58 * @see {@link provideTanStackQuery}
59 * @see {@link DevtoolsOptions}
60 */
61export const withDevtools: WithDevtools = (
62 withDevtoolsFn?: WithDevtoolsFn,
63 options: WithDevtoolsOptions = {},
64) =>
65 queryFeature('Devtools', [
66 {
67 provide: DEVTOOLS_OPTIONS_SIGNAL,
68 useFactory: (...deps: Array<any>) =>
69 computed(() => withDevtoolsFn?.(...deps) ?? {}),
70 deps: options.deps || [],
71 },
72 {
73 // Do not use provideEnvironmentInitializer while Angular < v19 is supported
74 provide: ENVIRONMENT_INITIALIZER,
75 multi: true,
76 useFactory: () => {
77 const devtoolsProvided = inject(DEVTOOLS_PROVIDED)
78 if (
79 !isPlatformBrowser(inject(PLATFORM_ID)) ||
80 devtoolsProvided.isProvided
81 )
82 return noop
83​
84 devtoolsProvided.isProvided = true
85 let injectorIsDestroyed = false
86 inject(DestroyRef).onDestroy(() => (injectorIsDestroyed = true))
87​
88 return () => {
89 const injectedClient = inject(QueryClient, {
90 optional: true,
91 })
92 const destroyRef = inject(DestroyRef)
93 const devtoolsOptions = inject(DEVTOOLS_OPTIONS_SIGNAL)
94 const injector = inject(Injector)
95​
96 let devtools: TanstackQueryDevtools | null = null
97 let el: HTMLElement | null = null
98​
99 const shouldLoadToolsSignal = computed(() => {
100 const { loadDevtools } = devtoolsOptions()
101 return typeof loadDevtools === 'boolean'
102 ? loadDevtools
103 : isDevMode()
104 })
105​
106 const getResolvedQueryClient = () => {
107 const client = devtoolsOptions().client ?? injectedClient
108 if (!client) {
109 throw new Error('No QueryClient found')
110 }
111 return client
112 }
113​
114 const destroyDevtools = () => {
115 devtools?.unmount()
116 el?.remove()
117 devtools = null
118 }
119​
120 effect(
121 () => {
122 const shouldLoadTools = shouldLoadToolsSignal()
123 const {
124 client,
125 position,
126 errorTypes,
127 buttonPosition,
128 initialIsOpen,
129 } = devtoolsOptions()
130​
131 if (!shouldLoadTools) {
132 // Destroy or do nothing
133 devtools && destroyDevtools()
134 return
135 }
136​
137 if (devtools) {
138 // Update existing devtools config
139 client && devtools.setClient(client)
140 position && devtools.setPosition(position)
141 errorTypes && devtools.setErrorTypes(errorTypes)
142 buttonPosition && devtools.setButtonPosition(buttonPosition)
143 typeof initialIsOpen === 'boolean' &&
144 devtools.setInitialIsOpen(initialIsOpen)
145 return
146 }
147​
148 // Create devtools
149 import('@tanstack/query-devtools')
150 .then((queryDevtools) => {
151 // As this code runs async, the injector could have been destroyed
152 if (injectorIsDestroyed) return
153​
154 devtools = new queryDevtools.TanstackQueryDevtools({
155 ...devtoolsOptions(),
156 client: getResolvedQueryClient(),
157 queryFlavor: 'Angular Query',
158 version: '5',
159 onlineManager,
160 })
161​
162 el = document.body.appendChild(document.createElement('div'))
163 el.classList.add('tsqd-parent-container')
164 devtools.mount(el)
165​
166 destroyRef.onDestroy(destroyDevtools)
167 })
168 .catch((error) => {
169 console.error(
170 'Install @tanstack/query-devtools or reinstall without --omit=optional.',
171 error,
172 )
173 })
174 },
175 { injector },
176 )
177 }
178 },
179 },
180 ])