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

with-devtools.ts

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