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