Open History to see the last commit
1import {
2 DestroyRef,
3 Injector,
4 PLATFORM_ID,
5 assertInInjectionContext,
6 computed,
7 effect,
8 inject,
9 runInInjectionContext,
10 untracked,
11} from '@angular/core'
12import { QueryClient, onlineManager } from '@tanstack/query-core'
13import { isPlatformBrowser } from '@angular/common'
14import type { TanstackQueryDevtoolsPanel } from '@tanstack/query-devtools'
15import type {
16 DevtoolsPanelOptions,
17 InjectDevtoolsPanel,
18 InjectDevtoolsPanelOptions,
19} from './types'
20β
21/**
22 * Inject a TanStack Query devtools panel and render it in the DOM.
23 *
24 * Devtools panel allows programmatic control over the devtools, for example if
25 * you want to render the devtools as part of your own devtools.
26 *
27 * Consider `withDevtools` instead if you don't need this.
28 *
29 * @param injectDevtoolsPanelFn - A function that returns devtools panel
30 * options.
31 * @param options - Additional configuration
32 * @returns DevtoolsPanelRef
33 * @see https://tanstack.com/query/v5/docs/framework/angular/devtools
34 */
35export const injectDevtoolsPanel: InjectDevtoolsPanel = (
36 injectDevtoolsPanelFn: () => DevtoolsPanelOptions,
37 options?: InjectDevtoolsPanelOptions,
38) => {
39 !options?.injector && assertInInjectionContext(injectDevtoolsPanel)
40 const currentInjector = options?.injector ?? inject(Injector)
41β
42 return runInInjectionContext(currentInjector, () => {
43 const destroyRef = inject(DestroyRef)
44 const isBrowser = isPlatformBrowser(inject(PLATFORM_ID))
45 const injectedClient = inject(QueryClient, { optional: true })
46β
47 const queryOptions = computed(injectDevtoolsPanelFn)
48 let devtools: TanstackQueryDevtoolsPanel | null = null
49β
50 const destroy = () => {
51 devtools?.unmount()
52 devtools = null
53 }
54β
55 if (!isBrowser)
56 return {
57 destroy,
58 }
59β
60 effect(() => {
61 const {
62 client = injectedClient,
63 errorTypes = [],
64 styleNonce,
65 shadowDOMTarget,
66 onClose,
67 hostElement,
68 } = queryOptions()
69β
70 untracked(() => {
71 if (!client) throw new Error('No QueryClient found')
72 if (!devtools && hostElement) {
73 import('@tanstack/query-devtools')
74 .then((queryDevtools) => {
75 devtools = new queryDevtools.TanstackQueryDevtoolsPanel({
76 client,
77 queryFlavor: 'Angular Query',
78 version: '5',
79 buttonPosition: 'bottom-left',
80 position: 'bottom',
81 initialIsOpen: true,
82 errorTypes,
83 styleNonce,
84 shadowDOMTarget,
85 onClose,
86 onlineManager,
87 })
88 devtools.mount(hostElement.nativeElement)
89 })
90 .catch((error) => {
91 console.error(
92 'Install @tanstack/query-devtools or reinstall without --omit=optional.',
93 error,
94 )
95 })
96 } else if (devtools && hostElement) {
97 devtools.setClient(client)
98 devtools.setErrorTypes(errorTypes)
99 onClose && devtools.setOnClose(onClose)
100 } else if (devtools && !hostElement) {
101 destroy()
102 }
103 })
104 })
105β
106 destroyRef.onDestroy(destroy)
107β
108 return {
109 destroy,
110 }
111 })
112}