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

with-devtools.ts

165 lines5.3 KB

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