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

with-devtools.ts

190 lines5.7 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 signal,
13} from '@angular/core'
14import { QueryClient, noop, onlineManager } from '@tanstack/query-core'
15import { queryFeature } from '../providers'
16import type { Signal } from '@angular/core'
17import type {
18 DevtoolsOptions,
19 WithDevtools,
20 WithDevtoolsFn,
21 WithDevtoolsOptions,
22} from './types'
23import type { TanstackQueryDevtools } from '@tanstack/query-devtools'
24​
25/**
26 * Internal token used to prevent double providing of devtools in child injectors
27 */
28const DEVTOOLS_PROVIDED = new InjectionToken('', {
29 factory: () => ({
30 isProvided: false,
31 }),
32})
33​
34/**
35 * Internal token for providing devtools options
36 */
37const DEVTOOLS_OPTIONS_SIGNAL = new InjectionToken<Signal<DevtoolsOptions>>('')
38​
39/**
40 * Enables developer tools in Angular development builds.
41 *
42 * **Example**
43 *
44 * ```ts
45 * export const appConfig: ApplicationConfig = {
46 * providers: [
47 * provideTanStackQuery(new QueryClient(), withDevtools())
48 * ]
49 * }
50 * ```
51 * The devtools will be rendered in `<body>`.
52 *
53 * If you need more control over when devtools are loaded, you can use the `loadDevtools` option.
54 *
55 * If you need more control over where devtools are rendered, consider `injectDevtoolsPanel`. This allows rendering devtools inside your own devtools for example.
56 * @param withDevtoolsFn - A function that returns `DevtoolsOptions`.
57 * @param options - Additional options for configuring `withDevtools`.
58 * @returns A set of providers for use with `provideTanStackQuery`.
59 * @see {@link provideTanStackQuery}
60 * @see {@link DevtoolsOptions}
61 */
62export const withDevtools: WithDevtools = (
63 withDevtoolsFn?: WithDevtoolsFn,
64 options: WithDevtoolsOptions = {},
65) =>
66 queryFeature('Devtools', [
67 {
68 provide: DEVTOOLS_OPTIONS_SIGNAL,
69 useFactory: (...deps: Array<any>) =>
70 computed(() => withDevtoolsFn?.(...deps) ?? {}),
71 deps: options.deps || [],
72 },
73 {
74 // Do not use provideEnvironmentInitializer while Angular < v19 is supported
75 provide: ENVIRONMENT_INITIALIZER,
76 multi: true,
77 useFactory: () => {
78 const devtoolsProvided = inject(DEVTOOLS_PROVIDED)
79 if (
80 !isPlatformBrowser(inject(PLATFORM_ID)) ||
81 devtoolsProvided.isProvided
82 )
83 return noop
84​
85 devtoolsProvided.isProvided = true
86​
87 return () => {
88 const injectedClient = inject(QueryClient, {
89 optional: true,
90 })
91 const destroyRef = inject(DestroyRef)
92 const devtoolsOptions = inject(DEVTOOLS_OPTIONS_SIGNAL)
93 const injector = inject(Injector)
94​
95 let devtools: TanstackQueryDevtools | null = null
96 let el: HTMLElement | null = null
97 let devtoolsImport: Promise<void> | null = null
98 const devtoolsClass = signal<typeof TanstackQueryDevtools | null>(
99 null,
100 )
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 theme,
133 } = devtoolsOptions()
134 const Devtools = devtoolsClass()
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 devtools.setTheme(theme)
151 return
152 }
153​
154 const resolvedClient = getResolvedQueryClient()
155​
156 if (!Devtools) {
157 devtoolsImport ??= import('@tanstack/query-devtools')
158 .then((queryDevtools) => {
159 devtoolsClass.set(queryDevtools.TanstackQueryDevtools)
160 })
161 .catch((error) => {
162 console.error(
163 'Install @tanstack/query-devtools or reinstall without --omit=optional.',
164 error,
165 )
166 })
167 return
168 }
169​
170 // Create devtools
171 devtools = new Devtools({
172 ...devtoolsOptions(),
173 client: resolvedClient,
174 queryFlavor: 'Angular Query',
175 version: '5',
176 onlineManager,
177 })
178​
179 el = document.body.appendChild(document.createElement('div'))
180 el.classList.add('tsqd-parent-container')
181 devtools.mount(el)
182​
183 destroyRef.onDestroy(destroyDevtools)
184 },
185 { injector },
186 )
187 }
188 },
189 },
190 ])