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

with-devtools.ts

183 lines5.6 KB

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