import { PLUGIN_CONTAINER_ID, TanStackDevtoolsCore } from '@tanstack/devtools' import { ApplicationRef, ChangeDetectionStrategy, Component, ComponentRef, DestroyRef, ElementRef, EnvironmentInjector, Injector, Type, afterNextRender, computed, createComponent, effect, inject, input, isSignal, reflectComponentType, runInInjectionContext, signal, untracked, } from '@angular/core' import type { Signal } from '@angular/core' import type { TanStackDevtoolsPlugin } from '@tanstack/devtools' import type { TanStackDevtoolsAngularFunctionalComponent, TanStackDevtoolsAngularInit, TanStackDevtoolsAngularPlugin, TanStackDevtoolsAngularPluginInputProps, TanStackDevtoolsAngularPluginRender, } from './types' @Component({ standalone: true, template: '', changeDetection: ChangeDetectionStrategy.OnPush, }) class TanStackPluginView {} @Component({ selector: 'tanstack-devtools', standalone: true, template: '', changeDetection: ChangeDetectionStrategy.OnPush, }) export class TanStackDevtools { readonly elementRef = inject>(ElementRef) readonly plugins = input([]) readonly config = input() readonly eventBusConfig = input() readonly devtools = signal(null) #componentRefs = signal>>([]) readonly #appRef = inject(ApplicationRef) readonly #injector = inject(EnvironmentInjector) readonly #viewInjector = inject(Injector) readonly #destroyRef = inject(DestroyRef) constructor() { afterNextRender(() => { const hostEl = this.elementRef.nativeElement const pluginsMap = this.getPluginsMap() const devtoolsCore = new TanStackDevtoolsCore({ config: this.config(), eventBusConfig: this.eventBusConfig(), plugins: pluginsMap, }) this.devtools.set(devtoolsCore) devtoolsCore.mount(hostEl) }) effect(() => { const devtools = this.devtools() if (!devtools) { return } const plugins = this.plugins() const config = this.config() const eventBusConfig = this.eventBusConfig() this.#destroyAllComponents() devtools.setConfig({ config, eventBusConfig, plugins: plugins?.map((p) => this.convertPlugin(p)) ?? [], }) }) this.#destroyRef.onDestroy(() => { this.#destroyAllComponents() const devtools = this.devtools() if (devtools) { devtools.unmount() this.devtools.set(null) } }) } private getPluginsMap(): Array { const plugins = this.plugins() if (!plugins) return [] return plugins.map((plugin) => this.convertPlugin(plugin)) } private convertPlugin( plugin: TanStackDevtoolsAngularPlugin, ): TanStackDevtoolsPlugin { return { id: plugin.id, defaultOpen: plugin.defaultOpen, name: typeof plugin.name === 'string' ? plugin.name : (e, theme) => { this.renderComponent(plugin.name as Type, e, { theme, ...(plugin.inputs ?? {}), }) }, render: (e, props) => { if (!plugin.render) { return } runInInjectionContext(this.#viewInjector, () => { if (isClassConstructor(plugin.render)) { this.renderComponent(plugin.render, e, { ...props, ...(plugin.inputs ?? {}), }) } else { this.#renderComponentFunction( plugin.render as Exclude< TanStackDevtoolsAngularPluginRender, Type | null >, e, { ...props, ...(plugin.inputs ?? {}), }, ) } }) }, destroy: (pluginId) => { this.#destroyComponentsInContainer(`${PLUGIN_CONTAINER_ID}-${pluginId}`) }, } } #normalizeInputs>( inputs: Signal | (() => TInputs) | TInputs, ): () => TInputs { return isSignal(inputs) ? inputs : computed(() => (typeof inputs === 'function' ? inputs() : inputs)) } async #renderComponentFunction( renderFn: Exclude | null>, container: HTMLElement, inputs: | (() => TanStackDevtoolsAngularPluginInputProps) | TanStackDevtoolsAngularPluginInputProps, ) { const result = await renderFn() if (!result) return const signalInputs = this.#normalizeInputs(inputs) if (isClassConstructor(result) || 'default' in result) { const instance = 'default' in result ? result.default : result if (!instance) return const componentRef = createComponent(instance, { environmentInjector: this.#injector, hostElement: container, }) this.#attachComponentRef(componentRef, signalInputs) } else { this.#renderFunctionalComponent(result, container, signalInputs) } } #renderFunctionalComponent( fn: TanStackDevtoolsAngularFunctionalComponent, container: HTMLElement, inputs: () => TanStackDevtoolsAngularPluginInputProps, ) { const component = createComponent(TanStackPluginView, { hostElement: container, environmentInjector: this.#injector, elementInjector: this.#viewInjector, }) this.#attachComponentRef(component, inputs) const unmount = runInInjectionContext(this.#injector, () => fn(inputs, component.location.nativeElement), ) component.onDestroy(() => unmount()) } private renderComponent( component: Type, container: HTMLElement, inputs: (() => Record) | Record, ) { const componentRef = createComponent(component, { environmentInjector: this.#injector, elementInjector: this.#viewInjector, hostElement: container, }) this.#attachComponentRef(componentRef, this.#normalizeInputs(inputs)) } #attachComponentRef( componentRef: ComponentRef, inputs: () => Record, ) { const mirror = reflectComponentType(componentRef.componentType) if (!mirror) { throw new Error( `[@tanstack-devtools/angular] The provided type is not a component`, ) } effect( () => { const latestInputs = inputs() for (const input of mirror.inputs) { if (input.propName in latestInputs) { componentRef.setInput(input.propName, latestInputs[input.propName]) } } }, { injector: componentRef.injector }, ) this.#appRef.attachView(componentRef.hostView) componentRef.changeDetectorRef.detectChanges() this.#componentRefs.update((refs) => [...refs, componentRef]) } #destroyComponentsInContainer(containerId: string) { this.#componentRefs.update((refs) => refs.filter((ref) => { const el = ref.location.nativeElement as HTMLElement if (el.id === containerId) { ref.destroy() this.#appRef.detachView(ref.hostView) return false } return true }), ) } #destroyAllComponents() { const refs = untracked(this.#componentRefs) for (const ref of refs) { this.#appRef.detachView(ref.hostView) ref.destroy() } this.#componentRefs.set([]) } } function isClassConstructor( o: unknown, ): o is new (...args: Array) => T { return typeof o === 'function' && !!o.prototype && !!o.prototype.constructor }