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 provide: ENVIRONMENT_INITIALIZER,
103 multi: true,
104 useValue: () => {
105 queryClient.mount()
106 // Unmount the query client on application destroy
107 inject(DestroyRef).onDestroy(() => queryClient.unmount())
108 },
109 },
110 features.map((feature) => feature.ɵproviders),
111 ])
112}
113​
114/**
115 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
116 *
117 * Allows to configure a `QueryClient`.
118 * @param queryClient - A `QueryClient` instance.
119 * @returns A set of providers to set up TanStack Query.
120 * @public
121 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
122 * @deprecated Use `provideTanStackQuery` instead.
123 */
124export function provideAngularQuery(
125 queryClient: QueryClient,
126): EnvironmentProviders {
127 return provideTanStackQuery(queryClient)
128}
129​
130/**
131 * Helper type to represent a Query feature.
132 */
133export interface QueryFeature<TFeatureKind extends QueryFeatureKind> {
134 ɵkind: TFeatureKind
135 ɵproviders: Array<Provider>
136}
137​
138/**
139 * Helper function to create an object that represents a Query feature.
140 * @param kind -
141 * @param providers -
142 * @returns A Query feature.
143 */
144function queryFeature<TFeatureKind extends QueryFeatureKind>(
145 kind: TFeatureKind,
146 providers: Array<Provider>,
147): QueryFeature<TFeatureKind> {
148 return { ɵkind: kind, ɵproviders: providers }
149}
150​
151/**
152 * A type alias that represents a feature which enables developer tools.
153 * The type is used to describe the return value of the `withDevtools` function.
154 * @public
155 * @see {@link withDevtools}
156 */
157export type DeveloperToolsFeature = QueryFeature<'DeveloperTools'>
158​
159/**
160 * Options for configuring the TanStack Query devtools.
161 * @public
162 */
163export interface DevtoolsOptions {
164 /**
165 * Set this true if you want the devtools to default to being open
166 */
167 initialIsOpen?: boolean
168 /**
169 * The position of the TanStack logo to open and close the devtools panel.
170 * `top-left` | `top-right` | `bottom-left` | `bottom-right` | `relative`
171 * Defaults to `bottom-right`.
172 */
173 buttonPosition?: DevtoolsButtonPosition
174 /**
175 * The position of the TanStack Query devtools panel.
176 * `top` | `bottom` | `left` | `right`
177 * Defaults to `bottom`.
178 */
179 position?: DevtoolsPosition
180 /**
181 * Custom instance of QueryClient
182 */
183 client?: QueryClient
184 /**
185 * Use this so you can define custom errors that can be shown in the devtools.
186 */
187 errorTypes?: Array<DevtoolsErrorType>
188 /**
189 * 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.
190 */
191 styleNonce?: string
192 /**
193 * Use this so you can attach the devtool's styles to a specific element in the DOM.
194 */
195 shadowDOMTarget?: ShadowRoot
196​
197 /**
198 * Whether the developer tools should load.
199 * - `auto`- (Default) Lazily loads devtools when in development mode. Skips loading in production mode.
200 * - `true`- Always load the devtools, regardless of the environment.
201 * - `false`- Never load the devtools, regardless of the environment.
202 *
203 * You can use `true` and `false` to override loading developer tools from an environment file.
204 * For example, a test environment might run in production mode but you may want to load developer tools.
205 *
206 * Additionally, you can use a signal in the callback to dynamically load the devtools based on a condition. For example,
207 * a signal created from a RxJS observable that listens for a keyboard shortcut.
208 *
209 * **Example**
210 * ```ts
211 * withDevtools(() => ({
212 * initialIsOpen: true,
213 * loadDevtools: inject(ExampleService).loadDevtools()
214 * }))
215 * ```
216 */
217 loadDevtools?: 'auto' | boolean
218}
219​
220/**
221 * Enables developer tools.
222 *
223 * **Example**
224 *
225 * ```ts
226 * export const appConfig: ApplicationConfig = {
227 * providers: [
228 * provideTanStackQuery(new QueryClient(), withDevtools())
229 * ]
230 * }
231 * ```
232 * By default the devtools will be loaded when Angular runs in development mode and rendered in `<body>`.
233 *
234 * 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.
235 *
236 * If you need more control over where devtools are rendered, consider `injectDevtoolsPanel`. This allows rendering devtools inside your own devtools for example.
237 * @param optionsFn - A function that returns `DevtoolsOptions`.
238 * @returns A set of providers for use with `provideTanStackQuery`.
239 * @public
240 * @see {@link provideTanStackQuery}
241 * @see {@link DevtoolsOptions}
242 */
243export function withDevtools(
244 optionsFn?: () => DevtoolsOptions,
245): DeveloperToolsFeature {
246 let providers: Array<Provider> = []
247 if (!isDevMode() && !optionsFn) {
248 providers = []
249 } else {
250 providers = [
251 {
252 provide: ENVIRONMENT_INITIALIZER,
253 multi: true,
254 useFactory: () => {
255 if (!isPlatformBrowser(inject(PLATFORM_ID))) return noop
256 const injector = inject(Injector)
257 const options = computed(() =>
258 runInInjectionContext(injector, () => optionsFn?.() ?? {}),
259 )
260​
261 let devtools: TanstackQueryDevtools | null = null
262 let el: HTMLElement | null = null
263​
264 const shouldLoadToolsSignal = computed(() => {
265 const { loadDevtools } = options()
266 return typeof loadDevtools === 'boolean'
267 ? loadDevtools
268 : isDevMode()
269 })
270​
271 const destroyRef = inject(DestroyRef)
272​
273 const getResolvedQueryClient = () => {
274 const injectedClient = injector.get(QueryClient, null)
275 const client = options().client ?? injectedClient
276 if (!client) {
277 throw new Error('No QueryClient found')
278 }
279 return client
280 }
281​
282 const destroyDevtools = () => {
283 devtools?.unmount()
284 el?.remove()
285 devtools = null
286 }
287​
288 return () =>
289 effect(() => {
290 const shouldLoadTools = shouldLoadToolsSignal()
291 const {
292 client,
293 position,
294 errorTypes,
295 buttonPosition,
296 initialIsOpen,
297 } = options()
298​
299 if (devtools && !shouldLoadTools) {
300 destroyDevtools()
301 return
302 } else if (devtools && shouldLoadTools) {
303 client && devtools.setClient(client)
304 position && devtools.setPosition(position)
305 errorTypes && devtools.setErrorTypes(errorTypes)
306 buttonPosition && devtools.setButtonPosition(buttonPosition)
307 initialIsOpen && devtools.setInitialIsOpen(initialIsOpen)
308 return
309 } else if (!shouldLoadTools) {
310 return
311 }
312​
313 el = document.body.appendChild(document.createElement('div'))
314 el.classList.add('tsqd-parent-container')
315​
316 import('@tanstack/query-devtools').then((queryDevtools) =>
317 runInInjectionContext(injector, () => {
318 devtools = new queryDevtools.TanstackQueryDevtools({
319 ...options(),
320 client: getResolvedQueryClient(),
321 queryFlavor: 'Angular Query',
322 version: '5',
323 onlineManager,
324 })
325​
326 el && devtools.mount(el)
327​
328 // Unmount the devtools on application destroy
329 destroyRef.onDestroy(destroyDevtools)
330 }),
331 )
332 })
333 },
334 },
335 ]
336 }
337 return queryFeature('DeveloperTools', providers)
338}
339​
340/**
341 * A type alias that represents all Query features available for use with `provideTanStackQuery`.
342 * Features can be enabled by adding special functions to the `provideTanStackQuery` call.
343 * See documentation for each symbol to find corresponding function name. See also `provideTanStackQuery`
344 * documentation on how to use those functions.
345 * @public
346 * @see {@link provideTanStackQuery}
347 */
348export type QueryFeatures = DeveloperToolsFeature // Union type of features but just one now
349​
350export const queryFeatures = ['DeveloperTools'] as const
351​
352export type QueryFeatureKind = (typeof queryFeatures)[number]