grafana/public/app/features/plugins/extensions/usePluginComponent.tsx
Erik Sundell b648ce3acf
Plugin extensions: Introduce new registry for added components (#91877)
* add added component registry

* fix broken test

* add tests for usePluginComponents hook

* readd expose components

* add type assertion exceptions to betterer results

* use new addedComponent registry in legacy endpoints

* remove unused code

* cleanup

* revert test code

* remove commented code

* wrap in try catch

* pr feedback
2024-08-27 11:14:04 +02:00

34 lines
1.1 KiB
TypeScript

import { useMemo } from 'react';
import { useObservable } from 'react-use';
import { UsePluginComponentResult } from '@grafana/runtime';
import { ExposedComponentsRegistry } from './registry/ExposedComponentsRegistry';
import { wrapWithPluginContext } from './utils';
// Returns a component exposed by a plugin.
// (Exposed components can be defined in plugins by calling .exposeComponent() on the AppPlugin instance.)
export function createUsePluginComponent(registry: ExposedComponentsRegistry) {
const observableRegistry = registry.asObservable();
return function usePluginComponent<Props extends object = {}>(id: string): UsePluginComponentResult<Props> {
const registry = useObservable(observableRegistry);
return useMemo(() => {
if (!registry || !registry[id]) {
return {
isLoading: false,
component: null,
};
}
const registryItem = registry[id];
return {
isLoading: false,
component: wrapWithPluginContext(registryItem.pluginId, registryItem.component),
};
}, [id, registry]);
};
}