Open History to see the last commit
1import { PLUGIN_CONTAINER_ID, TanStackDevtoolsCore } from '@tanstack/devtools'
2import {
3 ApplicationRef,
4 ChangeDetectionStrategy,
5 Component,
6 ComponentRef,
7 DestroyRef,
8 ElementRef,
9 EnvironmentInjector,
10 Injector,
11 Type,
12 afterNextRender,
13 computed,
14 createComponent,
15 effect,
16 inject,
17 input,
18 isSignal,
19 reflectComponentType,
20 runInInjectionContext,
21 signal,
22 untracked,
23} from '@angular/core'
24import type { Signal } from '@angular/core'
25import type { TanStackDevtoolsPlugin } from '@tanstack/devtools'
26import type {
27 TanStackDevtoolsAngularFunctionalComponent,
28 TanStackDevtoolsAngularInit,
29 TanStackDevtoolsAngularPlugin,
30 TanStackDevtoolsAngularPluginInputProps,
31 TanStackDevtoolsAngularPluginRender,
32} from './types'
33β
34@Component({
35 standalone: true,
36 template: '<ng-content></ng-content>',
37 changeDetection: ChangeDetectionStrategy.OnPush,
38})
39class TanStackPluginView {}
40β
41@Component({
42 selector: 'tanstack-devtools',
43 standalone: true,
44 template: '<ng-content/>',
45 changeDetection: ChangeDetectionStrategy.OnPush,
46})
47export class TanStackDevtools {
48 readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef)
49β
50 readonly plugins = input<TanStackDevtoolsAngularInit['plugins']>([])
51 readonly config = input<TanStackDevtoolsAngularInit['config']>()
52 readonly eventBusConfig =
53 input<TanStackDevtoolsAngularInit['eventBusConfig']>()
54β
55 readonly devtools = signal<TanStackDevtoolsCore | null>(null)
56 #componentRefs = signal<Array<ComponentRef<any>>>([])
57β
58 readonly #appRef = inject(ApplicationRef)
59 readonly #injector = inject(EnvironmentInjector)
60 readonly #viewInjector = inject(Injector)
61 readonly #destroyRef = inject(DestroyRef)
62β
63 constructor() {
64 afterNextRender(() => {
65 const hostEl = this.elementRef.nativeElement
66β
67 const pluginsMap = this.getPluginsMap()
68β
69 const devtoolsCore = new TanStackDevtoolsCore({
70 config: this.config(),
71 eventBusConfig: this.eventBusConfig(),
72 plugins: pluginsMap,
73 })
74β
75 this.devtools.set(devtoolsCore)
76β
77 devtoolsCore.mount(hostEl)
78 })
79β
80 effect(() => {
81 const devtools = this.devtools()
82 if (!devtools) {
83 return
84 }
85β
86 const plugins = this.plugins()
87 const config = this.config()
88 const eventBusConfig = this.eventBusConfig()
89β
90 this.#destroyAllComponents()
91β
92 devtools.setConfig({
93 config,
94 eventBusConfig,
95 plugins: plugins?.map((p) => this.convertPlugin(p)) ?? [],
96 })
97 })
98β
99 this.#destroyRef.onDestroy(() => {
100 this.#destroyAllComponents()
101 const devtools = this.devtools()
102 if (devtools) {
103 devtools.unmount()
104 this.devtools.set(null)
105 }
106 })
107 }
108β
109 private getPluginsMap(): Array<TanStackDevtoolsPlugin> {
110 const plugins = this.plugins()
111 if (!plugins) return []
112β
113 return plugins.map((plugin) => this.convertPlugin(plugin))
114 }
115β
116 private convertPlugin(
117 plugin: TanStackDevtoolsAngularPlugin,
118 ): TanStackDevtoolsPlugin {
119 return {
120 id: plugin.id,
121 defaultOpen: plugin.defaultOpen,
122 name:
123 typeof plugin.name === 'string'
124 ? plugin.name
125 : (e, theme) => {
126 this.renderComponent(plugin.name as Type<any>, e, {
127 theme,
128 ...(plugin.inputs ?? {}),
129 })
130 },
131 render: (e, props) => {
132 if (!plugin.render) {
133 return
134 }
135β
136 runInInjectionContext(this.#viewInjector, () => {
137 if (isClassConstructor<unknown>(plugin.render)) {
138 this.renderComponent(plugin.render, e, {
139 ...props,
140 ...(plugin.inputs ?? {}),
141 })
142 } else {
143 this.#renderComponentFunction(
144 plugin.render as Exclude<
145 TanStackDevtoolsAngularPluginRender,
146 Type<any> | null
147 >,
148 e,
149 {
150 ...props,
151 ...(plugin.inputs ?? {}),
152 },
153 )
154 }
155 })
156 },
157 destroy: (pluginId) => {
158 this.#destroyComponentsInContainer(`${PLUGIN_CONTAINER_ID}-${pluginId}`)
159 },
160 }
161 }
162β
163 #normalizeInputs<TInputs extends Record<string, any>>(
164 inputs: Signal<TInputs> | (() => TInputs) | TInputs,
165 ): () => TInputs {
166 return isSignal(inputs)
167 ? inputs
168 : computed(() => (typeof inputs === 'function' ? inputs() : inputs))
169 }
170β
171 async #renderComponentFunction(
172 renderFn: Exclude<TanStackDevtoolsAngularPluginRender, Type<any> | null>,
173 container: HTMLElement,
174 inputs:
175 | (() => TanStackDevtoolsAngularPluginInputProps)
176 | TanStackDevtoolsAngularPluginInputProps,
177 ) {
178 const result = await renderFn()
179 if (!result) return
180β
181 const signalInputs = this.#normalizeInputs(inputs)
182β
183 if (isClassConstructor(result) || 'default' in result) {
184 const instance = 'default' in result ? result.default : result
185 if (!instance) return
186 const componentRef = createComponent(instance, {
187 environmentInjector: this.#injector,
188 hostElement: container,
189 })
190 this.#attachComponentRef(componentRef, signalInputs)
191 } else {
192 this.#renderFunctionalComponent(result, container, signalInputs)
193 }
194 }
195β
196 #renderFunctionalComponent(
197 fn: TanStackDevtoolsAngularFunctionalComponent,
198 container: HTMLElement,
199 inputs: () => TanStackDevtoolsAngularPluginInputProps,
200 ) {
201 const component = createComponent(TanStackPluginView, {
202 hostElement: container,
203 environmentInjector: this.#injector,
204 elementInjector: this.#viewInjector,
205 })
206 this.#attachComponentRef(component, inputs)
207 const unmount = runInInjectionContext(this.#injector, () =>
208 fn(inputs, component.location.nativeElement),
209 )
210 component.onDestroy(() => unmount())
211 }
212β
213 private renderComponent(
214 component: Type<any>,
215 container: HTMLElement,
216 inputs: (() => Record<string, unknown>) | Record<string, unknown>,
217 ) {
218 const componentRef = createComponent(component, {
219 environmentInjector: this.#injector,
220 elementInjector: this.#viewInjector,
221 hostElement: container,
222 })
223 this.#attachComponentRef(componentRef, this.#normalizeInputs(inputs))
224 }
225β
226 #attachComponentRef(
227 componentRef: ComponentRef<any>,
228 inputs: () => Record<string, unknown>,
229 ) {
230 const mirror = reflectComponentType(componentRef.componentType)
231 if (!mirror) {
232 throw new Error(
233 `[@tanstack-devtools/angular] The provided type is not a component`,
234 )
235 }
236β
237 effect(
238 () => {
239 const latestInputs = inputs()
240 for (const input of mirror.inputs) {
241 if (input.propName in latestInputs) {
242 componentRef.setInput(input.propName, latestInputs[input.propName])
243 }
244 }
245 },
246 { injector: componentRef.injector },
247 )
248β
249 this.#appRef.attachView(componentRef.hostView)
250 componentRef.changeDetectorRef.detectChanges()
251 this.#componentRefs.update((refs) => [...refs, componentRef])
252 }
253β
254 #destroyComponentsInContainer(containerId: string) {
255 this.#componentRefs.update((refs) =>
256 refs.filter((ref) => {
257 const el = ref.location.nativeElement as HTMLElement
258 if (el.id === containerId) {
259 ref.destroy()
260 this.#appRef.detachView(ref.hostView)
261 return false
262 }
263 return true
264 }),
265 )
266 }
267β
268 #destroyAllComponents() {
269 const refs = untracked(this.#componentRefs)
270 for (const ref of refs) {
271 this.#appRef.detachView(ref.hostView)
272 ref.destroy()
273 }
274 this.#componentRefs.set([])
275 }
276}
277β
278function isClassConstructor<T>(
279 o: unknown,
280): o is new (...args: Array<any>) => T {
281 return typeof o === 'function' && !!o.prototype && !!o.prototype.constructor
282}