Open History to see the last commit
1import {
2 DestroyRef,
3 ENVIRONMENT_INITIALIZER,
4 Injector,
5 PLATFORM_ID,
6 computed,
7 effect,
8 inject,
9 makeEnvironmentProviders,
10 runInInjectionContext,
11} from '@angular/core'
12import { QueryClient, onlineManager } from '@tanstack/query-core'
13import { isPlatformBrowser } from '@angular/common'
14import { isDevMode } from './util/is-dev-mode/is-dev-mode'
15import { noop } from './util'
16import type { EnvironmentProviders, Provider } from '@angular/core'
17import type {
18 DevtoolsButtonPosition,
19 DevtoolsErrorType,
20 DevtoolsPosition,
21 TanstackQueryDevtools,
22} from '@tanstack/query-devtools'
23​
24/**
25 * Usually {@link provideTanStackQuery} is used once to set up TanStack Query and the
26 * {@link https://tanstack.com/query/latest/docs/reference/QueryClient|QueryClient}
27 * for the entire application. You can use `provideQueryClient` to provide a
28 * different `QueryClient` instance for a part of the application.
29 * @param queryClient - the `QueryClient` instance to provide.
30 * @public
31 */
32export function provideQueryClient(queryClient: QueryClient) {
33 return { provide: QueryClient, useValue: queryClient }
34}
35​
36/**
37 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
38 *
39 * Allows to configure a `QueryClient` and optional features such as developer tools.
40 *
41 * **Example - standalone**
42 *
43 * ```ts
44 * import {
45 * provideTanStackQuery,
46 * QueryClient,
47 * } from '@tanstack/angular-query-experimental'
48 *
49 * bootstrapApplication(AppComponent, {
50 * providers: [provideTanStackQuery(new QueryClient())],
51 * })
52 * ```
53 *
54 * **Example - NgModule-based**
55 *
56 * ```ts
57 * import {
58 * provideTanStackQuery,
59 * QueryClient,
60 * } from '@tanstack/angular-query-experimental'
61 *
62 * @NgModule({
63 * declarations: [AppComponent],
64 * imports: [BrowserModule],
65 * providers: [provideTanStackQuery(new QueryClient())],
66 * bootstrap: [AppComponent],
67 * })
68 * export class AppModule {}
69 * ```
70 *
71 * You can also enable optional developer tools by adding `withDevtools`. By
72 * default the tools will then be loaded when your app is in development mode.
73 * ```ts
74 * import {
75 * provideTanStackQuery,
76 * withDevtools
77 * QueryClient,
78 * } from '@tanstack/angular-query-experimental'
79 *
80 * bootstrapApplication(AppComponent,
81 * {
82 * providers: [
83 * provideTanStackQuery(new QueryClient(), withDevtools())
84 * ]
85 * }
86 * )
87 * ```
88 * @param queryClient - A `QueryClient` instance.
89 * @param features - Optional features to configure additional Query functionality.
90 * @returns A set of providers to set up TanStack Query.
91 * @public
92 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
93 * @see withDevtools
94 */
95export function provideTanStackQuery(
96 queryClient: QueryClient,
97 ...features: Array<QueryFeatures>
98): EnvironmentProviders {
99 return makeEnvironmentProviders([
100 provideQueryClient(queryClient),
101 {
102 // Do not use provideEnvironmentInitializer to support Angular < v19
103 provide: ENVIRONMENT_INITIALIZER,
104 multi: true,
105 useValue: () => {
106 queryClient.mount()
107 // Unmount the query client on application destroy
108 inject(DestroyRef).onDestroy(() => queryClient.unmount())
109 },
110 },
111 features.map((feature) => feature.ɵproviders),
112 ])
113}
114​
115/**
116 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
117 *
118 * Allows to configure a `QueryClient`.
119 * @param queryClient - A `QueryClient` instance.
120 * @returns A set of providers to set up TanStack Query.
121 * @public
122 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
123 * @deprecated Use `provideTanStackQuery` instead.
124 */
125export function provideAngularQuery(
126 queryClient: QueryClient,
127): EnvironmentProviders {
128 return provideTanStackQuery(queryClient)
129}
130​
131/**
132 * Helper type to represent a Query feature.
133 */
134export interface QueryFeature<TFeatureKind extends QueryFeatureKind> {
135 ɵkind: TFeatureKind
136 ɵproviders: Array<Provider>
137}
138​
139/**
140 * Helper function to create an object that represents a Query feature.
141 * @param kind -
142 * @param providers -
143 * @returns A Query feature.
144 */
145function queryFeature<TFeatureKind extends QueryFeatureKind>(
146 kind: TFeatureKind,
147 providers: Array<Provider>,
148): QueryFeature<TFeatureKind> {
149 return { ɵkind: kind, ɵproviders: providers }
150}
151​
152/**
153 * A type alias that represents a feature which enables developer tools.
154 * The type is used to describe the return value of the `withDevtools` function.
155 * @public
156 * @see {@link withDevtools}
157 */
158export type DeveloperToolsFeature = QueryFeature<'DeveloperTools'>
159​
160/**
161 * Options for configuring the TanStack Query devtools.
162 * @public
163 */
164export interface DevtoolsOptions {
165 /**
166 * Set this true if you want the devtools to default to being open
167 */
168 initialIsOpen?: boolean
169 /**
170 * The position of the TanStack logo to open and close the devtools panel.
171 * `top-left` | `top-right` | `bottom-left` | `bottom-right` | `relative`
172 * Defaults to `bottom-right`.
173 */
174 buttonPosition?: DevtoolsButtonPosition
175 /**
176 * The position of the TanStack Query devtools panel.
177 * `top` | `bottom` | `left` | `right`
178 * Defaults to `bottom`.
179 */
180 position?: DevtoolsPosition
181 /**
182 * Custom instance of QueryClient
183 */
184 client?: QueryClient
185 /**
186 * Use this so you can define custom errors that can be shown in the devtools.
187 */
188 errorTypes?: Array<DevtoolsErrorType>
189 /**
190 * Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
191 */
192 styleNonce?: string
193 /**
194 * Use this so you can attach the devtool's styles to a specific element in the DOM.
195 */
196 shadowDOMTarget?: ShadowRoot
197​
198 /**
199 * Whether the developer tools should load.
200 * - `auto`- (Default) Lazily loads devtools when in development mode. Skips loading in production mode.
201 * - `true`- Always load the devtools, regardless of the environment.
202 * - `false`- Never load the devtools, regardless of the environment.
203 *
204 * You can use `true` and `false` to override loading developer tools from an environment file.
205 * For example, a test environment might run in production mode but you may want to load developer tools.
206 *
207 * Additionally, you can use a signal in the callback to dynamically load the devtools based on a condition. For example,
208 * a signal created from a RxJS observable that listens for a keyboard shortcut.
209 *
210 * **Example**
211 * ```ts
212 * withDevtools(() => ({
213 * initialIsOpen: true,
214 * loadDevtools: inject(ExampleService).loadDevtools()
215 * }))
216 * ```
217 */
218 loadDevtools?: 'auto' | boolean
219}
220​
221/**
222 * Enables developer tools.
223 *
224 * **Example**
225 *
226 * ```ts
227 * export const appConfig: ApplicationConfig = {
228 * providers: [
229 * provideTanStackQuery(new QueryClient(), withDevtools())
230 * ]
231 * }
232 * ```
233 * By default the devtools will be loaded when Angular runs in development mode and rendered in `<body>`.
234 *
235 * If you need more control over when devtools are loaded, you can use the `loadDevtools` option. This is particularly useful if you want to load devtools based on environment configurations. For instance, you might have a test environment running in production mode but still require devtools to be available.
236 *
237 * If you need more control over where devtools are rendered, consider `injectDevtoolsPanel`. This allows rendering devtools inside your own devtools for example.
238 * @param optionsFn - A function that returns `DevtoolsOptions`.
239 * @returns A set of providers for use with `provideTanStackQuery`.
240 * @public
241 * @see {@link provideTanStackQuery}
242 * @see {@link DevtoolsOptions}
243 */
244export function withDevtools(
245 optionsFn?: () => DevtoolsOptions,
246): DeveloperToolsFeature {
247 let providers: Array<Provider> = []
248 if (!isDevMode() && !optionsFn) {
249 providers = []
250 } else {
251 providers = [
252 {
253 provide: ENVIRONMENT_INITIALIZER,
254 multi: true,
255 useFactory: () => {
256 if (!isPlatformBrowser(inject(PLATFORM_ID))) return noop
257 const injector = inject(Injector)
258 const options = computed(() =>
259 runInInjectionContext(injector, () => optionsFn?.() ?? {}),
260 )
261​
262 let devtools: TanstackQueryDevtools | null = null
263 let el: HTMLElement | null = null
264​
265 const shouldLoadToolsSignal = computed(() => {
266 const { loadDevtools } = options()
267 return typeof loadDevtools === 'boolean'
268 ? loadDevtools
269 : isDevMode()
270 })
271​
272 const destroyRef = inject(DestroyRef)
273​
274 const getResolvedQueryClient = () => {
275 const injectedClient = injector.get(QueryClient, null)
276 const client = options().client ?? injectedClient
277 if (!client) {
278 throw new Error('No QueryClient found')
279 }
280 return client
281 }
282​
283 const destroyDevtools = () => {
284 devtools?.unmount()
285 el?.remove()
286 devtools = null
287 }
288​
289 return () =>
290 effect(() => {
291 const shouldLoadTools = shouldLoadToolsSignal()
292 const {
293 client,
294 position,
295 errorTypes,
296 buttonPosition,
297 initialIsOpen,
298 } = options()
299​
300 if (devtools && !shouldLoadTools) {
301 destroyDevtools()
302 return
303 } else if (devtools && shouldLoadTools) {
304 client && devtools.setClient(client)
305 position && devtools.setPosition(position)
306 errorTypes && devtools.setErrorTypes(errorTypes)
307 buttonPosition && devtools.setButtonPosition(buttonPosition)
308 initialIsOpen && devtools.setInitialIsOpen(initialIsOpen)
309 return
310 } else if (!shouldLoadTools) {
311 return
312 }
313​
314 el = document.body.appendChild(document.createElement('div'))
315 el.classList.add('tsqd-parent-container')
316​
317 import('@tanstack/query-devtools').then((queryDevtools) =>
318 runInInjectionContext(injector, () => {
319 devtools = new queryDevtools.TanstackQueryDevtools({
320 ...options(),
321 client: getResolvedQueryClient(),
322 queryFlavor: 'Angular Query',
323 version: '5',
324 onlineManager,
325 })
326​
327 el && devtools.mount(el)
328​
329 // Unmount the devtools on application destroy
330 destroyRef.onDestroy(destroyDevtools)
331 }),
332 )
333 })
334 },
335 },
336 ]
337 }
338 return queryFeature('DeveloperTools', providers)
339}
340​
341/**
342 * A type alias that represents all Query features available for use with `provideTanStackQuery`.
343 * Features can be enabled by adding special functions to the `provideTanStackQuery` call.
344 * See documentation for each symbol to find corresponding function name. See also `provideTanStackQuery`
345 * documentation on how to use those functions.
346 * @public
347 * @see {@link provideTanStackQuery}
348 */
349export type QueryFeatures = DeveloperToolsFeature // Union type of features but just one now
350​
351export const queryFeatures = ['DeveloperTools'] as const
352​
353export type QueryFeatureKind = (typeof queryFeatures)[number]