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

with-devtools.ts

172 lines5.4 KB

1import { isPlatformBrowser } from '@angular/common'
2import {
3 DestroyRef,
4 InjectionToken,
5 PLATFORM_ID,
6 afterNextRender,
7 afterRenderEffect,
8 inject,
9 isDevMode,
10 isSignal,
11 makeEnvironmentProviders,
12 provideEnvironmentInitializer,
13} from '@angular/core'
14import { queryFeature } from '@tanstack/angular-query/internal'
15import { QueryClient, onlineManager } from '@tanstack/query-core'
16import { TanstackQueryDevtools } from '@tanstack/query-devtools'
17import type { Signal } from '@angular/core'
18import type { DevtoolsOptions, WithDevtools } from './types'
19​
20/**
21 * Internal token used to prevent double providing of devtools in child injectors
22 */
23const DEVTOOLS_PROVIDED = new InjectionToken('', {
24 factory: () => ({
25 isProvided: false,
26 }),
27})
28​
29/** Internal token for providing devtools options. */
30const DEVTOOLS_OPTIONS = new InjectionToken<DevtoolsOptions>('')
31​
32function resolveOption<T>(option: T | Signal<T | undefined> | undefined) {
33 return isSignal(option) ? option() : option
35​
36/**
37 * Enables developer tools in Angular development builds.
38 *
39 * **Example**
40 *
41 * ```ts
42 * export const appConfig: ApplicationConfig = {
43 * providers: [
44 * 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 `loadDevtools` option.
51 *
52 * If you need more control over where devtools are rendered, consider `injectDevtoolsPanel`. This allows rendering devtools inside your own devtools for example.
53 * @param withDevtoolsFn - A function that returns `DevtoolsOptions`. It runs
54 * once in an Angular injection context and can call `inject()`. Return signals
55 * as individual mutable option values to update them reactively.
56 * @returns A set of providers for use with `provideTanStackQuery`.
57 * @see {@link provideTanStackQuery}
58 * @see {@link DevtoolsOptions}
59 */
60export const withDevtools: WithDevtools = (withDevtoolsFn) =>
61 queryFeature(
62 makeEnvironmentProviders([
63 {
64 provide: DEVTOOLS_OPTIONS,
65 useFactory: () => withDevtoolsFn?.() ?? {},
66 },
67 provideEnvironmentInitializer(() => {
68 const devtoolsProvided = inject(DEVTOOLS_PROVIDED)
69 if (
70 !isPlatformBrowser(inject(PLATFORM_ID)) ||
71 devtoolsProvided.isProvided
72 )
73 return
74​
75 devtoolsProvided.isProvided = true
76​
77 const destroyRef = inject(DestroyRef)
78 const injectedClient = inject(QueryClient, { optional: true })
79 const options = inject(DEVTOOLS_OPTIONS)
80 const client = resolveOption(options.client) ?? injectedClient
81​
82 if (!client) throw new Error('No QueryClient found')
83​
84 const devtools = new TanstackQueryDevtools({
85 client,
86 queryFlavor: 'Angular Query',
87 version: '5',
88 onlineManager,
89 buttonPosition: resolveOption(options.buttonPosition),
90 position: resolveOption(options.position),
91 initialIsOpen: resolveOption(options.initialIsOpen),
92 errorTypes: resolveOption(options.errorTypes),
93 styleNonce: options.styleNonce,
94 shadowDOMTarget: options.shadowDOMTarget,
95 hideDisabledQueries: options.hideDisabledQueries,
96 theme: resolveOption(options.theme),
97 })
98​
99 let renderCompleted = false
100 let element: HTMLElement | null = null
101​
102 const shouldMount = () => {
103 const loadDevtools = resolveOption(options.loadDevtools)
104 return typeof loadDevtools === 'boolean' ? loadDevtools : isDevMode()
105 }
106​
107 const mount = () => {
108 if (element || !renderCompleted || !shouldMount()) return
109​
110 element = document.body.appendChild(document.createElement('div'))
111 element.classList.add('tsqd-parent-container')
112 devtools.mount(element)
113 }
114​
115 const unmount = () => {
116 if (!element) return
117​
118 devtools.unmount()
119 element.remove()
120 element = null
121 }
122​
123 afterNextRender({
124 write: () => {
125 if (destroyRef.destroyed) return
126​
127 renderCompleted = true
128 mount()
129 destroyRef.onDestroy(unmount)
130 },
131 })
132​
133 afterRenderEffect({
134 write: () => {
135 if (!renderCompleted) return
136 shouldMount() ? mount() : unmount()
137 },
138 })
139​
140 const registerOptionEffect = <T>(
141 option: T | Signal<T | undefined> | undefined,
142 update: (value: T | undefined) => void,
143 ) => {
144 if (!isSignal(option)) return
145 afterRenderEffect({
146 write: () => {
147 update(option())
148 },
149 })
150 }
151​
152 registerOptionEffect(options.client, (value) => {
153 devtools.setClient(value ?? injectedClient!)
154 })
155 registerOptionEffect(options.buttonPosition, (value) => {
156 devtools.setButtonPosition(value ?? 'bottom-right')
157 })
158 registerOptionEffect(options.position, (value) => {
159 devtools.setPosition(value ?? 'bottom')
160 })
161 registerOptionEffect(options.initialIsOpen, (value) => {
162 devtools.setInitialIsOpen(value ?? false)
163 })
164 registerOptionEffect(options.errorTypes, (value) => {
165 devtools.setErrorTypes(value ?? [])
166 })
167 registerOptionEffect(options.theme, (value) => {
168 devtools.setTheme(value)
169 })
170 }),
171 ]),
172 )