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

with-devtools.ts

184 lines5.6 KB

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
26 * injectors
27 */
28const DEVTOOLS_PROVIDED = new InjectionToken('', {
29 factory: () => ({
30 isProvided: false,
31 }),
32})
33​
34/** Internal token for providing devtools options */
35const DEVTOOLS_OPTIONS_SIGNAL = new InjectionToken<Signal<DevtoolsOptions>>('')
36​
37/**
38 * Enables developer tools in Angular development builds.
39 *
40 * **Example**
41 *
42 * ```ts
43 * export const appConfig: ApplicationConfig = {
44 * providers: [provideTanStackQuery(new QueryClient(), withDevtools())],
45 * }
46 * ```
47 *
48 * The devtools will be rendered in `<body>`.
49 *
50 * If you need more control over when devtools are loaded, you can use the
51 * `loadDevtools` option.
52 *
53 * If you need more control over where devtools are rendered, consider
54 * `injectDevtoolsPanel`. This allows rendering devtools inside your own
55 * devtools for example.
56 *
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 // Do not use provideEnvironmentInitializer while Angular < v19 is supported
76 provide: ENVIRONMENT_INITIALIZER,
77 multi: true,
78 useFactory: () => {
79 const devtoolsProvided = inject(DEVTOOLS_PROVIDED)
80 if (
81 !isPlatformBrowser(inject(PLATFORM_ID)) ||
82 devtoolsProvided.isProvided
83 )
84 return noop
85​
86 devtoolsProvided.isProvided = true
87 let injectorIsDestroyed = false
88 inject(DestroyRef).onDestroy(() => (injectorIsDestroyed = true))
89​
90 return () => {
91 const injectedClient = inject(QueryClient, {
92 optional: true,
93 })
94 const destroyRef = inject(DestroyRef)
95 const devtoolsOptions = inject(DEVTOOLS_OPTIONS_SIGNAL)
96 const injector = inject(Injector)
97​
98 let devtools: TanstackQueryDevtools | null = null
99 let el: HTMLElement | null = null
100​
101 const shouldLoadToolsSignal = computed(() => {
102 const { loadDevtools } = devtoolsOptions()
103 return typeof loadDevtools === 'boolean'
104 ? loadDevtools
105 : isDevMode()
106 })
107​
108 const getResolvedQueryClient = () => {
109 const client = devtoolsOptions().client ?? injectedClient
110 if (!client) {
111 throw new Error('No QueryClient found')
112 }
113 return client
114 }
115​
116 const destroyDevtools = () => {
117 devtools?.unmount()
118 el?.remove()
119 devtools = null
120 }
121​
122 effect(
123 () => {
124 const shouldLoadTools = shouldLoadToolsSignal()
125 const {
126 client,
127 position,
128 errorTypes,
129 buttonPosition,
130 initialIsOpen,
131 theme,
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 theme && devtools.setTheme(theme)
149 return
150 }
151​
152 // Create devtools
153 import('@tanstack/query-devtools')
154 .then((queryDevtools) => {
155 // As this code runs async, the injector could have been destroyed
156 if (injectorIsDestroyed) return
157​
158 devtools = new queryDevtools.TanstackQueryDevtools({
159 ...devtoolsOptions(),
160 client: getResolvedQueryClient(),
161 queryFlavor: 'Angular Query',
162 version: '5',
163 onlineManager,
164 })
165​
166 el = document.body.appendChild(document.createElement('div'))
167 el.classList.add('tsqd-parent-container')
168 devtools.mount(el)
169​
170 destroyRef.onDestroy(destroyDevtools)
171 })
172 .catch((error) => {
173 console.error(
174 'Install @tanstack/query-devtools or reinstall without --omit=optional.',
175 error,
176 )
177 })
178 },
179 { injector },
180 )
181 }
182 },
183 },
184 ])