Open History to see the last commit
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 theme,
130 } = devtoolsOptions()
131β
132 if (!shouldLoadTools) {
133 // Destroy or do nothing
134 devtools && destroyDevtools()
135 return
136 }
137β
138 if (devtools) {
139 // Update existing devtools config
140 client && devtools.setClient(client)
141 position && devtools.setPosition(position)
142 errorTypes && devtools.setErrorTypes(errorTypes)
143 buttonPosition && devtools.setButtonPosition(buttonPosition)
144 typeof initialIsOpen === 'boolean' &&
145 devtools.setInitialIsOpen(initialIsOpen)
146 theme && devtools.setTheme(theme)
147 return
148 }
149β
150 // Create devtools
151 import('@tanstack/query-devtools')
152 .then((queryDevtools) => {
153 // As this code runs async, the injector could have been destroyed
154 if (injectorIsDestroyed) return
155β
156 devtools = new queryDevtools.TanstackQueryDevtools({
157 ...devtoolsOptions(),
158 client: getResolvedQueryClient(),
159 queryFlavor: 'Angular Query',
160 version: '5',
161 onlineManager,
162 })
163β
164 el = document.body.appendChild(document.createElement('div'))
165 el.classList.add('tsqd-parent-container')
166 devtools.mount(el)
167β
168 destroyRef.onDestroy(destroyDevtools)
169 })
170 .catch((error) => {
171 console.error(
172 'Install @tanstack/query-devtools or reinstall without --omit=optional.',
173 error,
174 )
175 })
176 },
177 { injector },
178 )
179 }
180 },
181 },
182 ])